PageSourceSearch

https://psicomeet.com.br/assets/index-BgF4lzZw.js

js psicomeet.com.br collected 2026-10-06 04:38:24 UTC 2,691,482 bytes, 5,057 lines download raw bytes

1var h6=Object.defineProperty;var sT=Hn=>{throw TypeError(Hn)};var d6=(Hn,ur,vr)=>ur in Hn?h6(Hn,ur,{enumerable:!0,configurable:!0,writable:!0,value:vr}):Hn[ur]=vr;var aT=(Hn,ur,vr)=>d6(Hn,typeof ur!="symbol"?ur+"":ur,vr),Kx=(Hn,ur,vr)=>ur.has(Hn)||sT("Cannot "+vr);var mo=(Hn,ur,vr)=>(Kx(Hn,ur,"read from private field"),vr?vr.call(Hn):ur.get(Hn)),qx=(Hn,ur,vr)=>ur.has(Hn)?sT("Cannot add the same private member more than once"):ur instanceof WeakSet?ur.add(Hn):ur.set(Hn,vr),Iy=(Hn,ur,vr,_a)=>(Kx(Hn,ur,"write to private field"),_a?_a.call(Hn,vr):ur.set(Hn,vr),vr),Xx=(Hn,ur,vr)=>(Kx(Hn,ur,"access private method"),vr);import{g as p6,c as f6}from"./agora-rtc-vendor-CXiD3fib.js";function m6(Hn,ur){for(var vr=0;vr<ur.length;vr++){const _a=ur[vr];if(typeof _a!="string"&&!Array.isArray(_a)){for(const es in _a)if(es!=="default"&&!(es in Hn)){const Et=Object.getOwnPropertyDescriptor(_a,es);Et&&Object.defineProperty(Hn,es,Et.get?Et:{enumerable:!0,get:()=>_a[es]})}}}return Object.freeze(Object.defineProperty(Hn,Symbol.toStringTag,{value:"Module"}))}var iT={exports:{}};/*! For license information please see index.js.LICENSE.txt */(function(Hn,ur){(function(vr,_a){Hn.exports=_a()})(typeof self<"u"?self:f6,()=>(()=>{var vr={31:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K=this,H="";K.next=function(){var pe=K.x^K.x>>>2;return K.x=K.y,K.y=K.z,K.z=K.w,K.w=K.v,(K.d=K.d+362437|0)+(K.v=K.v^K.v<<4^pe^pe<<1)|0},K.x=0,K.y=0,K.z=0,K.w=0,K.v=0,ke===(0|ke)?K.x=ke:H+=ke;for(var ie=0;ie<H.length+64;ie++)K.x^=0|H.charCodeAt(ie),ie==H.length&&(K.d=K.x<<10^K.x>>>4),K.next()}function ct(ke,K){return K.x=ke.x,K.y=ke.y,K.z=ke.z,K.w=ke.w,K.v=ke.v,K.d=ke.d,K}function Te(ke,K){var H=new Nt(ke),ie=K&&K.state,pe=function(){return(H.next()>>>0)/4294967296};return pe.double=function(){do var Se=((H.next()>>>11)+(H.next()>>>0)/4294967296)/2097152;while(Se===0);return Se},pe.int32=H.next,pe.quick=pe,ie&&(typeof ie=="object"&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.xorwow=Te})(0,Et=Z.nmd(Et),Z.amdD)},45:function(Et,ye,Z){var Xe,Vt=this&&this.__createBinding||(Object.create?function(H,ie,pe,Se){Se===void 0&&(Se=pe);var Qe=Object.getOwnPropertyDescriptor(ie,pe);Qe&&!("get"in Qe?!ie.__esModule:Qe.writable||Qe.configurable)||(Qe={enumerable:!0,get:function(){return ie[pe]}}),Object.defineProperty(H,Se,Qe)}:function(H,ie,pe,Se){Se===void 0&&(Se=pe),H[Se]=ie[pe]}),ht=this&&this.__setModuleDefault||(Object.create?function(H,ie){Object.defineProperty(H,"default",{enumerable:!0,value:ie})}:function(H,ie){H.default=ie}),Nt=this&&this.__importStar||(Xe=function(H){return Xe=Object.getOwnPropertyNames||function(ie){var pe=[];for(var Se in ie)Object.prototype.hasOwnProperty.call(ie,Se)&&(pe[pe.length]=Se);return pe},Xe(H)},function(H){if(H&&H.__esModule)return H;var ie={};if(H!=null)for(var pe=Xe(H),Se=0;Se<pe.length;Se++)pe[Se]!=="default"&&Vt(ie,H,pe[Se]);return ht(ie,H),ie}),ct=this&&this.__awaiter||function(H,ie,pe,Se){return new(pe||(pe=Promise))(function(Qe,Ke){function de(Ee){try{tt(Se.next(Ee))}catch(Re){Ke(Re)}}function Fe(Ee){try{tt(Se.throw(Ee))}catch(Re){Ke(Re)}}function tt(Ee){var Re;Ee.done?Qe(Ee.value):(Re=Ee.value,Re instanceof pe?Re:new pe(function(pt){pt(Re)})).then(de,Fe)}tt((Se=Se.apply(H,ie||[])).next())})},Te=this&&this.__generator||function(H,ie){var pe,Se,Qe,Ke={label:0,sent:function(){if(1&Qe[0])throw Qe[1];return Qe[1]},trys:[],ops:[]},de=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return de.next=Fe(0),de.throw=Fe(1),de.return=Fe(2),typeof Symbol=="function"&&(de[Symbol.iterator]=function(){return this}),de;function Fe(tt){return function(Ee){return function(Re){if(pe)throw new TypeError("Generator is already executing.");for(;de&&(de=0,Re[0]&&(Ke=0)),Ke;)try{if(pe=1,Se&&(Qe=2&Re[0]?Se.return:Re[0]?Se.throw||((Qe=Se.return)&&Qe.call(Se),0):Se.next)&&!(Qe=Qe.call(Se,Re[1])).done)return Qe;switch(Se=0,Qe&&(Re=[2&Re[0],Qe.value]),Re[0]){case 0:case 1:Qe=Re;break;case 4:return Ke.label++,{value:Re[1],done:!1};case 5:Ke.label++,Se=Re[1],Re=[0];continue;case 7:Re=Ke.ops.pop(),Ke.trys.pop();continue;default:if(!((Qe=(Qe=Ke.trys).length>0&&Qe[Qe.length-1])||Re[0]!==6&&Re[0]!==2)){Ke=0;continue}if(Re[0]===3&&(!Qe||Re[1]>Qe[0]&&Re[1]<Qe[3])){Ke.label=Re[1];break}if(Re[0]===6&&Ke.label<Qe[1]){Ke.label=Qe[1],Qe=Re;break}if(Qe&&Ke.label<Qe[2]){Ke.label=Qe[2],Ke.ops.push(Re);break}Qe[2]&&Ke.ops.pop(),Ke.trys.pop();continue}Re=ie.call(H,Ke)}catch(pt){Re=[6,pt],Se=0}finally{pe=Qe=0}if(5&Re[0])throw Re[1];return{value:Re[0]?Re[1]:void 0,done:!0}}([tt,Ee])}}};
1Object.defineProperty(ye,"__esModule",{value:!0});var ke=Nt(Z(951)),K=function(){function H(){this.model=null}return H.prototype.loadModel=function(){return ct(this,void 0,void 0,function(){var ie,pe,Se;return Te(this,function(Qe){switch(Qe.label){case 0:ie="".concat(self.location.origin,"/web/model.json"),Qe.label=1;case 1:return Qe.trys.push([1,3,,4]),pe=this,[4,ke.loadLayersModel(ie)];case 2:return pe.model=Qe.sent(),console.log("✅ BlazeGaze model loaded successfully"),[3,4];case 3:throw Se=Qe.sent(),console.error("❌ Error loading BlazeGaze model from path:",ie),console.error(Se),Se;case 4:return this.model.getLayer("cnn_encoder").trainable=!1,[2]}})})},H.prototype.predict=function(ie,pe,Se){if(!this.model)throw new Error("Model not loaded. Call loadModel() first.");var Qe=[ie,pe,Se],Ke=this.model.predict(Qe);return Array.isArray(Ke)?Ke[0]:Ke},H}();ye.default=K},67:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K=this;K.next=function(){var H,ie,pe=K.x,Se=K.i;return H=pe[Se],ie=(H^=H>>>7)^H<<24,ie^=(H=pe[Se+1&7])^H>>>10,ie^=(H=pe[Se+3&7])^H>>>3,ie^=(H=pe[Se+4&7])^H<<7,H=pe[Se+7&7],ie^=(H^=H<<13)^H<<9,pe[Se]=ie,K.i=Se+1&7,ie},function(H,ie){var pe,Se=[];if(ie===(0|ie))Se[0]=ie;else for(ie=""+ie,pe=0;pe<ie.length;++pe)Se[7&pe]=Se[7&pe]<<15^ie.charCodeAt(pe)+Se[pe+1&7]<<13;for(;Se.length<8;)Se.push(0);for(pe=0;pe<8&&Se[pe]===0;++pe);for(pe==8?Se[7]=-1:Se[pe],H.x=Se,H.i=0,pe=256;pe>0;--pe)H.next()}(K,ke)}function ct(ke,K){return K.x=ke.x.slice(),K.i=ke.i,K}function Te(ke,K){ke==null&&(ke=+new Date);var H=new Nt(ke),ie=K&&K.state,pe=function(){return(H.next()>>>0)/4294967296};return pe.double=function(){do var Se=((H.next()>>>11)+(H.next()>>>0)/4294967296)/2097152;while(Se===0);return Se},pe.int32=H.next,pe.quick=pe,ie&&(ie.x&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.xorshift7=Te})(0,Et=Z.nmd(Et),Z.amdD)},108:()=>{},156:function(Et,ye,Z){var Xe=this&&this.__importDefault||function(ke){return ke&&ke.__esModule?ke:{default:ke}};Object.defineProperty(ye,"__esModule",{value:!0}),ye.BlazeGaze=ye.FaceLandmarkerClient=ye.WebcamClient=ye.WebEyeTrack=ye.WebEyeTrackProxy=void 0;var Vt=Xe(Z(382));ye.WebEyeTrack=Vt.default;var ht=Xe(Z(248));ye.WebEyeTrackProxy=ht.default;var Nt=Xe(Z(396));ye.WebcamClient=Nt.default;var ct=Xe(Z(743));ye.FaceLandmarkerClient=ct.default;var Te=Xe(Z(45));ye.BlazeGaze=Te.default},180:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K,H=this,ie=(K=4022871197,function(pe){pe=String(pe);for(var Se=0;Se<pe.length;Se++){var Qe=.02519603282416938*(K+=pe.charCodeAt(Se));Qe-=K=Qe>>>0,K=(Qe*=K)>>>0,K+=4294967296*(Qe-=K)}return 23283064365386963e-26*(K>>>0)});H.next=function(){var pe=2091639*H.s0+23283064365386963e-26*H.c;return H.s0=H.s1,H.s1=H.s2,H.s2=pe-(H.c=0|pe)},H.c=1,H.s0=ie(" "),H.s1=ie(" "),H.s2=ie(" "),H.s0-=ie(ke),H.s0<0&&(H.s0+=1),H.s1-=ie(ke),H.s1<0&&(H.s1+=1),H.s2-=ie(ke),H.s2<0&&(H.s2+=1),ie=null}function ct(ke,K){return K.c=ke.c,K.s0=ke.s0,K.s1=ke.s1,K.s2=ke.s2,K}function Te(ke,K){var H=new Nt(ke),ie=K&&K.state,pe=H.next;return pe.int32=function(){return 4294967296*H.next()|0},pe.double=function(){return pe()+11102230246251565e-32*(2097152*pe()|0)},pe.quick=pe,ie&&(typeof ie=="object"&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.alea=Te})(0,Et=Z.nmd(Et),Z.amdD)},181:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K=this,H="";K.x=0,K.y=0,K.z=0,K.w=0,K.next=function(){var pe=K.x^K.x<<11;return K.x=K.y,K.y=K.z,K.z=K.w,K.w^=K.w>>>19^pe^pe>>>8},ke===(0|ke)?K.x=ke:H+=ke;for(var ie=0;ie<H.length+64;ie++)K.x^=0|H.charCodeAt(ie),K.next()}function ct(ke,K){return K.x=ke.x,K.y=ke.y,K.z=ke.z,K.w=ke.w,K}function Te(ke,K){var H=new Nt(ke),ie=K&&K.state,pe=function(){return(H.next()>>>0)/4294967296};return pe.double=function(){do var Se=((H.next()>>>11)+(H.next()>>>0)/4294967296)/2097152;while(Se===0);return Se},pe.int32=H.next,pe.quick=pe,ie&&(typeof ie=="object"&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.xor128=Te})(0,Et=Z.nmd(Et),Z.amdD)},234:()=>{},248:function(Et,ye,Z){var Xe=this&&this.__awaiter||function(ct,Te,ke,K){return new(ke||(ke=Promise))(function(H,ie){function pe(Ke){try{Qe(K.next(Ke))}catch(de){ie(de)}}function Se(Ke){try{Qe(K.throw(Ke))}catch(de){ie(de)}}function Qe(Ke){var de;Ke.done?H(Ke.value):(de=Ke.value,de instanceof ke?de:new ke(function(Fe){Fe(de)})).then(pe,Se)}Qe((K=K.apply(ct,Te||[])).next())})},Vt=this&&this.__generator||function(ct,Te){var ke,K,H,ie={label:0,sent:function(){if(1&H[0])throw H[1];return H[1]},trys:[],ops:[]},pe=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return pe.next=Se(0),pe.throw=Se(1),pe.return=Se(2),typeof Symbol=="function"&&(pe[Symbol.iterator]=function(){return this}),pe;function Se(Qe){return function(Ke){return function(de){if(ke)throw new TypeError("Generator is already executing.");for(;pe&&(pe=0,de[0]&&(ie=0)),ie;)try{if(ke=1,K&&(H=2&de[0]?K.return:de[0]?K.throw||((H=K.return)&&H.call(K),0):K.next)&&!(H=H.call(K,de[1])).done)return H;switch(K=0,H&&(de=[2&de[0],H.value]),de[0]){case 0:case 1:H=de;break;case 4:return ie.label++,{value:de[1],done:!1};case 5:ie.label++,K=de[1],de=[0];continue;case 7:de=ie.ops.pop(),ie.trys.pop();continue;default:if(!((H=(H=ie.trys).length>0&&H[H.length-1])||de[0]!==6&&de[0]!==2)){ie=0;continue}if(de[0]===3&&(!H||de[1]>H[0]&&de[1]<H[3])){ie.label=de[1];break}if(de[0]===6&&ie.label<H[1]){ie.label=H[1],H=de;break}if(H&&ie.label<H[2]){ie.label=H[2],ie.ops.push(de);break}H[2]&&ie.ops.pop(),ie.trys.pop();continue}de=Te.call(ct,ie)}catch(Fe){de=[6,Fe],K=0}finally{ke=H=0}if(5&de[0])throw de[1];return{value:de[0]?de[1]:void 0,done:!0}}([Qe,Ke])}}},ht=this&&this.__importDefault||function(ct){return ct&&ct.__esMo
1dule?ct:{default:ct}};Object.defineProperty(ye,"__esModule",{value:!0});var Nt=ht(Z(983));ye.default=function(ct){var Te=this;this.status="idle",this.onGazeResults=function(){console.warn("onGazeResults callback not set")},this.worker=new Nt.default,console.log("WebEyeTrackProxy worker initialized"),this.worker.onmessage=function(ke){switch(ke.data.type){case"ready":console.log("[WebEyeTrackProxy] Worker is ready"),ct.startWebcam(function(H,ie){return Xe(Te,void 0,void 0,function(){return Vt(this,function(pe){return this.status==="idle"&&this.worker.postMessage({type:"step",payload:{frame:H,timestamp:ie}}),[2]})})});break;case"stepResult":var K=ke.data.result;Te.onGazeResults(K);break;case"statusUpdate":Te.status=ke.data.status;break;default:console.warn("[WebEyeTrackProxy] Unknown message type: ".concat(ke.data.type))}},this.worker.postMessage({type:"init"}),window.addEventListener("click",function(ke){var K=ke.clientX/window.innerWidth-.5,H=ke.clientY/window.innerHeight-.5;console.log("[WebEyeTrackProxy] Click at (".concat(K,", ").concat(H,")")),Te.worker.postMessage({type:"click",payload:{x:K,y:H}})})}},298:(Et,ye,Z)=>{Object.defineProperty(ye,"__esModule",{value:!0}),ye.safeSVD=function(Vt){var ht=console.warn;console.warn=function(){for(var ct=[],Te=0;Te<arguments.length;Te++)ct[Te]=arguments[Te];var ke=ct[0];typeof ke=="string"&&ke.includes("autoTranspose")||ht.apply(console,ct)};var Nt=new Xe.SVD(Vt,{autoTranspose:!1});return console.warn=ht,Nt};var Xe=Z(673)},382:function(Et,ye,Z){var Xe,Vt=this&&this.__createBinding||(Object.create?function(de,Fe,tt,Ee){Ee===void 0&&(Ee=tt);var Re=Object.getOwnPropertyDescriptor(Fe,tt);Re&&!("get"in Re?!Fe.__esModule:Re.writable||Re.configurable)||(Re={enumerable:!0,get:function(){return Fe[tt]}}),Object.defineProperty(de,Ee,Re)}:function(de,Fe,tt,Ee){Ee===void 0&&(Ee=tt),de[Ee]=Fe[tt]}),ht=this&&this.__setModuleDefault||(Object.create?function(de,Fe){Object.defineProperty(de,"default",{enumerable:!0,value:Fe})}:function(de,Fe){de.default=Fe}),Nt=this&&this.__importStar||(Xe=function(de){return Xe=Object.getOwnPropertyNames||function(Fe){var tt=[];for(var Ee in Fe)Object.prototype.hasOwnProperty.call(Fe,Ee)&&(tt[tt.length]=Ee);return tt},Xe(de)},function(de){if(de&&de.__esModule)return de;var Fe={};if(de!=null)for(var tt=Xe(de),Ee=0;Ee<tt.length;Ee++)tt[Ee]!=="default"&&Vt(Fe,de,tt[Ee]);return ht(Fe,de),Fe}),ct=this&&this.__awaiter||function(de,Fe,tt,Ee){return new(tt||(tt=Promise))(function(Re,pt){function Ne(Be){try{G(Ee.next(Be))}catch(Ze){pt(Ze)}}function Pe(Be){try{G(Ee.throw(Be))}catch(Ze){pt(Ze)}}function G(Be){var Ze;Be.done?Re(Be.value):(Ze=Be.value,Ze instanceof tt?Ze:new tt(function($t){$t(Ze)})).then(Ne,Pe)}G((Ee=Ee.apply(de,Fe||[])).next())})},Te=this&&this.__generator||function(de,Fe){var tt,Ee,Re,pt={label:0,sent:function(){if(1&Re[0])throw Re[1];return Re[1]},trys:[],ops:[]},Ne=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return Ne.next=Pe(0),Ne.throw=Pe(1),Ne.return=Pe(2),typeof Symbol=="function"&&(Ne[Symbol.iterator]=function(){return this}),Ne;function Pe(G){return function(Be){return function(Ze){if(tt)throw new TypeError("Generator is already executing.");for(;Ne&&(Ne=0,Ze[0]&&(pt=0)),pt;)try{if(tt=1,Ee&&(Re=2&Ze[0]?Ee.return:Ze[0]?Ee.throw||((Re=Ee.return)&&Re.call(Ee),0):Ee.next)&&!(Re=Re.call(Ee,Ze[1])).done)return Re;switch(Ee=0,Re&&(Ze=[2&Ze[0],Re.value]),Ze[0]){case 0:case 1:Re=Ze;break;case 4:return pt.label++,{value:Ze[1],done:!1};case 5:pt.label++,Ee=Ze[1],Ze=[0];continue;case 7:Ze=pt.ops.pop(),pt.trys.pop();continue;default:if(!((Re=(Re=pt.trys).length>0&&Re[Re.length-1])||Ze[0]!==6&&Ze[0]!==2)){pt=0;continue}if(Ze[0]===3&&(!Re||Ze[1]>Re[0]&&Ze[1]<Re[3])){pt.label=Ze[1];break}if(Ze[0]===6&&pt.label<Re[1]){pt.label=Re[1],Re=Ze;break}if(Re&&pt.label<Re[2]){pt.label=Re[2],pt.ops.push(Ze);break}Re[2]&&pt.ops.pop(),pt.trys.pop();continue}Ze=Fe.call(de,pt)}catch($t){Ze=[6,$t],Ee=0}finally{tt=Re=0}if(5&Ze[0])throw Ze[1];return{value:Ze[0]?Ze[1]:void 0,done:!0}}([G,Be])}}},ke=this&&this.__importDefault||function(de){return de&&de.__esModule?de:{default:de}};
1Object.defineProperty(ye,"__esModule",{value:!0});var K=Nt(Z(951)),H=Z(673),ie=ke(Z(45)),pe=ke(Z(743)),Se=Z(985),Qe=Z(670),Ke=function(){function de(Fe,tt){Fe===void 0&&(Fe=5),tt===void 0&&(tt=60),this.faceWidthComputed=!1,this.faceWidthCm=-1,this.perspectiveMatrixSet=!1,this.perspectiveMatrix=new H.Matrix(4,4),this.intrinsicsMatrixSet=!1,this.intrinsicsMatrix=new H.Matrix(3,3),this.affineMatrix=null,this.loaded=!1,this.latestMouseClick=null,this.latestGazeResult=null,this.calibData={supportX:[],supportY:[],timestamps:[],ptType:["calib"]},this.maxPoints=5,this.clickTTL=60,this.blazeGaze=new ie.default,this.faceLandmarkerClient=new pe.default,this.kalmanFilter=new Qe.KalmanFilter2D,this.maxPoints=Fe,this.clickTTL=tt}return de.prototype.initialize=function(){return ct(this,void 0,void 0,function(){return Te(this,function(Fe){switch(Fe.label){case 0:return[4,this.faceLandmarkerClient.initialize()];case 1:return Fe.sent(),[4,this.blazeGaze.loadModel()];case 2:return Fe.sent(),this.loaded=!0,[2]}})})},de.prototype.pruneCalibData=function(){var Fe=this;K.tidy(function(){Fe.calibData.supportX.length>Fe.maxPoints&&(Fe.calibData.supportX=Fe.calibData.supportX.slice(-Fe.maxPoints),Fe.calibData.supportY=Fe.calibData.supportY.slice(-Fe.maxPoints),Fe.calibData.timestamps=Fe.calibData.timestamps.slice(-Fe.maxPoints),Fe.calibData.ptType=Fe.calibData.ptType.slice(-Fe.maxPoints));var tt=Date.now(),Ee=1e3*Fe.clickTTL,Re=Fe.calibData.timestamps.map(function(pt,Ne){return tt-pt<=Ee||Fe.calibData.ptType[Ne]!=="click"?Ne:-1}).filter(function(pt){return pt!==-1});Fe.calibData.supportX=Re.map(function(pt){return Fe.calibData.supportX[pt]}),Fe.calibData.supportY=Re.map(function(pt){return Fe.calibData.supportY[pt]}),Fe.calibData.timestamps=Re.map(function(pt){return Fe.calibData.timestamps[pt]}),Fe.calibData.ptType=Re.map(function(pt){return Fe.calibData.ptType[pt]})})},de.prototype.handleClick=function(Fe,tt){var Ee,Re,pt;return console.log("🖱️ Global click at: (".concat(Fe,", ").concat(tt,"), ").concat(this.loaded)),this.latestMouseClick&&Date.now()-this.latestMouseClick.timestamp<1e3?(console.log("🖱️ Click ignored due to debounce"),void(this.latestMouseClick={x:Fe,y:tt,timestamp:Date.now()})):this.latestMouseClick&&Math.abs(Fe-this.latestMouseClick.x)<.05&&Math.abs(tt-this.latestMouseClick.y)<.05?(console.log("🖱️ Click ignored due to proximity to last click"),void(this.latestMouseClick={x:Fe,y:tt,timestamp:Date.now()})):(this.latestMouseClick={x:Fe,y:tt,timestamp:Date.now()},void(this.loaded&&this.latestGazeResult&&this.adapt([(Ee=this.latestGazeResult)===null||Ee===void 0?void 0:Ee.eyePatch],[(Re=this.latestGazeResult)===null||Re===void 0?void 0:Re.headVector],[(pt=this.latestGazeResult)===null||pt===void 0?void 0:pt.faceOrigin3D],[[Fe,tt]])))},de.prototype.computeFaceOrigin3D=function(Fe,tt,Ee,Re){var pt,Ne,Pe;this.faceWidthComputed===!1&&(this.faceWidthCm=(0,Se.estimateFaceWidth)(Ee),this.faceWidthComputed=!0);var G=(0,Se.faceReconstruction)(this.perspectiveMatrix,tt,Re,this.intrinsicsMatrix,this.faceWidthCm,Fe.width,Fe.height,(Pe=(Ne=(pt=this.latestGazeResult)===null||pt===void 0?void 0:pt.faceOrigin3D)===null||Ne===void 0?void 0:Ne[2])!==null&&Pe!==void 0?Pe:60),Be=(G[0],G[1]);return(0,Se.computeFaceOrigin3D)(Be)},de.prototype.prepareInput=function(Fe,tt){var Ee=Fe.width,Re=Fe.height;if(!this.perspectiveMatrixSet){var pt=Ee/Re;this.perspectiveMatrix=(0,Se.createPerspectiveMatrix)(pt),this.perspectiveMatrixSet=!0}this.intrinsicsMatrixSet||(this.intrinsicsMatrix=(0,Se.createIntrinsicsMatrix)(Ee,Re));var Ne=tt.faceLandmarks[0],Pe=Ne.map(function($t){return[Math.floor($t.x*Ee),Math.floor($t.y*Re)]}),G=(0,Se.translateMatrix)(tt.facialTransformationMatrixes[0]),Be=(0,Se.obtainEyePatch)(Fe,Pe),Ze=this.computeFaceOrigin3D(Fe,Ne.map(function($t){return[$t.x,$t.y]}),Pe,G);return[Be,(0,Se.getHeadVector)(G),Ze]},de.prototype.adapt=function(Fe,tt,Ee,Re,pt,Ne,Pe){var G=this;pt===void 0&&(pt=1),Ne===void 0&&(Ne=1e-5),Pe===void 0&&(Pe="calib"),this.pruneCalibData();var Be,Ze,$t,Wt,yn=K.train.adam(Ne,.85,.9,1e-8),Jt=function(De,Ye,rt,qe){return{supportX:{eyePatches:K.stack(De.map(function(He){return K.browser.fromPixels(He)}
1),0).toFloat().div(K.scalar(255)),headVectors:K.tensor(Ye,[Ye.length,3],"float32"),faceOrigins3D:K.tensor(rt,[rt.length,3],"float32")},supportY:K.tensor(qe,[qe.length,2],"float32")}}(Fe,tt,Ee,Re),fn=Jt.supportX,cn=Jt.supportY;if(this.calibData.supportX.push(fn),this.calibData.supportY.push(cn),this.calibData.timestamps.push(Date.now()),this.calibData.ptType.push(Pe),this.calibData.supportX.length>1?(Be=K.concat(this.calibData.supportX.map(function(De){return De.eyePatches}),0),Ze=K.concat(this.calibData.supportX.map(function(De){return De.headVectors}),0),$t=K.concat(this.calibData.supportX.map(function(De){return De.faceOrigins3D}),0),Wt=K.concat(this.calibData.supportY,0)):(Be=fn.eyePatches,Ze=fn.headVectors,$t=fn.faceOrigins3D,Wt=cn),Be.shape[0]>3){var Yn=K.tidy(function(){return G.blazeGaze.predict(Be,Ze,$t)}).arraySync(),Dn=Wt.arraySync(),zn=(0,Se.computeAffineMatrixML)(Yn,Dn);this.affineMatrix=K.tensor2d(zn,[2,3],"float32")}K.tidy(function(){for(var De=0;De<pt;De++){var Ye=K.variableGrads(function(){var He=G.blazeGaze.predict(Be,Ze,$t),At=G.affineMatrix?(0,Se.applyAffineMatrix)(G.affineMatrix,He):He;return K.losses.meanSquaredError(Wt,At).asScalar()}),rt=Ye.grads,qe=Ye.value;yn.applyGradients(rt),qe.data().then(function(He){return console.log("Loss = ".concat(He[0].toFixed(4)))})}})},de.prototype.step=function(Fe,tt){return ct(this,void 0,void 0,function(){var Ee,Re,pt,Ne,Pe,G,Be,Ze,$t,Wt,yn,Jt,fn,cn,Yn,Dn,zn,De,Ye,rt=this;return Te(this,function(qe){switch(qe.label){case 0:return Ee=performance.now(),[4,this.faceLandmarkerClient.processFrame(Fe)];case 1:return Re=qe.sent(),pt=performance.now(),Re&&Re.faceLandmarks&&Re.faceLandmarks.length!==0?(Ne=this.prepareInput(Fe,Re),Pe=Ne[0],G=Ne[1],Be=Ne[2],Ze=performance.now(),$t="open",Wt=(0,Se.computeEAR)(Re.faceLandmarks[0],"left"),yn=(0,Se.computeEAR)(Re.faceLandmarks[0],"right"),(Wt<.2||yn<.2)&&($t="closed"),$t==="closed"?[2,{facialLandmarks:Re.faceLandmarks[0],faceRt:Re.facialTransformationMatrixes[0],faceBlendshapes:Re.faceBlendshapes,eyePatch:Pe,headVector:G,faceOrigin3D:Be,metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:$t,normPog:[0,0],durations:{faceLandmarker:pt-Ee,prepareInput:Ze-pt,blazeGaze:0,kalmanFilter:0,total:Ze-Ee},timestamp:tt}]:(Jt=K.tidy(function(){var He=K.browser.fromPixels(Pe).toFloat().expandDims(0),At=He.div(K.scalar(255)),Ut=K.tensor2d(G,[1,3]),at=K.tensor2d(Be,[1,3]),Kt=rt.blazeGaze.predict(At,Ut,at);K.dispose([He,At,Ut,at]);var M=performance.now();if(rt.affineMatrix&&(Kt=(0,Se.applyAffineMatrix)(rt.affineMatrix,Kt)),!Kt||Kt.shape.length===0)throw new Error("BlazeGaze model did not return valid output");return[Kt,M]}),fn=Jt[0],cn=Jt[1],Yn=fn.arraySync(),K.dispose(fn),Dn=this.kalmanFilter.step(Yn[0]),zn=performance.now(),Dn[0]=Math.max(-.5,Math.min(.5,Dn[0])),Dn[1]=Math.max(-.5,Math.min(.5,Dn[1])),De={faceLandmarker:pt-Ee,prepareInput:Ze-pt,blazeGaze:cn-Ze,kalmanFilter:zn-cn,total:zn-Ee},Ye={facialLandmarks:Re.faceLandmarks[0],faceRt:Re.facialTransformationMatrixes[0],faceBlendshapes:Re.faceBlendshapes,eyePatch:Pe,headVector:G,faceOrigin3D:Be,metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:$t,normPog:Dn,durations:De,timestamp:tt},this.latestGazeResult=Ye,[2,Ye])):[2,{facialLandmarks:[],faceRt:{rows:0,columns:0,data:[]},faceBlendshapes:[],eyePatch:new ImageData(1,1),headVector:[0,0,0],faceOrigin3D:[0,0,0],metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:"closed",normPog:[0,0],durations:{faceLandmarker:pt-Ee,prepareInput:0,blazeGaze:0,kalmanFilter:0,total:0},timestamp:tt}]}})})},de}();ye.default=Ke},391:(Et,ye,Z)=>{var Xe=Z(180),Vt=Z(181),ht=Z(31),Nt=Z(67),ct=Z(833),Te=Z(717),ke=Z(801);ke.alea=Xe,ke.xor128=Vt,ke.xorwow=ht,ke.xorshift7=Nt,ke.xor4096=ct,ke.tychei=Te,Et.exports=ke},396:function(Et,ye,Z){var Xe=this&&this.__awaiter||function(ct,Te,ke,K){return new(ke||(ke=Promise))(function(H,ie){function pe(Ke){try{Qe(K.next(Ke))}catch(de){ie(de)}}function Se(Ke){try{Qe(K.throw(Ke))}catch(de){ie(de)}}function Qe(Ke){var de;Ke.done?H(Ke.value):(de=Ke.value,de instanceof ke?de:new ke(function(Fe){Fe(de)})).then(pe,Se)}Qe((K=K.apply(ct,Te||[])).next())})},Vt=this&&this.__generator||function(ct,Te){var ke,K,H,ie={label:0,sent:function(){if(1&H[0])throw H[1];return H[1]},trys:[],ops:[]},pe=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return pe.next=Se(0),pe.throw=Se(1),pe.return=Se(2),typeof Symbol=="function"&&(pe[Symbol.iterator]=function(){return this}),pe;function Se(Qe){return function(Ke){return function(de){if(ke)throw new TypeError("Generator is already executing.");for(;pe&&(pe=0,de[0]&&(ie=0)),ie;)try{if(ke=1,K&&(H=2&de[0]?K.return:de[0]?K.throw||((H=K.return)&&H.call(K),0):K.next)&&!(H=H.call(K,de[1])).done)return H;switch(K=0,H&&(de=[2&de[0],H.value]),de[0]){case 0:case 1:H=de;break;case 4:return ie.label++,{value:de[1],done:!1};case 5:ie.label++,K=de[1],de=[0];continue;case 7:de=ie.ops.pop(),ie.trys.pop();continue;default:if(!((H=(H=ie.trys).length>0&&H[H.length-1])||de[0]!==6&&de[0]!==2)){ie=0;continue}if(de[0]===3&&(!H||de[1]>H[0]&&de[1]<H[3])){ie.label=de[1];break}if(de[0]===6&&ie.label<H[1]){ie.label=H[1],H=de;break}if(H&&ie.label<H[2]){ie.label=H[2],ie.ops.push(de);break}H[2]&&ie.ops.pop(),ie.trys.pop();continue}de=Te.call(ct,ie)}catch(Fe){de=[6,Fe],K=0}finally{ke=H=0}if(5&de[0])throw de[1];return{value:de[0]?de[1]:void 0,done:!0}}([Qe,Ke])}}};
1Object.defineProperty(ye,"__esModule",{value:!0});var ht=Z(608),Nt=function(){function ct(Te){var ke=document.getElementById(Te);if(!ke)throw new Error("Video element with id '".concat(Te,"' not found"));this.videoElement=ke}return ct.prototype.startWebcam=function(Te){return Xe(this,void 0,void 0,function(){var ke,K,H,ie=this;return Vt(this,function(pe){switch(pe.label){case 0:return pe.trys.push([0,2,,3]),ke={video:{width:{ideal:640},height:{ideal:480},facingMode:"user"},audio:!1},K=this,[4,navigator.mediaDevices.getUserMedia(ke)];case 1:return K.stream=pe.sent(),this.videoElement.srcObject=this.stream,Te&&(this.frameCallback=Te),this.videoElement.onloadedmetadata=function(){ie.videoElement.play()},this.videoElement.addEventListener("loadeddata",function(){ie._processFrames()}),[3,3];case 2:return H=pe.sent(),console.error("Error accessing the webcam:",H),[3,3];case 3:return[2]}})})},ct.prototype.stopWebcam=function(){this.stream&&(this.stream.getTracks().forEach(function(Te){return Te.stop()}),this.stream=void 0)},ct.prototype._processFrames=function(){var Te=this,ke=function(){return Xe(Te,void 0,void 0,function(){var K;return Vt(this,function(H){switch(H.label){case 0:return!this.videoElement||this.videoElement.paused||this.videoElement.ended?[2]:(K=(0,ht.convertVideoFrameToImageData)(this.videoElement),this.frameCallback?[4,this.frameCallback(K,this.videoElement.currentTime)]:[3,2]);case 1:H.sent(),H.label=2;case 2:return requestAnimationFrame(ke),[2]}})})};requestAnimationFrame(ke)},ct}();ye.default=Nt},512:Et=>{Et.exports=function(ye,Z,Xe,Vt){var ht=self||window;try{try{var Nt;try{Nt=new ht.Blob([ye])}catch{(Nt=new(ht.BlobBuilder||ht.WebKitBlobBuilder||ht.MozBlobBuilder||ht.MSBlobBuilder)).append(ye),Nt=Nt.getBlob()}var ct=ht.URL||ht.webkitURL,Te=ct.createObjectURL(Nt),ke=new ht[Z](Te,Xe);return ct.revokeObjectURL(Te),ke}catch{return new ht[Z]("data:application/javascript,".concat(encodeURIComponent(ye)),Xe)}}catch{if(!Vt)throw Error("Inline worker is not supported");return new ht[Z](Vt,Xe)}}},530:()=>{},551:()=>{},570:Et=>{Et.exports=Z;var ye=null;try{ye=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 Z(G,Be,Ze){this.low=0|G,this.high=0|Be,this.unsigned=!!Ze}function Xe(G){return(G&&G.__isLong__)===!0}Z.prototype.__isLong__,Object.defineProperty(Z.prototype,"__isLong__",{value:!0}),Z.isLong=Xe;var Vt={},ht={};function Nt(G,Be){var Ze,$t,Wt;return Be?(Wt=0<=(G>>>=0)&&G<256)&&($t=ht[G])?$t:(Ze=Te(G,(0|G)<0?-1:0,!0),Wt&&(ht[G]=Ze),Ze):(Wt=-128<=(G|=0)&&G<128)&&($t=Vt[G])?$t:(Ze=Te(G,G<0?-1:0,!1),Wt&&(Vt[G]=Ze),Ze)}function ct(G,Be){if(isNaN(G))return Be?de:Ke;if(Be){if(G<0)return de;if(G>=pe)return pt}else{if(G<=-Se)return Ne;if(G+1>=Se)return Re}return G<0?ct(-G,Be).neg():Te(G%ie|0,G/ie|0,Be)}function Te(G,Be,Ze){return new Z(G,Be,Ze)}Z.fromInt=Nt,Z.fromNumber=ct,Z.fromBits=Te;var ke=Math.pow;function K(G,Be,Ze){if(G.length===0)throw Error("empty string");if(G==="NaN"||G==="Infinity"||G==="+Infinity"||G==="-Infinity")return Ke;if(typeof Be=="number"?(Ze=Be,Be=!1):Be=!!Be,(Ze=Ze||10)<2||36<Ze)throw RangeError("radix");var $t;if(($t=G.indexOf("-"))>0)throw Error("interior hyphen");if($t===0)return K(G.substring(1),Be,Ze).neg();for(var Wt=ct(ke(Ze,8)),yn=Ke,Jt=0;Jt<G.length;Jt+=8){var fn=Math.min(8,G.length-Jt),cn=parseInt(G.substring(Jt,Jt+fn),Ze);if(fn<8){var Yn=ct(ke(Ze,fn));yn=yn.mul(Yn).add(ct(cn))}else yn=(yn=yn.mul(Wt)).add(ct(cn))}return yn.unsigned=Be,yn}function H(G,Be){return typeof G=="number"?ct(G,Be):typeof G=="string"?K(G,Be):Te(G.low,G.high,typeof Be=="boolean"?Be:G.unsigned)}Z.fromString=K,Z.fromValue=H;var ie=4294967296,pe=ie*ie,Se=pe/2,Qe=Nt(1<<24),Ke=Nt(0);Z.ZERO=Ke;var de=Nt(0,!0);Z.UZERO=de;var Fe=Nt(1);Z.ONE=Fe;var tt=Nt(1,!0);Z.UONE=tt;var Ee=Nt(-1);Z.NEG_ONE=Ee;var Re=Te(-1,2147483647,!1);Z.MAX_VALUE=Re;var pt=Te(-1,-1,!0);Z.MAX_UNSIGNED_VALUE=pt;var Ne=Te(0,-2147483648,!1);Z.MIN_VALUE=Ne;var Pe=Z.prototype;Pe.toInt=function(){return this.unsigned?this.low>>>0:this.low},Pe.toNumber=function(){return this.unsigned?(this.high>>>0)*ie+(this.low>>>0):this.high*ie+(this.low>>>0)},Pe.toString=function(G){if((G=G||10)<2||36<G)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Ne)){var Be=ct(G),Ze=this.div(Be),$t=Ze.mul(Be).sub(this);return Ze.toString(G)+$t.toInt().toString(G)}return"-"+this.neg().toString(G)}for(var Wt=ct(ke(G,6),this.unsigned),yn=this,Jt="";;){var fn=yn.div(Wt),cn=(yn.sub(fn.mul(Wt)).toInt()>>>0).toString(G);if((yn=fn).isZero())return cn+Jt;for(;cn.length<6;)cn="0"+cn;Jt=""+cn+Jt}},Pe.getHighBits=function(){return this.high},Pe.getHighBitsUnsigned=function(){return this.high>>>0},Pe.getLowBits=function(){return this.low},Pe.getLowBitsUnsigned=function(){return this.low>>>0},Pe.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ne)?64:this.neg().getNumBitsAbs();for(var G=this.high!=0?this.high:this.low,Be=31;Be>0&&!(G&1<<Be);Be--);return this.high!=0?Be+33:Be+1},Pe.isZero=function(){return this.high===0&&this.low===0},Pe.eqz=Pe.isZero,Pe.isNegative=function(){return!this.unsigned&&this.high<0},Pe.isPositive=function(){return this.unsigned||this.high>=0},Pe.isOdd=function(){return!(1&~this.low)},Pe.isEven=function(){return!(1&this.low)},Pe.equals=function(G){return Xe(G)||(G=H(G)),(this.unsigned===G.unsigned||this.high>>>31!=1||G.high>>>31!=1)&&this.high===G.high&&this.low===G.low},Pe.eq=Pe.equals,Pe.notEquals=function(G){return!this.eq(G)},Pe.neq=Pe.notEquals,Pe.ne=Pe.notEquals,Pe.lessThan=function(G){return this.comp(G)<0},Pe.lt=Pe.lessThan,Pe.lessThanOrEqual=function(G){return this.comp(G)<=0},Pe.lte=Pe.lessThanOrEqual,Pe.le=Pe.lessThanOrEqual,Pe.greaterThan=function(G){return this.comp(G)>0},Pe.gt=Pe.greaterThan,Pe.greaterThanOrEqual=function(G){return this.comp(G)>=0},Pe.gte=Pe.greaterThanOrEqual,Pe.ge=Pe.greaterThanOrEqual,Pe.compare=function(G){if(Xe(G)||(G=H(G)),this.eq(G))return 0;var Be=this.isNegative(),Ze=G.isNegative();return Be&&!Ze?-1:!Be&&Ze?1:this.unsigned?G.high>>>0>this.high>>>0||G.high===this.high&&G.low>>>0>this.low>>>0?-1:1:this.sub(G).isNegative()?-1:1},Pe.comp=Pe.compare,Pe.negate=function(){return!this.unsigned&&this.eq(Ne)?Ne:this.not().add(Fe)},Pe.neg=Pe.negate,Pe.add=function(G){Xe(G)||(G=H(G));var Be=this.high>>>16,Ze=65535&this.high,$t=this.low>>>16,Wt=65535&this.low,yn=G.high>>>16,Jt=65535&G.high,fn=G.low>>>16,cn=0,Yn=0,Dn=0,zn=0;return Dn+=(zn+=Wt+(65535&G.low))>>>16,Yn+=(Dn+=$t+fn)>>>16,cn+=(Yn+=Ze+Jt)>>>16,cn+=Be+yn,Te((Dn&=65535)<<16|(zn&=65535),(cn&=65535)<<16|(Yn&=65535),this.unsigned)},Pe.subtract=function(G){return Xe(G)||(G=H(G)),this.add(G.neg())},Pe.sub=Pe.subtract,Pe.multiply=function(G){if(this.isZero())return Ke;if(Xe(G)||(G=H(G)),ye)return Te(ye.mul(this.low,this.high,G.low,G.high),ye.get_high(),this.unsigned);if(G.isZero())return Ke;if(this.eq(Ne))return G.isOdd()?Ne:Ke;if(G.eq(Ne))return this.isOdd()?Ne:Ke;if(this.isNegative())return G.isNegative()?this.neg().mul(G.neg()):this.neg().mul(G).neg();if(G.isNegative())return this.mul(G.neg()).neg();if(this.lt(Qe)&&G.lt(Qe))return ct(this.toNumber()*G.toNumber(),this.unsigned);var Be=this.high>>>16,Ze=65535&this.high,$t=this.low>>>16,Wt=65535&this.low,yn=G.high>>>16,Jt=65535&G.high,fn=G.low>>>16,cn=65535&G.low,Yn=0,Dn=0,zn=0,De=0;return zn+=(De+=Wt*cn)>>>16,Dn+=(zn+=$t*cn)>>>16,zn&=65535,Dn+=(zn+=Wt*fn)>>>16,Yn+=(Dn+=Ze*cn)>>>16,Dn&=65535,Yn+=(Dn+=$t*fn)>>>16,Dn&=65535,Yn+=(Dn+=Wt*Jt)>>>16,Yn+=Be*cn+Ze*fn+$t*Jt+Wt*yn,Te((zn&=65535)<<16|(De&=65535),(Yn&=65535)<<16|(Dn&=65535),this.unsigned)},Pe.mul=Pe.multiply,Pe.divide=function(G){if(Xe(G)||(G=H(G)),G.isZero())throw Error("division by zero");var Be,Ze,$t;if(ye)return this.unsigned||this.high!==-2147483648||G.low!==-1||G.high!==-1?Te((this.unsigned?ye.div_u:ye.div_s)(this.low,this.high,G.low,G.high),ye.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?de:Ke;if(this.unsigned){if(G.unsigned||(G=G.toUnsigned()),G.gt(this))return de;if(G.gt(this.shru(1)))return tt;$t=de}
1else{if(this.eq(Ne))return G.eq(Fe)||G.eq(Ee)?Ne:G.eq(Ne)?Fe:(Be=this.shr(1).div(G).shl(1)).eq(Ke)?G.isNegative()?Fe:Ee:(Ze=this.sub(G.mul(Be)),$t=Be.add(Ze.div(G)));if(G.eq(Ne))return this.unsigned?de:Ke;if(this.isNegative())return G.isNegative()?this.neg().div(G.neg()):this.neg().div(G).neg();if(G.isNegative())return this.div(G.neg()).neg();$t=Ke}for(Ze=this;Ze.gte(G);){Be=Math.max(1,Math.floor(Ze.toNumber()/G.toNumber()));for(var Wt=Math.ceil(Math.log(Be)/Math.LN2),yn=Wt<=48?1:ke(2,Wt-48),Jt=ct(Be),fn=Jt.mul(G);fn.isNegative()||fn.gt(Ze);)fn=(Jt=ct(Be-=yn,this.unsigned)).mul(G);Jt.isZero()&&(Jt=Fe),$t=$t.add(Jt),Ze=Ze.sub(fn)}return $t},Pe.div=Pe.divide,Pe.modulo=function(G){return Xe(G)||(G=H(G)),ye?Te((this.unsigned?ye.rem_u:ye.rem_s)(this.low,this.high,G.low,G.high),ye.get_high(),this.unsigned):this.sub(this.div(G).mul(G))},Pe.mod=Pe.modulo,Pe.rem=Pe.modulo,Pe.not=function(){return Te(~this.low,~this.high,this.unsigned)},Pe.and=function(G){return Xe(G)||(G=H(G)),Te(this.low&G.low,this.high&G.high,this.unsigned)},Pe.or=function(G){return Xe(G)||(G=H(G)),Te(this.low|G.low,this.high|G.high,this.unsigned)},Pe.xor=function(G){return Xe(G)||(G=H(G)),Te(this.low^G.low,this.high^G.high,this.unsigned)},Pe.shiftLeft=function(G){return Xe(G)&&(G=G.toInt()),(G&=63)==0?this:G<32?Te(this.low<<G,this.high<<G|this.low>>>32-G,this.unsigned):Te(0,this.low<<G-32,this.unsigned)},Pe.shl=Pe.shiftLeft,Pe.shiftRight=function(G){return Xe(G)&&(G=G.toInt()),(G&=63)==0?this:G<32?Te(this.low>>>G|this.high<<32-G,this.high>>G,this.unsigned):Te(this.high>>G-32,this.high>=0?0:-1,this.unsigned)},Pe.shr=Pe.shiftRight,Pe.shiftRightUnsigned=function(G){if(Xe(G)&&(G=G.toInt()),(G&=63)==0)return this;var Be=this.high;return G<32?Te(this.low>>>G|Be<<32-G,Be>>>G,this.unsigned):Te(G===32?Be:Be>>>G-32,0,this.unsigned)},Pe.shru=Pe.shiftRightUnsigned,Pe.shr_u=Pe.shiftRightUnsigned,Pe.toSigned=function(){return this.unsigned?Te(this.low,this.high,!1):this},Pe.toUnsigned=function(){return this.unsigned?this:Te(this.low,this.high,!0)},Pe.toBytes=function(G){return G?this.toBytesLE():this.toBytesBE()},Pe.toBytesLE=function(){var G=this.high,Be=this.low;return[255&Be,Be>>>8&255,Be>>>16&255,Be>>>24,255&G,G>>>8&255,G>>>16&255,G>>>24]},Pe.toBytesBE=function(){var G=this.high,Be=this.low;return[G>>>24,G>>>16&255,G>>>8&255,255&G,Be>>>24,Be>>>16&255,Be>>>8&255,255&Be]},Z.fromBytes=function(G,Be,Ze){return Ze?Z.fromBytesLE(G,Be):Z.fromBytesBE(G,Be)},Z.fromBytesLE=function(G,Be){return new Z(G[0]|G[1]<<8|G[2]<<16|G[3]<<24,G[4]|G[5]<<8|G[6]<<16|G[7]<<24,Be)},Z.fromBytesBE=function(G,Be){return new Z(G[4]<<24|G[5]<<16|G[6]<<8|G[7],G[0]<<24|G[1]<<16|G[2]<<8|G[3],Be)}},590:()=>{},608:(Et,ye)=>{Object.defineProperty(ye,"__esModule",{value:!0}),ye.convertVideoFrameToImageData=function(Z){var Xe=document.createElement("canvas");Xe.width=Z.videoWidth,Xe.height=Z.videoHeight;var Vt=Xe.getContext("2d");return Vt.drawImage(Z,0,0),Vt.getImageData(0,0,Xe.width,Xe.height)}},670:(Et,ye,Z)=>{Object.defineProperty(ye,"__esModule",{value:!0}),ye.KalmanFilter2D=void 0;var Xe=Z(673),Vt=function(){function ht(Nt,ct,Te){Nt===void 0&&(Nt=1),ct===void 0&&(ct=1e-4),Te===void 0&&(Te=.01),this.x=Xe.Matrix.zeros(4,1),this.F=new Xe.Matrix([[1,0,Nt,0],[0,1,0,Nt],[0,0,1,0],[0,0,0,1]]),this.H=new Xe.Matrix([[1,0,0,0],[0,1,0,0]]),this.R=Xe.Matrix.eye(2).mul(Te),this.Q=Xe.Matrix.eye(4).mul(ct),this.P=Xe.Matrix.eye(4)}return ht.prototype.predict=function(){return this.x=this.F.mmul(this.x),this.P=this.F.mmul(this.P).mmul(this.F.transpose()).add(this.Q),this.x.subMatrix(0,1,0,0).to1DArray()},ht.prototype.update=function(Nt){var ct=new Xe.Matrix([[Nt[0]],[Nt[1]]]).sub(this.H.mmul(this.x)),Te=this.H.mmul(this.P).mmul(this.H.transpose()).add(this.R),ke=this.P.mmul(this.H.transpose()).mmul((0,Xe.inverse)(Te));this.x=this.x.add(ke.mmul(ct));var K=Xe.Matrix.eye(4);return this.P=K.sub(ke.mmul(this.H)).mmul(this.P),this.x.subMatrix(0,1,0,0).to1DArray()},ht.prototype.step=function(Nt){return this.predict(),this.update(Nt)},ht}();ye.KalmanFilter2D=Vt},673:(Et,ye,Z)=>{var He,Yx,at;Object.defineProperty(ye,"__esModule",{value:!0});var Xe=Z(788),Vt=Z(718);const ht=" ".repeat(2),Nt=" ".repeat(4);function ct(M,S={}){const{maxRows:b=15,maxColumns:k=10,maxNumSize:E=8,padMinus:F="auto"}=S;return`${M.constructor.name} {
2${ht}[
3${Nt}${function(B,Q,te,Ce,Ae){const{rows:mt,columns:et}=B,it=Math.min(mt,Q),A=Math.min(et,te),ge=[];if(Ae==="auto"){Ae=!1;e:for(let Ve=0;Ve<it;Ve++)for(let j=0;j<A;j++)if(B.get(Ve,j)<0){Ae=!0;break e}}for(let Ve=0;Ve<it;Ve++){let j=[];for(let oe=0;oe<A;oe++)j.push(Te(B.get(Ve,oe),Ce,Ae));ge.push(`${j.join(" ")}`)}return A!==et&&(ge[ge.length-1]+=` ... ${et-te} more columns`),it!==mt&&ge.push(`... ${mt-Q} more rows`),ge.join(`
4${Nt}`)}(M,b,k,E,F)}
5${ht}]
6${ht}rows: ${M.rows}
7${ht}columns: ${M.columns}
8}`}function Te(M,S,b){return(M>=0&&b?` ${ke(M,S-1)}`:ke(M,S)).padEnd(S)}function ke(M,S){let b=M.toString();if(b.length<=S)return b;let k=M.toFixed(S);if(k.length>S&&(k=M.toFixed(Math.max(0,S-(k.length-S)))),k.length<=S&&!k.startsWith("0.000")&&!k.startsWith("-0.000"))return k;let E=M.toExponential(S);return E.length>S&&(E=M.toExponential(Math.max(0,S-(E.length-S)))),E.slice(0)}function K(M,S,b){let k=b?M.rows:M.rows-1;if(S<0||S>k)throw new RangeError("Row index out of range")}
vendor: 9,650 bytes, line 8
8function H(M,S,b){let k=b?M.columns:M.columns-1;if(S<0||S>k)throw new RangeError("Column index out of range")}function ie(M,S){if(S.to1DArray&&(S=S.to1DArray()),S.length!==M.columns)throw new RangeError("vector size must be the same as the number of columns");return S}function pe(M,S){if(S.to1DArray&&(S=S.to1DArray()),S.length!==M.rows)throw new RangeError("vector size must be the same as the number of rows");return S}function Se(M,S){if(!Xe.isAnyArray(S))throw new TypeError("row indices must be an array");for(let b=0;b<S.length;b++)if(S[b]<0||S[b]>=M.rows)throw new RangeError("row indices are out of range")}function Qe(M,S){if(!Xe.isAnyArray(S))throw new TypeError("column indices must be an array");for(let b=0;b<S.length;b++)if(S[b]<0||S[b]>=M.columns)throw new RangeError("column indices are out of range")}function Ke(M,S,b,k,E){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if(Fe("startRow",S),Fe("endRow",b),Fe("startColumn",k),Fe("endColumn",E),S>b||k>E||S<0||S>=M.rows||b<0||b>=M.rows||k<0||k>=M.columns||E<0||E>=M.columns)throw new RangeError("Submatrix indices are out of range")}function de(M,S=0){let b=[];for(let k=0;k<M;k++)b.push(S);return b}function Fe(M,S){if(typeof S!="number")throw new TypeError(`${M} must be a number`)}function tt(M){if(M.isEmpty())throw new Error("Empty matrix has no elements to index")}class Ee{static from1DArray(S,b,k){if(S*b!==k.length)throw new RangeError("data length does not match given dimensions");let E=new Ne(S,b);for(let F=0;F<S;F++)for(let B=0;B<b;B++)E.set(F,B,k[F*b+B]);return E}static rowVector(S){let b=new Ne(1,S.length);for(let k=0;k<S.length;k++)b.set(0,k,S[k]);return b}static columnVector(S){let b=new Ne(S.length,1);for(let k=0;k<S.length;k++)b.set(k,0,S[k]);return b}static zeros(S,b){return new Ne(S,b)}static ones(S,b){return new Ne(S,b).fill(1)}static rand(S,b,k={}){if(typeof k!="object")throw new TypeError("options must be an object");const{random:E=Math.random}=k;let F=new Ne(S,b);for(let B=0;B<S;B++)for(let Q=0;Q<b;Q++)F.set(B,Q,E());return F}static randInt(S,b,k={}){if(typeof k!="object")throw new TypeError("options must be an object");const{min:E=0,max:F=1e3,random:B=Math.random}=k;if(!Number.isInteger(E))throw new TypeError("min must be an integer");if(!Number.isInteger(F))throw new TypeError("max must be an integer");if(E>=F)throw new RangeError("min must be smaller than max");let Q=F-E,te=new Ne(S,b);for(let Ce=0;Ce<S;Ce++)for(let Ae=0;Ae<b;Ae++){let mt=E+Math.round(B()*Q);te.set(Ce,Ae,mt)}return te}static eye(S,b,k){b===void 0&&(b=S),k===void 0&&(k=1);let E=Math.min(S,b),F=this.zeros(S,b);for(let B=0;B<E;B++)F.set(B,B,k);return F}static diag(S,b,k){let E=S.length;b===void 0&&(b=E),k===void 0&&(k=b);let F=Math.min(E,b,k),B=this.zeros(b,k);for(let Q=0;Q<F;Q++)B.set(Q,Q,S[Q]);return B}static min(S,b){S=this.checkMatrix(S),b=this.checkMatrix(b);let k=S.rows,E=S.columns,F=new Ne(k,E);for(let B=0;B<k;B++)for(let Q=0;Q<E;Q++)F.set(B,Q,Math.min(S.get(B,Q),b.get(B,Q)));return F}static max(S,b){S=this.checkMatrix(S),b=this.checkMatrix(b);let k=S.rows,E=S.columns,F=new this(k,E);for(let B=0;B<k;B++)for(let Q=0;Q<E;Q++)F.set(B,Q,Math.max(S.get(B,Q),b.get(B,Q)));return F}static checkMatrix(S){return Ee.isMatrix(S)?S:new Ne(S)}static isMatrix(S){return S!=null&&S.klass==="Matrix"}get size(){return this.rows*this.columns}apply(S){if(typeof S!="function")throw new TypeError("callback must be a function");for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)S.call(this,b,k);return this}to1DArray(){let S=[];for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)S.push(this.get(b,k));return S}to2DArray(){let S=[];for(let b=0;b<this.rows;b++){S.push([]);for(let k=0;k<this.columns;k++)S[b].push(this.get(b,k))}return S}toJSON(){return this.to2DArray()}isRowVector(){return this.rows===1}isColumnVector(){return this.columns===1}isVector(){return this.rows===1||this.columns===1}isSquare(){return this.rows===this.columns}isEmpty(){return this.rows===0||this.columns===0}isSymmetric(){if(this.isSquare()){for(let S=0;S<this.rows;S++)for(let b=0;b<=S;b++)if(this.get(S,b)!==this.get(b,S))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let S=0;S<this.rows;S++)if(this.get(S,S)!==0)return!1;return!0}isEchelonForm(){let S=0,b=0,k=-1,E=!0,F=!1;for(;S<this.rows&&E;){for(b=0,F=!1;b<this.columns&&F===!1;)this.get(S,b)===0?b++:this.get(S,b)===1&&b>k?(F=!0,k=b):(E=!1,F=!0);S++}return E}isReducedEchelonForm(){let S=0,b=0,k=-1,E=!0,F=!1;for(;S<this.rows&&E;){for(b=0,F=!1;b<this.columns&&F===!1;)this.get(S,b)===0?b++:this.get(S,b)===1&&b>k?(F=!0,k=b):(E=!1,F=!0);for(let B=b+1;B<this.rows;B++)this.get(S,B)!==0&&(E=!1);S++}return E}echelonForm(){let S=this.clone(),b=0,k=0;for(;b<S.rows&&k<S.columns;){let E=b;for(let F=b;F<S.rows;F++)S.get(F,k)>S.get(E,k)&&(E=F);if(S.get(E,k)===0)k++;else{S.swapRows(b,E);let F=S.get(b,k);for(let B=k;B<S.columns;B++)S.set(b,B,S.get(b,B)/F);for(let B=b+1;B<S.rows;B++){let Q=S.get(B,k)/S.get(b,k);S.set(B,k,0);for(let te=k+1;te<S.columns;te++)S.set(B,te,S.get(B,te)-S.get(b,te)*Q)}b++,k++}}return S}reducedEchelonForm(){let S=this.echelonForm(),b=S.columns,k=S.rows,E=k-1;for(;E>=0;)if(S.maxRow(E)===0)E--;else{let F=0,B=!1;for(;F<k&&B===!1;)S.get(E,F)===1?B=!0:F++;for(let Q=0;Q<E;Q++){let te=S.get(Q,F);for(let Ce=F;Ce<b;Ce++){let Ae=S.get(Q,Ce)-te*S.get(E,Ce);S.set(Q,Ce,Ae)}}E--}return S}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(S={}){if(typeof S!="object")throw new TypeError("options must be an object");const{rows:b=1,columns:k=1}=S;if(!Number.isInteger(b)||b<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(k)||k<=0)throw new TypeError("columns must be a positive integer");let E=new Ne(this.rows*b,this.columns*k);for(let F=0;F<b;F++)for(let B=0;B<k;B++)E.setSubMatrix(this,this.rows*F,this.columns*B);return E}fill(S){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,S);return this}neg(){return this.mulS(-1)}getRow(S){K(this,S);let b=[];for(let k=0;k<this.columns;k++)b.push(this.get(S,k));return b}getRowVector(S){return Ne.rowVector(this.getRow(S))}setRow(S,b){K(this,S),b=ie(this,b);for(let k=0;k<this.columns;k++)this.set(S,k,b[k]);return this}swapRows(S,b){K(this,S),K(this,b);for(let k=0;k<this.columns;k++){let E=this.get(S,k);this.set(S,k,this.get(b,k)),this.set(b,k,E)}return this}getColumn(S){H(this,S);let b=[];for(let k=0;k<this.rows;k++)b.push(this.get(k,S));return b}getColumnVector(S){return Ne.columnVector(this.getColumn(S))}setColumn(S,b){H(this,S),b=pe(this,b);for(let k=0;k<this.rows;k++)this.set(k,S,b[k]);return this}swapColumns(S,b){H(this,S),H(this,b);for(let k=0;k<this.rows;k++){let E=this.get(k,S);this.set(k,S,this.get(k,b)),this.set(k,b,E)}return this}addRowVector(S){S=ie(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)+S[k]);return this}subRowVector(S){S=ie(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)-S[k]);return this}mulRowVector(S){S=ie(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)*S[k]);return this}divRowVector(S){S=ie(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)/S[k]);return this}addColumnVector(S){S=pe(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)+S[b]);return this}subColumnVector(S){S=pe(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)-S[b]);return this}mulColumnVector(S){S=pe(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)*S[b]);return this}divColumnVector(S){S=pe(this,S);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,this.get(b,k)/S[b]);return this}mulRow(S,b){K(this,S);for(let k=0;k<this.columns;k++)this.set(S,k,this.get(S,k)*b);return this}mulColumn(S,b){H(this,S);for(let k=0;k<this.rows;k++)this.set(k,S,this.get(k,S)*b);return this}max(S){if(this.isEmpty())return NaN;switch(S){case"row":{const b=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)>b[k]&&(b[k]=this.get(k,E));return b}case"column":{const b=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)>b[E]&&(b[E]=this.get(k,E));return b}case void 0:{let b=this.get(0,0);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)>b&&(b=this.get(k,E));return b}default:throw new Error(`invalid option: ${S}`)}}maxIndex(){tt(this);let S=this.get(0,0),b=[0,0];for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)>S&&(S=this.get(k,E),b[0]=k,b[1]=E);return b}min(S){if(this.isEmpty())return NaN;switch(S){case"row":{const b=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)<b[k]&&(b[k]=this.get(k,E));return b}case"column":{const b=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)<b[E]&&(b[E]=this.get(k,E));return b}case void 0:{let b=this.get(0,0);for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)<b&&(b=this.get(k,E));return b}default:throw new Error(`invalid option: ${S}`)}}minIndex(){tt(this);let S=this.get(0,0),b=[0,0];for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.get(k,E)<S&&(S=this.get(k,E),b[0]=k,b[1]=E);return b}maxRow(S){if(K(this,S),this.isEmpty())return NaN;
vendor: 6,725 bytes, line 8
8let b=this.get(S,0);for(let k=1;k<this.columns;k++)this.get(S,k)>b&&(b=this.get(S,k));return b}maxRowIndex(S){K(this,S),tt(this);let b=this.get(S,0),k=[S,0];for(let E=1;E<this.columns;E++)this.get(S,E)>b&&(b=this.get(S,E),k[1]=E);return k}minRow(S){if(K(this,S),this.isEmpty())return NaN;let b=this.get(S,0);for(let k=1;k<this.columns;k++)this.get(S,k)<b&&(b=this.get(S,k));return b}minRowIndex(S){K(this,S),tt(this);let b=this.get(S,0),k=[S,0];for(let E=1;E<this.columns;E++)this.get(S,E)<b&&(b=this.get(S,E),k[1]=E);return k}maxColumn(S){if(H(this,S),this.isEmpty())return NaN;let b=this.get(0,S);for(let k=1;k<this.rows;k++)this.get(k,S)>b&&(b=this.get(k,S));return b}maxColumnIndex(S){H(this,S),tt(this);let b=this.get(0,S),k=[0,S];for(let E=1;E<this.rows;E++)this.get(E,S)>b&&(b=this.get(E,S),k[0]=E);return k}minColumn(S){if(H(this,S),this.isEmpty())return NaN;let b=this.get(0,S);for(let k=1;k<this.rows;k++)this.get(k,S)<b&&(b=this.get(k,S));return b}minColumnIndex(S){H(this,S),tt(this);let b=this.get(0,S),k=[0,S];for(let E=1;E<this.rows;E++)this.get(E,S)<b&&(b=this.get(E,S),k[0]=E);return k}diag(){let S=Math.min(this.rows,this.columns),b=[];for(let k=0;k<S;k++)b.push(this.get(k,k));return b}norm(S="frobenius"){switch(S){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${S}`)}}cumulativeSum(){let S=0;for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)S+=this.get(b,k),this.set(b,k,S);return this}dot(S){Ee.isMatrix(S)&&(S=S.to1DArray());let b=this.to1DArray();if(b.length!==S.length)throw new RangeError("vectors do not have the same size");let k=0;for(let E=0;E<b.length;E++)k+=b[E]*S[E];return k}mmul(S){S=Ne.checkMatrix(S);let b=this.rows,k=this.columns,E=S.columns,F=new Ne(b,E),B=new Float64Array(k);for(let Q=0;Q<E;Q++){for(let te=0;te<k;te++)B[te]=S.get(te,Q);for(let te=0;te<b;te++){let Ce=0;for(let Ae=0;Ae<k;Ae++)Ce+=this.get(te,Ae)*B[Ae];F.set(te,Q,Ce)}}return F}mpow(S){if(!this.isSquare())throw new RangeError("Matrix must be square");if(!Number.isInteger(S)||S<0)throw new RangeError("Exponent must be a non-negative integer");let b=Ne.eye(this.rows),k=this;for(let E=S;E>=1;E/=2)1&E&&(b=b.mmul(k)),k=k.mmul(k);return b}strassen2x2(S){S=Ne.checkMatrix(S);let b=new Ne(2,2);const k=this.get(0,0),E=S.get(0,0),F=this.get(0,1),B=S.get(0,1),Q=this.get(1,0),te=S.get(1,0),Ce=this.get(1,1),Ae=S.get(1,1),mt=(k+Ce)*(E+Ae),et=(Q+Ce)*E,it=k*(B-Ae),A=Ce*(te-E),ge=(k+F)*Ae,Ve=mt+A-ge+(F-Ce)*(te+Ae),j=it+ge,oe=et+A,Y=mt-et+it+(Q-k)*(E+B);return b.set(0,0,Ve),b.set(0,1,j),b.set(1,0,oe),b.set(1,1,Y),b}strassen3x3(S){S=Ne.checkMatrix(S);let b=new Ne(3,3);const k=this.get(0,0),E=this.get(0,1),F=this.get(0,2),B=this.get(1,0),Q=this.get(1,1),te=this.get(1,2),Ce=this.get(2,0),Ae=this.get(2,1),mt=this.get(2,2),et=S.get(0,0),it=S.get(0,1),A=S.get(0,2),ge=S.get(1,0),Ve=S.get(1,1),j=S.get(1,2),oe=S.get(2,0),Y=S.get(2,1),le=S.get(2,2),ue=(k-B)*(-it+Ve),vt=(-k+B+Q)*(et-it+Ve),Me=(B+Q)*(-et+it),en=k*et,jt=(-k+Ce+Ae)*(et-A+j),q=(-k+Ce)*(A-j),Le=(Ce+Ae)*(-et+A),Oe=(-F+Ae+mt)*(Ve+oe-Y),je=(F-mt)*(Ve-Y),_t=F*oe,Zt=(Ae+mt)*(-oe+Y),hn=(-F+Q+te)*(j+oe-le),an=(F-te)*(j-le),ve=(Q+te)*(-oe+le),fr=en+_t+E*ge,Zn=(k+E+F-B-Q-Ae-mt)*Ve+vt+Me+en+Oe+_t+Zt,Qn=en+jt+Le+(k+E+F-Q-te-Ce-Ae)*j+_t+hn+ve,Hr=ue+Q*(-et+it+ge-Ve-j-oe+le)+vt+en+_t+hn+an,ft=ue+vt+Me+en+te*Y,St=_t+hn+an+ve+B*A,wt=en+jt+q+Ae*(-et+A+ge-Ve-j-oe+Y)+Oe+je+_t,bt=Oe+je+_t+Zt+Ce*it,Ge=en+jt+q+Le+mt*le;return b.set(0,0,fr),b.set(0,1,Zn),b.set(0,2,Qn),b.set(1,0,Hr),b.set(1,1,ft),b.set(1,2,St),b.set(2,0,wt),b.set(2,1,bt),b.set(2,2,Ge),b}mmulStrassen(S){S=Ne.checkMatrix(S);let b=this.clone(),k=b.rows,E=b.columns,F=S.rows,B=S.columns;function Q(Ae,mt,et){let it=Ae.rows,A=Ae.columns;if(it===mt&&A===et)return Ae;{let ge=Ee.zeros(mt,et);return ge=ge.setSubMatrix(Ae,0,0),ge}}E!==F&&console.warn(`Multiplying ${k} x ${E} and ${F} x ${B} matrix: dimensions do not match.`);let te=Math.max(k,F),Ce=Math.max(E,B);return b=Q(b,te,Ce),function Ae(mt,et,it,A){if(it<=512||A<=512)return mt.mmul(et);it%2==1&&A%2==1?(mt=Q(mt,it+1,A+1),et=Q(et,it+1,A+1)):it%2==1?(mt=Q(mt,it+1,A),et=Q(et,it+1,A)):A%2==1&&(mt=Q(mt,it,A+1),et=Q(et,it,A+1));let ge=parseInt(mt.rows/2,10),Ve=parseInt(mt.columns/2,10),j=mt.subMatrix(0,ge-1,0,Ve-1),oe=et.subMatrix(0,ge-1,0,Ve-1),Y=mt.subMatrix(0,ge-1,Ve,mt.columns-1),le=et.subMatrix(0,ge-1,Ve,et.columns-1),ue=mt.subMatrix(ge,mt.rows-1,0,Ve-1),vt=et.subMatrix(ge,et.rows-1,0,Ve-1),Me=mt.subMatrix(ge,mt.rows-1,Ve,mt.columns-1),en=et.subMatrix(ge,et.rows-1,Ve,et.columns-1),jt=Ae(Ee.add(j,Me),Ee.add(oe,en),ge,Ve),q=Ae(Ee.add(ue,Me),oe,ge,Ve),Le=Ae(j,Ee.sub(le,en),ge,Ve),Oe=Ae(Me,Ee.sub(vt,oe),ge,Ve),je=Ae(Ee.add(j,Y),en,ge,Ve),_t=Ae(Ee.sub(ue,j),Ee.add(oe,le),ge,Ve),Zt=Ae(Ee.sub(Y,Me),Ee.add(vt,en),ge,Ve),hn=Ee.add(jt,Oe);hn.sub(je),hn.add(Zt);let an=Ee.add(Le,je),ve=Ee.add(q,Oe),fr=Ee.sub(jt,q);fr.add(Le),fr.add(_t);let Zn=Ee.zeros(2*hn.rows,2*hn.columns);return Zn=Zn.setSubMatrix(hn,0,0),Zn=Zn.setSubMatrix(an,hn.rows,0),Zn=Zn.setSubMatrix(ve,0,hn.columns),Zn=Zn.setSubMatrix(fr,hn.rows,hn.columns),Zn.subMatrix(0,it-1,0,A-1)}(b,S=Q(S,te,Ce),te,Ce)}scaleRows(S={}){if(typeof S!="object")throw new TypeError("options must be an object");const{min:b=0,max:k=1}=S;if(!Number.isFinite(b))throw new TypeError("min must be a number");if(!Number.isFinite(k))throw new TypeError("max must be a number");if(b>=k)throw new RangeError("min must be smaller than max");let E=new Ne(this.rows,this.columns);for(let F=0;F<this.rows;F++){const B=this.getRow(F);B.length>0&&Vt(B,{min:b,max:k,output:B}),E.setRow(F,B)}return E}scaleColumns(S={}){if(typeof S!="object")throw new TypeError("options must be an object");const{min:b=0,max:k=1}=S;if(!Number.isFinite(b))throw new TypeError("min must be a number");if(!Number.isFinite(k))throw new TypeError("max must be a number");if(b>=k)throw new RangeError("min must be smaller than max");let E=new Ne(this.rows,this.columns);for(let F=0;F<this.columns;F++){const B=this.getColumn(F);B.length&&Vt(B,{min:b,max:k,output:B}),E.setColumn(F,B)}return E}flipRows(){const S=Math.ceil(this.columns/2);for(let b=0;b<this.rows;b++)for(let k=0;k<S;k++){let E=this.get(b,k),F=this.get(b,this.columns-1-k);this.set(b,k,F),this.set(b,this.columns-1-k,E)}return this}flipColumns(){const S=Math.ceil(this.rows/2);for(let b=0;b<this.columns;b++)for(let k=0;k<S;k++){let E=this.get(k,b),F=this.get(this.rows-1-k,b);this.set(k,b,F),this.set(this.rows-1-k,b,E)}return this}kroneckerProduct(S){S=Ne.checkMatrix(S);let b=this.rows,k=this.columns,E=S.rows,F=S.columns,B=new Ne(b*E,k*F);for(let Q=0;Q<b;Q++)for(let te=0;te<k;te++)for(let Ce=0;Ce<E;Ce++)for(let Ae=0;Ae<F;Ae++)B.set(E*Q+Ce,F*te+Ae,this.get(Q,te)*S.get(Ce,Ae));return B}
vendor: 7,422 bytes, line 8
8kroneckerSum(S){if(S=Ne.checkMatrix(S),!this.isSquare()||!S.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let b=this.rows,k=S.rows,E=this.kroneckerProduct(Ne.eye(k,k)),F=Ne.eye(b,b).kroneckerProduct(S);return E.add(F)}transpose(){let S=new Ne(this.columns,this.rows);for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)S.set(k,b,this.get(b,k));return S}sortRows(S=Re){for(let b=0;b<this.rows;b++)this.setRow(b,this.getRow(b).sort(S));return this}sortColumns(S=Re){for(let b=0;b<this.columns;b++)this.setColumn(b,this.getColumn(b).sort(S));return this}subMatrix(S,b,k,E){Ke(this,S,b,k,E);let F=new Ne(b-S+1,E-k+1);for(let B=S;B<=b;B++)for(let Q=k;Q<=E;Q++)F.set(B-S,Q-k,this.get(B,Q));return F}subMatrixRow(S,b,k){if(b===void 0&&(b=0),k===void 0&&(k=this.columns-1),b>k||b<0||b>=this.columns||k<0||k>=this.columns)throw new RangeError("Argument out of range");let E=new Ne(S.length,k-b+1);for(let F=0;F<S.length;F++)for(let B=b;B<=k;B++){if(S[F]<0||S[F]>=this.rows)throw new RangeError(`Row index out of range: ${S[F]}`);E.set(F,B-b,this.get(S[F],B))}return E}subMatrixColumn(S,b,k){if(b===void 0&&(b=0),k===void 0&&(k=this.rows-1),b>k||b<0||b>=this.rows||k<0||k>=this.rows)throw new RangeError("Argument out of range");let E=new Ne(k-b+1,S.length);for(let F=0;F<S.length;F++)for(let B=b;B<=k;B++){if(S[F]<0||S[F]>=this.columns)throw new RangeError(`Column index out of range: ${S[F]}`);E.set(B-b,F,this.get(B,S[F]))}return E}setSubMatrix(S,b,k){if((S=Ne.checkMatrix(S)).isEmpty())return this;Ke(this,b,b+S.rows-1,k,k+S.columns-1);for(let E=0;E<S.rows;E++)for(let F=0;F<S.columns;F++)this.set(b+E,k+F,S.get(E,F));return this}selection(S,b){Se(this,S),Qe(this,b);let k=new Ne(S.length,b.length);for(let E=0;E<S.length;E++){let F=S[E];for(let B=0;B<b.length;B++){let Q=b[B];k.set(E,B,this.get(F,Q))}}return k}trace(){let S=Math.min(this.rows,this.columns),b=0;for(let k=0;k<S;k++)b+=this.get(k,k);return b}clone(){return this.constructor.copy(this,new Ne(this.rows,this.columns))}static copy(S,b){for(const[k,E,F]of S.entries())b.set(k,E,F);return b}sum(S){switch(S){case"row":return function(b){let k=de(b.rows);for(let E=0;E<b.rows;++E)for(let F=0;F<b.columns;++F)k[E]+=b.get(E,F);return k}(this);case"column":return function(b){let k=de(b.columns);for(let E=0;E<b.rows;++E)for(let F=0;F<b.columns;++F)k[F]+=b.get(E,F);return k}(this);case void 0:return function(b){let k=0;for(let E=0;E<b.rows;E++)for(let F=0;F<b.columns;F++)k+=b.get(E,F);return k}(this);default:throw new Error(`invalid option: ${S}`)}}product(S){switch(S){case"row":return function(b){let k=de(b.rows,1);for(let E=0;E<b.rows;++E)for(let F=0;F<b.columns;++F)k[E]*=b.get(E,F);return k}(this);case"column":return function(b){let k=de(b.columns,1);for(let E=0;E<b.rows;++E)for(let F=0;F<b.columns;++F)k[F]*=b.get(E,F);return k}(this);case void 0:return function(b){let k=1;for(let E=0;E<b.rows;E++)for(let F=0;F<b.columns;F++)k*=b.get(E,F);return k}(this);default:throw new Error(`invalid option: ${S}`)}}mean(S){const b=this.sum(S);switch(S){case"row":for(let k=0;k<this.rows;k++)b[k]/=this.columns;return b;case"column":for(let k=0;k<this.columns;k++)b[k]/=this.rows;return b;case void 0:return b/this.size;default:throw new Error(`invalid option: ${S}`)}}variance(S,b={}){if(typeof S=="object"&&(b=S,S=void 0),typeof b!="object")throw new TypeError("options must be an object");const{unbiased:k=!0,mean:E=this.mean(S)}=b;if(typeof k!="boolean")throw new TypeError("unbiased must be a boolean");switch(S){case"row":if(!Xe.isAnyArray(E))throw new TypeError("mean must be an array");return function(F,B,Q){const te=F.rows,Ce=F.columns,Ae=[];for(let mt=0;mt<te;mt++){let et=0,it=0,A=0;for(let ge=0;ge<Ce;ge++)A=F.get(mt,ge)-Q[mt],et+=A,it+=A*A;B?Ae.push((it-et*et/Ce)/(Ce-1)):Ae.push((it-et*et/Ce)/Ce)}return Ae}(this,k,E);case"column":if(!Xe.isAnyArray(E))throw new TypeError("mean must be an array");return function(F,B,Q){const te=F.rows,Ce=F.columns,Ae=[];for(let mt=0;mt<Ce;mt++){let et=0,it=0,A=0;for(let ge=0;ge<te;ge++)A=F.get(ge,mt)-Q[mt],et+=A,it+=A*A;B?Ae.push((it-et*et/te)/(te-1)):Ae.push((it-et*et/te)/te)}return Ae}(this,k,E);case void 0:if(typeof E!="number")throw new TypeError("mean must be a number");return function(F,B,Q){const te=F.rows,Ce=F.columns,Ae=te*Ce;let mt=0,et=0,it=0;for(let A=0;A<te;A++)for(let ge=0;ge<Ce;ge++)it=F.get(A,ge)-Q,mt+=it,et+=it*it;return B?(et-mt*mt/Ae)/(Ae-1):(et-mt*mt/Ae)/Ae}(this,k,E);default:throw new Error(`invalid option: ${S}`)}}standardDeviation(S,b){typeof S=="object"&&(b=S,S=void 0);const k=this.variance(S,b);if(S===void 0)return Math.sqrt(k);for(let E=0;E<k.length;E++)k[E]=Math.sqrt(k[E]);return k}center(S,b={}){if(typeof S=="object"&&(b=S,S=void 0),typeof b!="object")throw new TypeError("options must be an object");const{center:k=this.mean(S)}=b;switch(S){case"row":if(!Xe.isAnyArray(k))throw new TypeError("center must be an array");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)-F[B])}(this,k),this;case"column":if(!Xe.isAnyArray(k))throw new TypeError("center must be an array");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)-F[Q])}(this,k),this;case void 0:if(typeof k!="number")throw new TypeError("center must be a number");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)-F)}(this,k),this;default:throw new Error(`invalid option: ${S}`)}}scale(S,b={}){if(typeof S=="object"&&(b=S,S=void 0),typeof b!="object")throw new TypeError("options must be an object");let k=b.scale;switch(S){case"row":if(k===void 0)k=function(E){const F=[];for(let B=0;B<E.rows;B++){let Q=0;for(let te=0;te<E.columns;te++)Q+=E.get(B,te)**2/(E.columns-1);F.push(Math.sqrt(Q))}return F}(this);else if(!Xe.isAnyArray(k))throw new TypeError("scale must be an array");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)/F[B])}(this,k),this;case"column":if(k===void 0)k=function(E){const F=[];for(let B=0;B<E.columns;B++){let Q=0;for(let te=0;te<E.rows;te++)Q+=E.get(te,B)**2/(E.rows-1);F.push(Math.sqrt(Q))}return F}(this);else if(!Xe.isAnyArray(k))throw new TypeError("scale must be an array");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)/F[Q])}(this,k),this;case void 0:if(k===void 0)k=function(E){const F=E.size-1;let B=0;for(let Q=0;Q<E.columns;Q++)for(let te=0;te<E.rows;te++)B+=E.get(te,Q)**2/F;return Math.sqrt(B)}(this);else if(typeof k!="number")throw new TypeError("scale must be a number");return function(E,F){for(let B=0;B<E.rows;B++)for(let Q=0;Q<E.columns;Q++)E.set(B,Q,E.get(B,Q)/F)}(this,k),this;default:throw new Error(`invalid option: ${S}`)}}toString(S){return ct(this,S)}[Symbol.iterator](){return this.entries()}*entries(){for(let S=0;S<this.rows;S++)for(let b=0;b<this.columns;b++)yield[S,b,this.get(S,b)]}*values(){for(let S=0;S<this.rows;S++)for(let b=0;b<this.columns;b++)yield this.get(S,b)}}function Re(M,S){return M-S}function pt(M){return M.every(S=>typeof S=="number")}Ee.prototype.klass="Matrix",typeof Symbol<"u"&&(Ee.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return ct(this)}),Ee.random=Ee.rand,Ee.randomInt=Ee.randInt,Ee.diagonal=Ee.diag,Ee.prototype.diagonal=Ee.prototype.diag,Ee.identity=Ee.eye,Ee.prototype.negate=Ee.prototype.neg,Ee.prototype.tensorProduct=Ee.prototype.kroneckerProduct;
vendor: 7,091 bytes, line 8
8const Ut=class Ut extends Ee{constructor(b,k){super();qx(this,He);aT(this,"data");if(Ut.isMatrix(b))Xx(this,He,Yx).call(this,b.rows,b.columns),Ut.copy(b,this);else if(Number.isInteger(b)&&b>=0)Xx(this,He,Yx).call(this,b,k);else{if(!Xe.isAnyArray(b))throw new TypeError("First argument must be a positive number or an array");{const E=b;if(typeof(k=(b=E.length)?E[0].length:0)!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let F=0;F<b;F++){if(E[F].length!==k)throw new RangeError("Inconsistent array dimensions");if(!pt(E[F]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(E[F]))}this.rows=b,this.columns=k}}}set(b,k,E){return this.data[b][k]=E,this}get(b,k){return this.data[b][k]}removeRow(b){return K(this,b),this.data.splice(b,1),this.rows-=1,this}addRow(b,k){return k===void 0&&(k=b,b=this.rows),K(this,b,!0),k=Float64Array.from(ie(this,k)),this.data.splice(b,0,k),this.rows+=1,this}removeColumn(b){H(this,b);for(let k=0;k<this.rows;k++){const E=new Float64Array(this.columns-1);for(let F=0;F<b;F++)E[F]=this.data[k][F];for(let F=b+1;F<this.columns;F++)E[F-1]=this.data[k][F];this.data[k]=E}return this.columns-=1,this}addColumn(b,k){k===void 0&&(k=b,b=this.columns),H(this,b,!0),k=pe(this,k);for(let E=0;E<this.rows;E++){const F=new Float64Array(this.columns+1);let B=0;for(;B<b;B++)F[B]=this.data[E][B];for(F[B++]=k[E];B<this.columns+1;B++)F[B]=this.data[E][B-1];this.data[E]=F}return this.columns+=1,this}};He=new WeakSet,Yx=function(b,k){if(this.data=[],!(Number.isInteger(k)&&k>=0))throw new TypeError("nColumns must be a positive integer");for(let E=0;E<b;E++)this.data.push(new Float64Array(k));this.rows=b,this.columns=k};let Ne=Ut;(function(M,S){M.prototype.add=function(b){return typeof b=="number"?this.addS(b):this.addM(b)},M.prototype.addS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)+b);return this},M.prototype.addM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)+b.get(k,E));return this},M.add=function(b,k){return new S(b).add(k)},M.prototype.sub=function(b){return typeof b=="number"?this.subS(b):this.subM(b)},M.prototype.subS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)-b);return this},M.prototype.subM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)-b.get(k,E));return this},M.sub=function(b,k){return new S(b).sub(k)},M.prototype.subtract=M.prototype.sub,M.prototype.subtractS=M.prototype.subS,M.prototype.subtractM=M.prototype.subM,M.subtract=M.sub,M.prototype.mul=function(b){return typeof b=="number"?this.mulS(b):this.mulM(b)},M.prototype.mulS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)*b);return this},M.prototype.mulM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)*b.get(k,E));return this},M.mul=function(b,k){return new S(b).mul(k)},M.prototype.multiply=M.prototype.mul,M.prototype.multiplyS=M.prototype.mulS,M.prototype.multiplyM=M.prototype.mulM,M.multiply=M.mul,M.prototype.div=function(b){return typeof b=="number"?this.divS(b):this.divM(b)},M.prototype.divS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)/b);return this},M.prototype.divM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)/b.get(k,E));return this},M.div=function(b,k){return new S(b).div(k)},M.prototype.divide=M.prototype.div,M.prototype.divideS=M.prototype.divS,M.prototype.divideM=M.prototype.divM,M.divide=M.div,M.prototype.mod=function(b){return typeof b=="number"?this.modS(b):this.modM(b)},M.prototype.modS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)%b);return this},M.prototype.modM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)%b.get(k,E));return this},M.mod=function(b,k){return new S(b).mod(k)},M.prototype.modulus=M.prototype.mod,M.prototype.modulusS=M.prototype.modS,M.prototype.modulusM=M.prototype.modM,M.modulus=M.mod,M.prototype.and=function(b){return typeof b=="number"?this.andS(b):this.andM(b)},M.prototype.andS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)&b);return this},M.prototype.andM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)&b.get(k,E));return this},M.and=function(b,k){return new S(b).and(k)},M.prototype.or=function(b){return typeof b=="number"?this.orS(b):this.orM(b)},M.prototype.orS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)|b);return this},M.prototype.orM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)|b.get(k,E));return this},M.or=function(b,k){return new S(b).or(k)},M.prototype.xor=function(b){return typeof b=="number"?this.xorS(b):this.xorM(b)},M.prototype.xorS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)^b);return this},M.prototype.xorM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)^b.get(k,E));return this},M.xor=function(b,k){return new S(b).xor(k)},M.prototype.leftShift=function(b){return typeof b=="number"?this.leftShiftS(b):this.leftShiftM(b)},M.prototype.leftShiftS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)<<b);return this},M.prototype.leftShiftM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)<<b.get(k,E));return this},M.leftShift=function(b,k){return new S(b).leftShift(k)},M.prototype.signPropagatingRightShift=function(b){return typeof b=="number"?this.signPro
vendor: 7,184 bytes, line 8
8pagatingRightShiftS(b):this.signPropagatingRightShiftM(b)},M.prototype.signPropagatingRightShiftS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)>>b);return this},M.prototype.signPropagatingRightShiftM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)>>b.get(k,E));return this},M.signPropagatingRightShift=function(b,k){return new S(b).signPropagatingRightShift(k)},M.prototype.rightShift=function(b){return typeof b=="number"?this.rightShiftS(b):this.rightShiftM(b)},M.prototype.rightShiftS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)>>>b);return this},M.prototype.rightShiftM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)>>>b.get(k,E));return this},M.rightShift=function(b,k){return new S(b).rightShift(k)},M.prototype.zeroFillRightShift=M.prototype.rightShift,M.prototype.zeroFillRightShiftS=M.prototype.rightShiftS,M.prototype.zeroFillRightShiftM=M.prototype.rightShiftM,M.zeroFillRightShift=M.rightShift,M.prototype.not=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,~this.get(b,k));return this},M.not=function(b){return new S(b).not()},M.prototype.abs=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.abs(this.get(b,k)));return this},M.abs=function(b){return new S(b).abs()},M.prototype.acos=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.acos(this.get(b,k)));return this},M.acos=function(b){return new S(b).acos()},M.prototype.acosh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.acosh(this.get(b,k)));return this},M.acosh=function(b){return new S(b).acosh()},M.prototype.asin=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.asin(this.get(b,k)));return this},M.asin=function(b){return new S(b).asin()},M.prototype.asinh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.asinh(this.get(b,k)));return this},M.asinh=function(b){return new S(b).asinh()},M.prototype.atan=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.atan(this.get(b,k)));return this},M.atan=function(b){return new S(b).atan()},M.prototype.atanh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.atanh(this.get(b,k)));return this},M.atanh=function(b){return new S(b).atanh()},M.prototype.cbrt=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.cbrt(this.get(b,k)));return this},M.cbrt=function(b){return new S(b).cbrt()},M.prototype.ceil=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.ceil(this.get(b,k)));return this},M.ceil=function(b){return new S(b).ceil()},M.prototype.clz32=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.clz32(this.get(b,k)));return this},M.clz32=function(b){return new S(b).clz32()},M.prototype.cos=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.cos(this.get(b,k)));return this},M.cos=function(b){return new S(b).cos()},M.prototype.cosh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.cosh(this.get(b,k)));return this},M.cosh=function(b){return new S(b).cosh()},M.prototype.exp=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.exp(this.get(b,k)));return this},M.exp=function(b){return new S(b).exp()},M.prototype.expm1=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.expm1(this.get(b,k)));return this},M.expm1=function(b){return new S(b).expm1()},M.prototype.floor=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.floor(this.get(b,k)));return this},M.floor=function(b){return new S(b).floor()},M.prototype.fround=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.fround(this.get(b,k)));return this},M.fround=function(b){return new S(b).fround()},M.prototype.log=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.log(this.get(b,k)));return this},M.log=function(b){return new S(b).log()},M.prototype.log1p=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.log1p(this.get(b,k)));return this},M.log1p=function(b){return new S(b).log1p()},M.prototype.log10=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.log10(this.get(b,k)));return this},M.log10=function(b){return new S(b).log10()},M.prototype.log2=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.log2(this.get(b,k)));return this},M.log2=function(b){return new S(b).log2()},M.prototype.round=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.round(this.get(b,k)));return this},M.round=function(b){return new S(b).round()},M.prototype.sign=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.sign(this.get(b,k)));return this},M.sign=function(b){return new S(b).sign()},M.prototype.sin=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.sin(this.get(b,k)));return this},M.sin=function(b){return new S(b).sin()},M.prototype.sinh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.sinh(this.get(b,k)));return this},M.sinh=function(b){return new S(b).sinh()},M.prototype.sqrt=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.sqrt(this.get(b,k)));return this},M.sqrt=function(b){return new S(b).sqrt()},M.prototype.tan=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.tan(this.get(b,k)));return this},M.tan=function(b){return new S(b).tan()},M.prototype.tanh=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.tanh(this.get(b,k)));return this},M.tanh=function(b){return new S(b).tanh()},M.prototype.trunc=function(){for(let b=0;b<this.rows;b++)for(let k=0;k<this.columns;k++)this.set(b,k,Math.trunc(this.get(b,k)));return this},M.trunc=function(b){return new S(b).trunc()},M.pow=function(b,k){return new S(b).pow(k)},M.prototype.pow=function(b){return typeof b=="number"?this.powS(b):this.powM(b)},M.prototype.powS=function(b){for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)**b);return this},M.prototype.powM=function(b){if(b=S.checkMatrix(b),this.rows!==b.rows||this.columns!==b.columns)throw new RangeError("Matrices dimensions must be equal");for(let k=0;k<this.rows;k++)for(let E=0;E<this.columns;E++)this.set(k,E,this.get(k,E)**b.get(k,E));return this}})(Ee,Ne);
8const Kt=class Kt extends Ee{constructor(b){super();qx(this,at);if(Ne.isMatrix(b)){if(!b.isSymmetric())throw new TypeError("not symmetric data");Iy(this,at,Ne.copy(b,new Ne(b.rows,b.rows)))}else if(Number.isInteger(b)&&b>=0)Iy(this,at,new Ne(b,b));else if(Iy(this,at,new Ne(b)),!this.isSymmetric())throw new TypeError("not symmetric data")}get size(){return mo(this,at).size}get rows(){return mo(this,at).rows}get columns(){return mo(this,at).columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(b){return Ne.isMatrix(b)&&b.klassType==="SymmetricMatrix"}static zeros(b){return new this(b)}static ones(b){return new this(b).fill(1)}clone(){const b=new Kt(this.diagonalSize);for(const[k,E,F]of this.upperRightEntries())b.set(k,E,F);return b}toMatrix(){return new Ne(this)}get(b,k){return mo(this,at).get(b,k)}set(b,k,E){return mo(this,at).set(b,k,E),mo(this,at).set(k,b,E),this}removeCross(b){return mo(this,at).removeRow(b),mo(this,at).removeColumn(b),this}addCross(b,k){k===void 0&&(k=b,b=this.diagonalSize);const E=k.slice();return E.splice(b,1),mo(this,at).addRow(b,E),mo(this,at).addColumn(b,k),this}applyMask(b){if(b.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const k=[];for(const[E,F]of b.entries())F||k.push(E);k.reverse();for(const E of k)this.removeCross(E);return this}toCompact(){const{diagonalSize:b}=this,k=new Array(b*(b+1)/2);for(let E=0,F=0,B=0;B<k.length;B++)k[B]=this.get(F,E),++E>=b&&(E=++F);return k}static fromCompact(b){const k=b.length,E=(Math.sqrt(8*k+1)-1)/2;if(!Number.isInteger(E))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(b)}`);const F=new Kt(E);for(let B=0,Q=0,te=0;te<k;te++)F.set(B,Q,b[te]),++B>=E&&(B=++Q);return F}*upperRightEntries(){for(let b=0,k=0;b<this.diagonalSize;void 0){const E=this.get(b,k);yield[b,k,E],++k>=this.diagonalSize&&(k=++b)}}*upperRightValues(){for(let b=0,k=0;b<this.diagonalSize;void 0)yield this.get(b,k),++k>=this.diagonalSize&&(k=++b)}};at=new WeakMap;let Pe=Kt;Pe.prototype.klassType="SymmetricMatrix";class G extends Pe{static isDistanceMatrix(S){return Pe.isSymmetricMatrix(S)&&S.klassSubType==="DistanceMatrix"}constructor(S){if(super(S),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(S,b,k){return S===b&&(k=0),super.set(S,b,k)}addCross(S,b){return b===void 0&&(b=S,S=this.diagonalSize),(b=b.slice())[S]=0,super.addCross(S,b)}toSymmetricMatrix(){return new Pe(this)}clone(){const S=new G(this.diagonalSize);for(const[b,k,E]of this.upperRightEntries())b!==k&&S.set(b,k,E);return S}toCompact(){const{diagonalSize:S}=this,b=new Array((S-1)*S/2);for(let k=1,E=0,F=0;F<b.length;F++)b[F]=this.get(E,k),++k>=S&&(k=1+ ++E);return b}static fromCompact(S){const b=S.length;if(b===0)return new this(0);const k=(Math.sqrt(8*b+1)+1)/2;if(!Number.isInteger(k))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(S)}`);const E=new this(k);for(let F=1,B=0,Q=0;Q<b;Q++)E.set(F,B,S[Q]),++F>=k&&(F=1+ ++B);return E}}G.prototype.klassSubType="DistanceMatrix";class Be extends Ee{constructor(S,b,k){super(),this.matrix=S,this.rows=b,this.columns=k}}class Ze extends Be{constructor(S,b,k){Se(S,b),Qe(S,k),super(S,b.length,k.length),this.rowIndices=b,this.columnIndices=k}set(S,b,k){return this.matrix.set(this.rowIndices[S],this.columnIndices[b],k),this}get(S,b){return this.matrix.get(this.rowIndices[S],this.columnIndices[b])}}class $t extends Ee{constructor(S,b={}){const{rows:k=1}=b;if(S.length%k!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=k,this.columns=S.length/k,this.data=S}set(S,b,k){let E=this._calculateIndex(S,b);return this.data[E]=k,this}get(S,b){let k=this._calculateIndex(S,b);return this.data[k]}_calculateIndex(S,b){return S*this.columns+b}}class Wt extends Ee{constructor(S){super(),this.data=S,this.rows=S.length,this.columns=S[0].length}set(S,b,k){return this.data[S][b]=k,this}get(S,b){return this.data[S][b]}}class yn{constructor(S){let b,k,E,F,B,Q,te,Ce,Ae,mt=(S=Wt.checkMatrix(S)).clone(),et=mt.rows,it=mt.columns,A=new Float64Array(et),ge=1;for(b=0;b<et;b++)A[b]=b;
vendor: 7,759 bytes, line 8
8for(Ce=new Float64Array(et),k=0;k<it;k++){for(b=0;b<et;b++)Ce[b]=mt.get(b,k);for(b=0;b<et;b++){for(Ae=Math.min(b,k),B=0,E=0;E<Ae;E++)B+=mt.get(b,E)*Ce[E];Ce[b]-=B,mt.set(b,k,Ce[b])}for(F=k,b=k+1;b<et;b++)Math.abs(Ce[b])>Math.abs(Ce[F])&&(F=b);if(F!==k){for(E=0;E<it;E++)Q=mt.get(F,E),mt.set(F,E,mt.get(k,E)),mt.set(k,E,Q);te=A[F],A[F]=A[k],A[k]=te,ge=-ge}if(k<et&&mt.get(k,k)!==0)for(b=k+1;b<et;b++)mt.set(b,k,mt.get(b,k)/mt.get(k,k))}this.LU=mt,this.pivotVector=A,this.pivotSign=ge}isSingular(){let S=this.LU,b=S.columns;for(let k=0;k<b;k++)if(S.get(k,k)===0)return!0;return!1}solve(S){S=Ne.checkMatrix(S);let b=this.LU;if(b.rows!==S.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let k,E,F,B=S.columns,Q=S.subMatrixRow(this.pivotVector,0,B-1),te=b.columns;for(F=0;F<te;F++)for(k=F+1;k<te;k++)for(E=0;E<B;E++)Q.set(k,E,Q.get(k,E)-Q.get(F,E)*b.get(k,F));for(F=te-1;F>=0;F--){for(E=0;E<B;E++)Q.set(F,E,Q.get(F,E)/b.get(F,F));for(k=0;k<F;k++)for(E=0;E<B;E++)Q.set(k,E,Q.get(k,E)-Q.get(F,E)*b.get(k,F))}return Q}get determinant(){let S=this.LU;if(!S.isSquare())throw new Error("Matrix must be square");let b=this.pivotSign,k=S.columns;for(let E=0;E<k;E++)b*=S.get(E,E);return b}get lowerTriangularMatrix(){let S=this.LU,b=S.rows,k=S.columns,E=new Ne(b,k);for(let F=0;F<b;F++)for(let B=0;B<k;B++)F>B?E.set(F,B,S.get(F,B)):F===B?E.set(F,B,1):E.set(F,B,0);return E}get upperTriangularMatrix(){let S=this.LU,b=S.rows,k=S.columns,E=new Ne(b,k);for(let F=0;F<b;F++)for(let B=0;B<k;B++)F<=B?E.set(F,B,S.get(F,B)):E.set(F,B,0);return E}get pivotPermutationVector(){return Array.from(this.pivotVector)}}function Jt(M,S){let b=0;return Math.abs(M)>Math.abs(S)?(b=S/M,Math.abs(M)*Math.sqrt(1+b*b)):S!==0?(b=M/S,Math.abs(S)*Math.sqrt(1+b*b)):0}class fn{constructor(S){let b,k,E,F,B=(S=Wt.checkMatrix(S)).clone(),Q=S.rows,te=S.columns,Ce=new Float64Array(te);for(E=0;E<te;E++){let Ae=0;for(b=E;b<Q;b++)Ae=Jt(Ae,B.get(b,E));if(Ae!==0){for(B.get(E,E)<0&&(Ae=-Ae),b=E;b<Q;b++)B.set(b,E,B.get(b,E)/Ae);for(B.set(E,E,B.get(E,E)+1),k=E+1;k<te;k++){for(F=0,b=E;b<Q;b++)F+=B.get(b,E)*B.get(b,k);for(F=-F/B.get(E,E),b=E;b<Q;b++)B.set(b,k,B.get(b,k)+F*B.get(b,E))}}Ce[E]=-Ae}this.QR=B,this.Rdiag=Ce}solve(S){S=Ne.checkMatrix(S);let b=this.QR,k=b.rows;if(S.rows!==k)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let E,F,B,Q,te=S.columns,Ce=S.clone(),Ae=b.columns;for(B=0;B<Ae;B++)for(F=0;F<te;F++){for(Q=0,E=B;E<k;E++)Q+=b.get(E,B)*Ce.get(E,F);for(Q=-Q/b.get(B,B),E=B;E<k;E++)Ce.set(E,F,Ce.get(E,F)+Q*b.get(E,B))}for(B=Ae-1;B>=0;B--){for(F=0;F<te;F++)Ce.set(B,F,Ce.get(B,F)/this.Rdiag[B]);for(E=0;E<B;E++)for(F=0;F<te;F++)Ce.set(E,F,Ce.get(E,F)-Ce.get(B,F)*b.get(E,B))}return Ce.subMatrix(0,Ae-1,0,te-1)}isFullRank(){let S=this.QR.columns;for(let b=0;b<S;b++)if(this.Rdiag[b]===0)return!1;return!0}get upperTriangularMatrix(){let S,b,k=this.QR,E=k.columns,F=new Ne(E,E);for(S=0;S<E;S++)for(b=0;b<E;b++)S<b?F.set(S,b,k.get(S,b)):S===b?F.set(S,b,this.Rdiag[S]):F.set(S,b,0);return F}get orthogonalMatrix(){let S,b,k,E,F=this.QR,B=F.rows,Q=F.columns,te=new Ne(B,Q);for(k=Q-1;k>=0;k--){for(S=0;S<B;S++)te.set(S,k,0);for(te.set(k,k,1),b=k;b<Q;b++)if(F.get(k,k)!==0){for(E=0,S=k;S<B;S++)E+=F.get(S,k)*te.get(S,b);for(E=-E/F.get(k,k),S=k;S<B;S++)te.set(S,b,te.get(S,b)+E*F.get(S,k))}}return te}}class cn{constructor(S,b={}){if((S=Wt.checkMatrix(S)).isEmpty())throw new Error("Matrix must be non-empty");let k=S.rows,E=S.columns;const{computeLeftSingularVectors:F=!0,computeRightSingularVectors:B=!0,autoTranspose:Q=!1}=b;let te,Ce=!!F,Ae=!!B,mt=!1;if(k<E)if(Q){te=S.transpose(),k=te.rows,E=te.columns,mt=!0;let q=Ce;Ce=Ae,Ae=q}else te=S.clone(),console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose");else te=S.clone();let et=Math.min(k,E),it=Math.min(k+1,E),A=new Float64Array(it),ge=new Ne(k,et),Ve=new Ne(E,E),j=new Float64Array(E),oe=new Float64Array(k),Y=new Float64Array(it);for(let q=0;q<it;q++)Y[q]=q;let le=Math.min(k-1,E),ue=Math.max(0,Math.min(E-2,k)),vt=Math.max(le,ue);for(let q=0;q<vt;q++){if(q<le){A[q]=0;for(let Le=q;Le<k;Le++)A[q]=Jt(A[q],te.get(Le,q));if(A[q]!==0){te.get(q,q)<0&&(A[q]=-A[q]);for(let Le=q;Le<k;Le++)te.set(Le,q,te.get(Le,q)/A[q]);te.set(q,q,te.get(q,q)+1)}A[q]=-A[q]}for(let Le=q+1;Le<E;Le++){if(q<le&&A[q]!==0){let Oe=0;for(let je=q;je<k;je++)Oe+=te.get(je,q)*te.get(je,Le);Oe=-Oe/te.get(q,q);for(let je=q;je<k;je++)te.set(je,Le,te.get(je,Le)+Oe*te.get(je,q))}j[Le]=te.get(q,Le)}if(Ce&&q<le)for(let Le=q;Le<k;Le++)ge.set(Le,q,te.get(Le,q));if(q<ue){j[q]=0;for(let Le=q+1;Le<E;Le++)j[q]=Jt(j[q],j[Le]);if(j[q]!==0){j[q+1]<0&&(j[q]=0-j[q]);for(let Le=q+1;Le<E;Le++)j[Le]/=j[q];j[q+1]+=1}if(j[q]=-j[q],q+1<k&&j[q]!==0){for(let Le=q+1;Le<k;Le++)oe[Le]=0;for(let Le=q+1;Le<k;Le++)for(let Oe=q+1;Oe<E;Oe++)oe[Le]+=j[Oe]*te.get(Le,Oe);for(let Le=q+1;Le<E;Le++){let Oe=-j[Le]/j[q+1];for(let je=q+1;je<k;je++)te.set(je,Le,te.get(je,Le)+Oe*oe[je])}}if(Ae)for(let Le=q+1;Le<E;Le++)Ve.set(Le,q,j[Le])}}let Me=Math.min(E,k+1);if(le<E&&(A[le]=te.get(le,le)),k<Me&&(A[Me-1]=0),ue+1<Me&&(j[ue]=te.get(ue,Me-1)),j[Me-1]=0,Ce){for(let q=le;q<et;q++){for(let Le=0;Le<k;Le++)ge.set(Le,q,0);ge.set(q,q,1)}for(let q=le-1;q>=0;q--)if(A[q]!==0){for(let Le=q+1;Le<et;Le++){let Oe=0;for(let je=q;je<k;je++)Oe+=ge.get(je,q)*ge.get(je,Le);Oe=-Oe/ge.get(q,q);for(let je=q;je<k;je++)ge.set(je,Le,ge.get(je,Le)+Oe*ge.get(je,q))}for(let Le=q;Le<k;Le++)ge.set(Le,q,-ge.get(Le,q));ge.set(q,q,1+ge.get(q,q));for(let Le=0;Le<q-1;Le++)ge.set(Le,q,0)}else{for(let Le=0;Le<k;Le++)ge.set(Le,q,0);ge.set(q,q,1)}}if(Ae)for(let q=E-1;q>=0;q--){if(q<ue&&j[q]!==0)for(let Le=q+1;Le<E;Le++){let Oe=0;for(let je=q+1;je<E;je++)Oe+=Ve.get(je,q)*Ve.get(je,Le);Oe=-Oe/Ve.get(q+1,q);for(let je=q+1;je<E;je++)Ve.set(je,Le,Ve.get(je,Le)+Oe*Ve.get(je,q))}for(let Le=0;Le<E;Le++)Ve.set(Le,q,0);Ve.set(q,q,1)}let en=Me-1,jt=Number.EPSILON;for(;Me>0;){let q,Le;for(q=Me-2;q>=-1&&q!==-1;q--){const Oe=Number.MIN_VALUE+jt*Math.abs(A[q]+Math.abs(A[q+1]));if(Math.abs(j[q])<=Oe||Number.isNaN(j[q])){j[q]=0;break}}if(q===Me-2)Le=4;else{let Oe;for(Oe=Me-1;Oe>=q&&Oe!==q;Oe--){let je=(Oe!==Me?Math.abs(j[Oe]):0)+(Oe!==q+1?Math.abs(j[Oe-1]):0);if(Math.abs(A[Oe])<=jt*je){A[Oe]=0;break}}Oe===q?Le=3:Oe===Me-1?Le=1:(Le=2,q=Oe)}switch(q++,Le){case 1:{let Oe=j[Me-2];j[Me-2]=0;for(let je=Me-2;je>=q;je--){let _t=Jt(A[je],Oe),Zt=A[je]/_t,hn=Oe/_t;if(A[je]=_t,je!==q&&(Oe=-hn*j[je-1],j[je-1]=Zt*j[je-1]),Ae)for(let an=0;an<E;an++)_t=Zt*Ve.get(an,je)+hn*Ve.get(an,Me-1),Ve.set(an,Me-1,-hn*Ve.get(an,je)+Zt*Ve.get(an,Me-1)),Ve.set(an,je,_t)}break}case 2:{let Oe=j[q-1];j[q-1]=0;for(let je=q;je<Me;je++){let _t=Jt(A[je],Oe),Zt=A[je]/_t,hn=Oe/_t;if(A[je]=_t,Oe=-hn*j[je],j[je]=Zt*j[je],Ce)for(let an=0;an<k;an++)_t=Zt*ge.get(an,je)+hn*ge.get(an,q-1),ge.set(an,q-1,-hn*ge.get(an,je)+Zt*ge.get(an,q-1)),ge.set(an,je,_t)}break}case 3:{const Oe=Math.max(Math.abs(A[Me-1]),Math.abs(A[Me-2]),Math.abs(j[Me-2]),Math.abs(A[q]),Math.abs(j[q])),je=A[Me-1]/Oe,_t=A[Me-2]/Oe,Zt=j[Me-2]/Oe,hn=A[q]/Oe,an=j[q]/Oe,ve=((_t+je)*(_t-je)+Zt*Zt)/2,fr=je*Zt*(je*Zt);let Zn=0;ve===0&&fr===0||(Zn=ve<0?0-Math.sqrt(ve*ve+fr):Math.sqrt(ve*ve+fr),Zn=fr/(ve+Zn));let Qn=(hn+je)*(hn-je)+Zn,Hr=hn*an;for(let ft=q;ft<Me-1;ft++){let St=Jt(Qn,Hr);St===0&&(St=Number.MIN_VALUE);let wt=Qn/St,bt=Hr/St;if(ft!==q&&(j[ft-1]=St),Qn=wt*A[ft]+bt*j[ft],j[ft]=wt*j[ft]-bt*A[ft],Hr=bt*A[ft+1],A[ft+1]=wt*A[ft+1],Ae)for(let Ge=0;Ge<E;Ge++)St=wt*Ve.get(Ge,ft)+bt*Ve.get(Ge,ft+1),Ve.set(Ge,ft+1,-bt*Ve.get(Ge,ft)+wt*Ve.get(Ge,ft+1)),Ve.set(Ge,ft,St);if(St=Jt(Qn,Hr),St===0&&(St=Number.MIN_VALUE),wt=Qn/St,bt=Hr/St,A[ft]=St,Qn=wt*j[ft]+bt*A[ft+1],A[ft+1]=-bt*j[ft]+wt*A[ft+1],Hr=bt*j[ft+1],j[ft+1
vendor: 4,398 bytes, line 8
8]=wt*j[ft+1],Ce&&ft<k-1)for(let Ge=0;Ge<k;Ge++)St=wt*ge.get(Ge,ft)+bt*ge.get(Ge,ft+1),ge.set(Ge,ft+1,-bt*ge.get(Ge,ft)+wt*ge.get(Ge,ft+1)),ge.set(Ge,ft,St)}j[Me-2]=Qn;break}case 4:if(A[q]<=0&&(A[q]=A[q]<0?-A[q]:0,Ae))for(let Oe=0;Oe<=en;Oe++)Ve.set(Oe,q,-Ve.get(Oe,q));for(;q<en&&!(A[q]>=A[q+1]);){let Oe=A[q];if(A[q]=A[q+1],A[q+1]=Oe,Ae&&q<E-1)for(let je=0;je<E;je++)Oe=Ve.get(je,q+1),Ve.set(je,q+1,Ve.get(je,q)),Ve.set(je,q,Oe);if(Ce&&q<k-1)for(let je=0;je<k;je++)Oe=ge.get(je,q+1),ge.set(je,q+1,ge.get(je,q)),ge.set(je,q,Oe);q++}Me--}}if(mt){let q=Ve;Ve=ge,ge=q}this.m=k,this.n=E,this.s=A,this.U=ge,this.V=Ve}solve(S){let b=S,k=this.threshold,E=this.s.length,F=Ne.zeros(E,E);for(let et=0;et<E;et++)Math.abs(this.s[et])<=k?F.set(et,et,0):F.set(et,et,1/this.s[et]);let B=this.U,Q=this.rightSingularVectors,te=Q.mmul(F),Ce=Q.rows,Ae=B.rows,mt=Ne.zeros(Ce,Ae);for(let et=0;et<Ce;et++)for(let it=0;it<Ae;it++){let A=0;for(let ge=0;ge<E;ge++)A+=te.get(et,ge)*B.get(it,ge);mt.set(et,it,A)}return mt.mmul(b)}solveForDiagonal(S){return this.solve(Ne.diag(S))}inverse(){let S=this.V,b=this.threshold,k=S.rows,E=S.columns,F=new Ne(k,this.s.length);for(let Ae=0;Ae<k;Ae++)for(let mt=0;mt<E;mt++)Math.abs(this.s[mt])>b&&F.set(Ae,mt,S.get(Ae,mt)/this.s[mt]);let B=this.U,Q=B.rows,te=B.columns,Ce=new Ne(k,Q);for(let Ae=0;Ae<k;Ae++)for(let mt=0;mt<Q;mt++){let et=0;for(let it=0;it<te;it++)et+=F.get(Ae,it)*B.get(mt,it);Ce.set(Ae,mt,et)}return Ce}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let S=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,b=0,k=this.s;for(let E=0,F=k.length;E<F;E++)k[E]>S&&b++;return b}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Ne.diag(this.s)}}function Yn(M,S,b=!1){return M=Wt.checkMatrix(M),S=Wt.checkMatrix(S),b?new cn(M).solve(S):M.isSquare()?new yn(M).solve(S):new fn(M).solve(S)}function Dn(M,S){let b=[];for(let k=0;k<M;k++)k!==S&&b.push(k);return b}function zn(M,S,b,k=1e-9,E=1e-9){if(M>E)return new Array(S.rows+1).fill(0);{let F=S.addRow(b,[0]);for(let B=0;B<F.rows;B++)Math.abs(F.get(B,0))<k&&F.set(B,0,0);return F.to1DArray()}}class De{constructor(S,b={}){const{assumeSymmetric:k=!1}=b;if(!(S=Wt.checkMatrix(S)).isSquare())throw new Error("Matrix is not a square matrix");if(S.isEmpty())throw new Error("Matrix must be non-empty");let E,F,B=S.columns,Q=new Ne(B,B),te=new Float64Array(B),Ce=new Float64Array(B),Ae=S,mt=!1;if(mt=!!k||S.isSymmetric(),mt){for(E=0;E<B;E++)for(F=0;F<B;F++)Q.set(E,F,Ae.get(E,F));(function(et,it,A,ge){let Ve,j,oe,Y,le,ue,vt,Me;for(le=0;le<et;le++)A[le]=ge.get(et-1,le);for(Y=et-1;Y>0;Y--){for(Me=0,oe=0,ue=0;ue<Y;ue++)Me+=Math.abs(A[ue]);if(Me===0)for(it[Y]=A[Y-1],le=0;le<Y;le++)A[le]=ge.get(Y-1,le),ge.set(Y,le,0),ge.set(le,Y,0);else{for(ue=0;ue<Y;ue++)A[ue]/=Me,oe+=A[ue]*A[ue];for(Ve=A[Y-1],j=Math.sqrt(oe),Ve>0&&(j=-j),it[Y]=Me*j,oe-=Ve*j,A[Y-1]=Ve-j,le=0;le<Y;le++)it[le]=0;for(le=0;le<Y;le++){for(Ve=A[le],ge.set(le,Y,Ve),j=it[le]+ge.get(le,le)*Ve,ue=le+1;ue<=Y-1;ue++)j+=ge.get(ue,le)*A[ue],it[ue]+=ge.get(ue,le)*Ve;it[le]=j}for(Ve=0,le=0;le<Y;le++)it[le]/=oe,Ve+=it[le]*A[le];for(vt=Ve/(oe+oe),le=0;le<Y;le++)it[le]-=vt*A[le];for(le=0;le<Y;le++){for(Ve=A[le],j=it[le],ue=le;ue<=Y-1;ue++)ge.set(ue,le,ge.get(ue,le)-(Ve*it[ue]+j*A[ue]));A[le]=ge.get(Y-1,le),ge.set(Y,le,0)}}A[Y]=oe}for(Y=0;Y<et-1;Y++){if(ge.set(et-1,Y,ge.get(Y,Y)),ge.set(Y,Y,1),oe=A[Y+1],oe!==0){for(ue=0;ue<=Y;ue++)A[ue]=ge.get(ue,Y+1)/oe;for(le=0;le<=Y;le++){for(j=0,ue=0;ue<=Y;ue++)j+=ge.get(ue,Y+1)*ge.get(ue,le);for(ue=0;ue<=Y;ue++)ge.set(ue,le,ge.get(ue,le)-j*A[ue])}}for(ue=0;ue<=Y;ue++)ge.set(ue,Y+1,0)}for(le=0;le<et;le++)A[le]=ge.get(et-1,le),ge.set(et-1,le,0);ge.set(et-1,et-1,1),it[0]=0})(B,Ce,te,Q),function(et,it,A,ge){let Ve,j,oe,Y,le,ue,vt,Me,en,jt,q,Le,Oe,je,_t,Zt;for(oe=1;oe<et;oe++)it[oe-1]=it[oe];it[et-1]=0;let hn=0,an=0,ve=Number.EPSILON;for(ue=0;ue<et;ue++){for(an=Math.max(an,Math.abs(A[ue])+Math.abs(it[ue])),vt=ue;vt<et&&!(Math.abs(it[vt])<=ve*an);)vt++;if(vt>ue)do{for(Ve=A[ue],Me=(A[ue+1]-Ve)/(2*it[ue]),en=Jt(Me,1),Me<0&&(en=-en),A[ue]=it[ue]/(Me+en),A[ue+1]=it[ue]*(Me+en),jt=A[ue+1],j=Ve-A[ue],oe=ue+2;oe<et;oe++)A[oe]-=j;for(hn+=j,Me=A[vt],q=1,Le=q,Oe=q,je=it[ue+1],_t=0,Zt=0,oe=vt-1;oe>=ue;
vendor: 12,427 bytes, line 8
8oe--)for(Oe=Le,Le=q,Zt=_t,Ve=q*it[oe],j=q*Me,en=Jt(Me,it[oe]),it[oe+1]=_t*en,_t=it[oe]/en,q=Me/en,Me=q*A[oe]-_t*Ve,A[oe+1]=j+_t*(q*Ve+_t*A[oe]),le=0;le<et;le++)j=ge.get(le,oe+1),ge.set(le,oe+1,_t*ge.get(le,oe)+q*j),ge.set(le,oe,q*ge.get(le,oe)-_t*j);Me=-_t*Zt*Oe*je*it[ue]/jt,it[ue]=_t*Me,A[ue]=q*Me}while(Math.abs(it[ue])>ve*an);A[ue]=A[ue]+hn,it[ue]=0}for(oe=0;oe<et-1;oe++){for(le=oe,Me=A[oe],Y=oe+1;Y<et;Y++)A[Y]<Me&&(le=Y,Me=A[Y]);if(le!==oe)for(A[le]=A[oe],A[oe]=Me,Y=0;Y<et;Y++)Me=ge.get(Y,oe),ge.set(Y,oe,ge.get(Y,le)),ge.set(Y,le,Me)}}(B,Ce,te,Q)}else{let et=new Ne(B,B),it=new Float64Array(B);for(F=0;F<B;F++)for(E=0;E<B;E++)et.set(E,F,Ae.get(E,F));(function(A,ge,Ve,j){let oe,Y,le,ue,vt,Me,en,jt=A-1;for(Me=1;Me<=jt-1;Me++){for(en=0,ue=Me;ue<=jt;ue++)en+=Math.abs(ge.get(ue,Me-1));if(en!==0){for(le=0,ue=jt;ue>=Me;ue--)Ve[ue]=ge.get(ue,Me-1)/en,le+=Ve[ue]*Ve[ue];for(Y=Math.sqrt(le),Ve[Me]>0&&(Y=-Y),le-=Ve[Me]*Y,Ve[Me]=Ve[Me]-Y,vt=Me;vt<A;vt++){for(oe=0,ue=jt;ue>=Me;ue--)oe+=Ve[ue]*ge.get(ue,vt);for(oe/=le,ue=Me;ue<=jt;ue++)ge.set(ue,vt,ge.get(ue,vt)-oe*Ve[ue])}for(ue=0;ue<=jt;ue++){for(oe=0,vt=jt;vt>=Me;vt--)oe+=Ve[vt]*ge.get(ue,vt);for(oe/=le,vt=Me;vt<=jt;vt++)ge.set(ue,vt,ge.get(ue,vt)-oe*Ve[vt])}Ve[Me]=en*Ve[Me],ge.set(Me,Me-1,en*Y)}}for(ue=0;ue<A;ue++)for(vt=0;vt<A;vt++)j.set(ue,vt,ue===vt?1:0);for(Me=jt-1;Me>=1;Me--)if(ge.get(Me,Me-1)!==0){for(ue=Me+1;ue<=jt;ue++)Ve[ue]=ge.get(ue,Me-1);for(vt=Me;vt<=jt;vt++){for(Y=0,ue=Me;ue<=jt;ue++)Y+=Ve[ue]*j.get(ue,vt);for(Y=Y/Ve[Me]/ge.get(Me,Me-1),ue=Me;ue<=jt;ue++)j.set(ue,vt,j.get(ue,vt)+Y*Ve[ue])}}})(B,et,it,Q),function(A,ge,Ve,j,oe){let Y,le,ue,vt,Me,en,jt,q,Le,Oe,je,_t,Zt,hn,an,ve=A-1,fr=A-1,Zn=Number.EPSILON,Qn=0,Hr=0,ft=0,St=0,wt=0,bt=0,Ge=0,Zs=0;for(Y=0;Y<A;Y++)for((Y<0||Y>fr)&&(Ve[Y]=oe.get(Y,Y),ge[Y]=0),le=Math.max(Y-1,0);le<A;le++)Hr+=Math.abs(oe.get(Y,le));for(;ve>=0;){for(vt=ve;vt>0&&(bt=Math.abs(oe.get(vt-1,vt-1))+Math.abs(oe.get(vt,vt)),bt===0&&(bt=Hr),!(Math.abs(oe.get(vt,vt-1))<Zn*bt));)vt--;if(vt===ve)oe.set(ve,ve,oe.get(ve,ve)+Qn),Ve[ve]=oe.get(ve,ve),ge[ve]=0,ve--,Zs=0;else if(vt===ve-1){if(jt=oe.get(ve,ve-1)*oe.get(ve-1,ve),ft=(oe.get(ve-1,ve-1)-oe.get(ve,ve))/2,St=ft*ft+jt,Ge=Math.sqrt(Math.abs(St)),oe.set(ve,ve,oe.get(ve,ve)+Qn),oe.set(ve-1,ve-1,oe.get(ve-1,ve-1)+Qn),q=oe.get(ve,ve),St>=0){for(Ge=ft>=0?ft+Ge:ft-Ge,Ve[ve-1]=q+Ge,Ve[ve]=Ve[ve-1],Ge!==0&&(Ve[ve]=q-jt/Ge),ge[ve-1]=0,ge[ve]=0,q=oe.get(ve,ve-1),bt=Math.abs(q)+Math.abs(Ge),ft=q/bt,St=Ge/bt,wt=Math.sqrt(ft*ft+St*St),ft/=wt,St/=wt,le=ve-1;le<A;le++)Ge=oe.get(ve-1,le),oe.set(ve-1,le,St*Ge+ft*oe.get(ve,le)),oe.set(ve,le,St*oe.get(ve,le)-ft*Ge);for(Y=0;Y<=ve;Y++)Ge=oe.get(Y,ve-1),oe.set(Y,ve-1,St*Ge+ft*oe.get(Y,ve)),oe.set(Y,ve,St*oe.get(Y,ve)-ft*Ge);for(Y=0;Y<=fr;Y++)Ge=j.get(Y,ve-1),j.set(Y,ve-1,St*Ge+ft*j.get(Y,ve)),j.set(Y,ve,St*j.get(Y,ve)-ft*Ge)}else Ve[ve-1]=q+ft,Ve[ve]=q+ft,ge[ve-1]=Ge,ge[ve]=-Ge;ve-=2,Zs=0}else{if(q=oe.get(ve,ve),Le=0,jt=0,vt<ve&&(Le=oe.get(ve-1,ve-1),jt=oe.get(ve,ve-1)*oe.get(ve-1,ve)),Zs===10){for(Qn+=q,Y=0;Y<=ve;Y++)oe.set(Y,Y,oe.get(Y,Y)-q);bt=Math.abs(oe.get(ve,ve-1))+Math.abs(oe.get(ve-1,ve-2)),q=Le=.75*bt,jt=-.4375*bt*bt}if(Zs===30&&(bt=(Le-q)/2,bt=bt*bt+jt,bt>0)){for(bt=Math.sqrt(bt),Le<q&&(bt=-bt),bt=q-jt/((Le-q)/2+bt),Y=0;Y<=ve;Y++)oe.set(Y,Y,oe.get(Y,Y)-bt);Qn+=bt,q=Le=jt=.964}for(Zs+=1,Me=ve-2;Me>=vt&&(Ge=oe.get(Me,Me),wt=q-Ge,bt=Le-Ge,ft=(wt*bt-jt)/oe.get(Me+1,Me)+oe.get(Me,Me+1),St=oe.get(Me+1,Me+1)-Ge-wt-bt,wt=oe.get(Me+2,Me+1),bt=Math.abs(ft)+Math.abs(St)+Math.abs(wt),ft/=bt,St/=bt,wt/=bt,Me!==vt)&&!(Math.abs(oe.get(Me,Me-1))*(Math.abs(St)+Math.abs(wt))<Zn*(Math.abs(ft)*(Math.abs(oe.get(Me-1,Me-1))+Math.abs(Ge)+Math.abs(oe.get(Me+1,Me+1)))));)Me--;for(Y=Me+2;Y<=ve;Y++)oe.set(Y,Y-2,0),Y>Me+2&&oe.set(Y,Y-3,0);for(ue=Me;ue<=ve-1&&(hn=ue!==ve-1,ue!==Me&&(ft=oe.get(ue,ue-1),St=oe.get(ue+1,ue-1),wt=hn?oe.get(ue+2,ue-1):0,q=Math.abs(ft)+Math.abs(St)+Math.abs(wt),q!==0&&(ft/=q,St/=q,wt/=q)),q!==0);ue++)if(bt=Math.sqrt(ft*ft+St*St+wt*wt),ft<0&&(bt=-bt),bt!==0){for(ue!==Me?oe.set(ue,ue-1,-bt*q):vt!==Me&&oe.set(ue,ue-1,-oe.get(ue,ue-1)),ft+=bt,q=ft/bt,Le=St/bt,Ge=wt/bt,St/=ft,wt/=ft,le=ue;le<A;le++)ft=oe.get(ue,le)+St*oe.get(ue+1,le),hn&&(ft+=wt*oe.get(ue+2,le),oe.set(ue+2,le,oe.get(ue+2,le)-ft*Ge)),oe.set(ue,le,oe.get(ue,le)-ft*q),oe.set(ue+1,le,oe.get(ue+1,le)-ft*Le);for(Y=0;Y<=Math.min(ve,ue+3);Y++)ft=q*oe.get(Y,ue)+Le*oe.get(Y,ue+1),hn&&(ft+=Ge*oe.get(Y,ue+2),oe.set(Y,ue+2,oe.get(Y,ue+2)-ft*wt)),oe.set(Y,ue,oe.get(Y,ue)-ft),oe.set(Y,ue+1,oe.get(Y,ue+1)-ft*St);for(Y=0;Y<=fr;Y++)ft=q*j.get(Y,ue)+Le*j.get(Y,ue+1),hn&&(ft+=Ge*j.get(Y,ue+2),j.set(Y,ue+2,j.get(Y,ue+2)-ft*wt)),j.set(Y,ue,j.get(Y,ue)-ft),j.set(Y,ue+1,j.get(Y,ue+1)-ft*St)}}}if(Hr!==0){for(ve=A-1;ve>=0;ve--)if(ft=Ve[ve],St=ge[ve],St===0)for(vt=ve,oe.set(ve,ve,1),Y=ve-1;Y>=0;Y--){for(jt=oe.get(Y,Y)-ft,wt=0,le=vt;le<=ve;le++)wt+=oe.get(Y,le)*oe.get(le,ve);if(ge[Y]<0)Ge=jt,bt=wt;else if(vt=Y,ge[Y]===0?oe.set(Y,ve,jt!==0?-wt/jt:-wt/(Zn*Hr)):(q=oe.get(Y,Y+1),Le=oe.get(Y+1,Y),St=(Ve[Y]-ft)*(Ve[Y]-ft)+ge[Y]*ge[Y],en=(q*bt-Ge*wt)/St,oe.set(Y,ve,en),oe.set(Y+1,ve,Math.abs(q)>Math.abs(Ge)?(-wt-jt*en)/q:(-bt-Le*en)/Ge)),en=Math.abs(oe.get(Y,ve)),Zn*en*en>1)for(le=Y;le<=ve;le++)oe.set(le,ve,oe.get(le,ve)/en)}else if(St<0)for(vt=ve-1,Math.abs(oe.get(ve,ve-1))>Math.abs(oe.get(ve-1,ve))?(oe.set(ve-1,ve-1,St/oe.get(ve,ve-1)),oe.set(ve-1,ve,-(oe.get(ve,ve)-ft)/oe.get(ve,ve-1))):(an=Ye(0,-oe.get(ve-1,ve),oe.get(ve-1,ve-1)-ft,St),oe.set(ve-1,ve-1,an[0]),oe.set(ve-1,ve,an[1])),oe.set(ve,ve-1,0),oe.set(ve,ve,1),Y=ve-2;Y>=0;Y--){for(Oe=0,je=0,le=vt;le<=ve;le++)Oe+=oe.get(Y,le)*oe.get(le,ve-1),je+=oe.get(Y,le)*oe.get(le,ve);if(jt=oe.get(Y,Y)-ft,ge[Y]<0)Ge=jt,wt=Oe,bt=je;else if(vt=Y,ge[Y]===0?(an=Ye(-Oe,-je,jt,St),oe.set(Y,ve-1,an[0]),oe.set(Y,ve,an[1])):(q=oe.get(Y,Y+1),Le=oe.get(Y+1,Y),_t=(Ve[Y]-ft)*(Ve[Y]-ft)+ge[Y]*ge[Y]-St*St,Zt=2*(Ve[Y]-ft)*St,_t===0&&Zt===0&&(_t=Zn*Hr*(Math.abs(jt)+Math.abs(St)+Math.abs(q)+Math.abs(Le)+Math.abs(Ge))),an=Ye(q*wt-Ge*Oe+St*je,q*bt-Ge*je-St*Oe,_t,Zt),oe.set(Y,ve-1,an[0]),oe.set(Y,ve,an[1]),Math.abs(q)>Math.abs(Ge)+Math.abs(St)?(oe.set(Y+1,ve-1,(-Oe-jt*oe.get(Y,ve-1)+St*oe.get(Y,ve))/q),oe.set(Y+1,ve,(-je-jt*oe.get(Y,ve)-St*oe.get(Y,ve-1))/q)):(an=Ye(-wt-Le*oe.get(Y,ve-1),-bt-Le*oe.get(Y,ve),Ge,St),oe.set(Y+1,ve-1,an[0]),oe.set(Y+1,ve,an[1]))),en=Math.max(Math.abs(oe.get(Y,ve-1)),Math.abs(oe.get(Y,ve))),Zn*en*en>1)for(le=Y;le<=ve;le++)oe.set(le,ve-1,oe.get(le,ve-1)/en),oe.set(le,ve,oe.get(le,ve)/en)}for(Y=0;Y<A;Y++)if(Y<0||Y>fr)for(le=Y;le<A;le++)j.set(Y,le,oe.get(Y,le));for(le=A-1;le>=0;le--)for(Y=0;Y<=fr;Y++){for(Ge=0,ue=0;ue<=Math.min(le,fr);ue++)Ge+=j.get(Y,ue)*oe.get(ue,le);j.set(Y,le,Ge)}}}(B,Ce,te,Q,et)}this.n=B,this.e=Ce,this.d=te,this.V=Q}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let S,b,k=this.n,E=this.e,F=this.d,B=new Ne(k,k);for(S=0;S<k;S++){for(b=0;b<k;b++)B.set(S,b,0);B.set(S,S,F[S]),E[S]>0?B.set(S,S+1,E[S]):E[S]<0&&B.set(S,S-1,E[S])}return B}}function Ye(M,S,b,k){let E,F;return Math.abs(b)>Math.abs(k)?(E=k/b,F=b+E*k,[(M+E*S)/F,(S-E*M)/F]):(E=b/k,F=k+E*b,[(E*M+S)/F,(E*S-M)/F])}class rt{constructor(S){if(!(S=Wt.checkMatrix(S)).isSymmetric())throw new Error("Matrix is not symmetric");let b,k,E,F=S,B=F.rows,Q=new Ne(B,B),te=!0;for(k=0;k<B;k++){let Ce=0;for(E=0;E<k;E++){let Ae=0;for(b=0;b<E;b++)Ae+=Q.get(E,b)*Q.get(k,b);Ae=(F.get(k,E)-Ae)/Q.get(E,E),Q.set(k,E,Ae),Ce+=Ae*Ae}for(Ce=F.get(k,k)-Ce,te&&(te=Ce>0),Q.set(k,k,Math.sqrt(Math.max(Ce,0))),E=k+1;E<B;E++)Q.set(k,E,0)}this.L=Q,this.positiveDefinite=te}isPositiveDefinite(){return this.positiveDefinite}solve(S){S=Wt.checkMatrix(S);let b=this.L,k=b.rows;if(S.rows!==k)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let E,F,B,Q=S.columns,te=S.clone();for(B=0;B<k;B++)for(F=0;F<Q;F++){for(E=0;E<B;E++)te.set(B,F,te.get(B,F)-te.get(E,F)*b.get(B,E));te.set(B,F,te.get(B,F)/b.get(B,B))}for(B=k-1;B>=0;B--)for(F=0;F<Q;F++){for(E=B+1;E<k;E++)te.set(B,F,te.get(B,F)-te.get(E,F)*b.get(E,B));te.set(B,F,te.get(B,F)/b.get(B,B))}return te}get lowerTriangularMatrix(){return this.L}}class qe{constructor(S,b={}){S=Wt.checkMatrix(S);let{Y:k}=b;const{scaleScores:E=!1,maxIterations:F=1e3,terminationCriteria:B=1e-10}=b;let Q;if(k){if(k=Xe.isAnyArray(k)&&typeof k[0]=="number"?Ne.columnVector(k):Wt.checkMatrix(k),k.rows!==S.rows)throw new Error("Y should have the same number of rows as X");Q=k.getColumnVector(0)}else Q=S.getColumnVector(0);let te,Ce,Ae,mt,et=1;for(let it=0;it<F&&et>B;it++)Ae=S.transpose().mmul(Q).div(Q.transpose().mmul(Q).get(0,0)),Ae=Ae.div(Ae.norm()),te=S.mmul(Ae).div(Ae.transpose().mmul(Ae).get(0,0)),it>0&&(et=te.clone().sub(mt).pow(2).sum()),mt=te.clone(),k?(Ce=k.transpose().mmul(te).div(te.transpose().mmul(te).get(0,0)),Ce=Ce.div(Ce.norm()),Q=k.mmul(Ce).div(Ce.transpose().mmul(Ce).get(0,0))):Q=te;if(k){let it=S.transpose().mmul(te).div(te.transpose().mmul(te).get(0,0));it=it.div(it.norm());let A=S.clone().sub(te.clone().mmul(it.transpose())),ge=Q.transpose().mmul(te).div(te.transpose().mmul(te).get(0,0)),Ve=k.clone().sub(te.clone().mulS(ge.get(0,0)).mmul(Ce.transpose()));this.t=te,this.p=it.transpose(),this.w=Ae.transpose(),this.q=Ce,this.u=Q,this.s=te.transpose().mmul(te),this.xResidual=A,this.yResidual=Ve,this.betas=ge}else this.w=Ae.transpose(),this.s=te.transpose().mmul(te).sqrt(),this.t=E?te.clone().div(this.s.get(0,0)):te,this.xResidual=S.sub(te.mmul(Ae.transpose()))}}ye.AbstractMatrix=Ee,ye.CHO=rt,ye.CholeskyDecomposition=rt,ye.DistanceMatrix=G,ye.EVD=De,ye.EigenvalueDecomposition=De,ye.LU=yn,ye.LuDecomposition=yn,ye.Matrix=Ne,ye.MatrixColumnSelectionView=class extends Be{constructor(M,S){Qe(M,S),super(M,M.rows,S.length),this.columnIndices=S}set(M,S,b){return this.matrix.set(M,this.columnIndices[S],b),this}get(M,S){return this.matrix.get(M,this.columnIndices[S])}},ye.MatrixColumnView=class extends Be{constructor(M,S){H(M,S),super(M,M.rows,1),this.column=S}set(M,S,b){return this.matrix.set(M,this.column,b),this}get(M){return this.matrix.get(M,this.column)}},ye.MatrixFlipColumnView=class extends Be{constructor(M){super(M,M.rows,M.columns)}set(M,S,b){return this.matrix.set(M,this.columns-S-1,b),this}get(M,S){return this.matrix.get(M,this.columns-S-1)}},ye.MatrixFlipRowView=class extends Be{constructor(M){super(M,M.rows,M.columns)}set(M,S,b){return this.matrix.set(this.rows-M-1,S,b),this}get(M,S){return this.matrix.get(this.rows-M-1,S)}},ye.MatrixRowSelectionView=class extends Be{constructor(M,S){Se(M,S),super(M,S.length,M.columns),this.rowIndices=S}set(M,S,b){return this.matrix.set(this.rowIndices[M],S,b),this}get(M,S){return this.matrix.get(this.rowIndices[M],S)}},ye.MatrixRowView=class extends Be{constructor(M,S){K(M,S),super(M,1,M.columns),this.row=S}set(M,S,b){return this.matrix.set(this.row,S,b),this}get(M,S){return this.matrix.get(this.row,S)}},ye.MatrixSelectionView=Ze,ye.MatrixSubView=class extends Be{constructor(M,S,b,k,E){Ke(M,S,b,k,E),super(M,b-S+1,E-k+1),this.startRow=S,this.startColumn=k}set(M,S,b){return this.matrix.set(this.startRow+M,this.startColumn+S,b),this}get(M,S){return this.matrix.get(this.startRow+M,this.startColumn+S)}},ye.MatrixTransposeView=class extends Be{constructor(M){super(M,M.columns,M.rows)}set(M,S,b){return this.matrix.set(S,M,b),this}get(M,S){return this.matrix.get(S,M)}},ye.NIPALS=qe,ye.Nipals=qe,ye.QR=fn,ye.QrDecomposition=fn,ye.SVD=cn,ye.SingularValueDecomposition=cn,ye.SymmetricMatrix=Pe,ye.WrapperMatrix1D=$t,ye.WrapperMatrix2D=Wt,ye.correlation=function(M,S=M,b={}){M=new Ne(M);let k=!1;if(typeof S!="object"||Ne.isMatrix(S)||Xe.isAnyArray(S)?S=new Ne(S):(b=S,S=M,k=!0),M.rows!==S.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:E=!0,scale:F=!0}=b;E&&(M.center("column"),k||S.center("column")),F&&(M.scale("column"),k||S.scale("column"));const B=M.standardDeviation("column",{unbiased:!0}),Q=k?B:S.standardDeviation("column",{unbiased:!0}),te=M.transpose().mmul(S);for(let Ce=0;Ce<te.rows;Ce++)for(let Ae=0;Ae<te.columns;Ae++)te.set(Ce,Ae,te.get(Ce,Ae)*(1/(B[Ce]*Q[Ae]))*(1/(M.rows-1)));return te},ye.covariance=function(M,S=M,b={}){M=new Ne(M);let k=!1;if(typeof S!="object"||Ne.isMatrix(S)||Xe.isAnyArray(S)?S=new Ne(S):(b=S,S=M,k=!0),M.rows!==S.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:E=!0}
8=b;E&&(M=M.center("column"),k||(S=S.center("column")));const F=M.transpose().mmul(S);for(let B=0;B<F.rows;B++)for(let Q=0;Q<F.columns;Q++)F.set(B,Q,F.get(B,Q)*(1/(M.rows-1)));return F},ye.default=Ne,ye.determinant=function M(S){if((S=Ne.checkMatrix(S)).isSquare()){if(S.columns===0)return 1;let b,k,E,F;if(S.columns===2)return b=S.get(0,0),k=S.get(0,1),E=S.get(1,0),F=S.get(1,1),b*F-k*E;if(S.columns===3){let B,Q,te;return B=new Ze(S,[1,2],[1,2]),Q=new Ze(S,[1,2],[0,2]),te=new Ze(S,[1,2],[0,1]),b=S.get(0,0),k=S.get(0,1),E=S.get(0,2),b*M(B)-k*M(Q)+E*M(te)}return new yn(S).determinant}throw Error("determinant can only be calculated for a square matrix")},ye.inverse=function(M,S=!1){return M=Wt.checkMatrix(M),S?new cn(M).inverse():Yn(M,Ne.eye(M.rows))},ye.linearDependencies=function(M,S={}){const{thresholdValue:b=1e-9,thresholdError:k=1e-9}=S;let E=(M=Ne.checkMatrix(M)).rows,F=new Ne(E,E);for(let B=0;B<E;B++){let Q=Ne.columnVector(M.getRow(B)),te=M.subMatrixRow(Dn(E,B)).transpose(),Ce=new cn(te).solve(Q),Ae=Ne.sub(Q,te.mmul(Ce)).abs().max();F.setRow(B,zn(Ae,Ce,B,b,k))}return F},ye.pseudoInverse=function(M,S=Number.EPSILON){if((M=Ne.checkMatrix(M)).isEmpty())return M.transpose();let b=new cn(M,{autoTranspose:!0}),k=b.leftSingularVectors,E=b.rightSingularVectors,F=b.diagonal;for(let B=0;B<F.length;B++)Math.abs(F[B])>S?F[B]=1/F[B]:F[B]=0;return E.mmul(Ne.diag(F).mmul(k.transpose()))},ye.solve=Yn,ye.wrap=function(M,S){if(Xe.isAnyArray(M))return M[0]&&Xe.isAnyArray(M[0])?new Wt(M):new $t(M,S);throw new Error("the argument is not an array")}},717:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K=this,H="";K.next=function(){var pe=K.b,Se=K.c,Qe=K.d,Ke=K.a;return pe=pe<<25^pe>>>7^Se,Se=Se-Qe|0,Qe=Qe<<24^Qe>>>8^Ke,Ke=Ke-pe|0,K.b=pe=pe<<20^pe>>>12^Se,K.c=Se=Se-Qe|0,K.d=Qe<<16^Se>>>16^Ke,K.a=Ke-pe|0},K.a=0,K.b=0,K.c=-1640531527,K.d=1367130551,ke===Math.floor(ke)?(K.a=ke/4294967296|0,K.b=0|ke):H+=ke;for(var ie=0;ie<H.length+20;ie++)K.b^=0|H.charCodeAt(ie),K.next()}function ct(ke,K){return K.a=ke.a,K.b=ke.b,K.c=ke.c,K.d=ke.d,K}function Te(ke,K){var H=new Nt(ke),ie=K&&K.state,pe=function(){return(H.next()>>>0)/4294967296};return pe.double=function(){do var Se=((H.next()>>>11)+(H.next()>>>0)/4294967296)/2097152;while(Se===0);return Se},pe.int32=H.next,pe.quick=pe,ie&&(typeof ie=="object"&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.tychei=Te})(0,Et=Z.nmd(Et),Z.amdD)},718:(Et,ye,Z)=>{Z.r(ye),Z.d(ye,{default:()=>Vt});var Xe=Z(788);function Vt(ht){var Nt,ct=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!(0,Xe.isAnyArray)(ht))throw new TypeError("input must be an array");if(ht.length===0)throw new TypeError("input must not be empty");if(ct.output!==void 0){if(!(0,Xe.isAnyArray)(ct.output))throw new TypeError("output option must be an array if specified");Nt=ct.output}else Nt=new Array(ht.length);var Te=function(Ke){var de=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!(0,Xe.isAnyArray)(Ke))throw new TypeError("input must be an array");if(Ke.length===0)throw new TypeError("input must not be empty");var Fe=de.fromIndex,tt=Fe===void 0?0:Fe,Ee=de.toIndex,Re=Ee===void 0?Ke.length:Ee;if(tt<0||tt>=Ke.length||!Number.isInteger(tt))throw new Error("fromIndex must be a positive integer smaller than length");if(Re<=tt||Re>Ke.length||!Number.isInteger(Re))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var pt=Ke[tt],Ne=tt+1;Ne<Re;Ne++)Ke[Ne]<pt&&(pt=Ke[Ne]);return pt}(ht),ke=function(Ke){var de=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!(0,Xe.isAnyArray)(Ke))throw new TypeError("input must be an array");if(Ke.length===0)throw new TypeError("input must not be empty");var Fe=de.fromIndex,tt=Fe===void 0?0:Fe,Ee=de.toIndex,Re=Ee===void 0?Ke.length:Ee;if(tt<0||tt>=Ke.length||!Number.isInteger(tt))throw new Error("fromIndex must be a positive integer smaller than length");if(Re<=tt||Re>Ke.length||!Number.isInteger(Re))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var pt=Ke[tt],Ne=tt+1;Ne<Re;Ne++)Ke[Ne]>pt&&(pt=Ke[Ne]);return pt}(ht);if(Te===ke)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var K=ct.min,H=K===void 0?ct.autoMinMax?Te:0:K,ie=ct.max,pe=ie===void 0?ct.autoMinMax?ke:1:ie;if(H>=pe)throw new RangeError("min option must be smaller than max option");for(var Se=(pe-H)/(ke-Te),Qe=0;Qe<ht.length;Qe++)Nt[Qe]=(ht[Qe]-Te)*Se+H;return Nt}},743:function(Et,ye,Z){var Xe=this&&this.__awaiter||function(ct,Te,ke,K){return new(ke||(ke=Promise))(function(H,ie){function pe(Ke){try{Qe(K.next(Ke))}catch(de){ie(de)}}function Se(Ke){try{Qe(K.throw(Ke))}catch(de){ie(de)}}function Qe(Ke){var de;Ke.done?H(Ke.value):(de=Ke.value,de instanceof ke?de:new ke(function(Fe){Fe(de)})).then(pe,Se)}Qe((K=K.apply(ct,Te||[])).next())})},Vt=this&&this.__generator||function(ct,Te){var ke,K,H,ie={label:0,sent:function(){if(1&H[0])throw H[1];return H[1]},trys:[],ops:[]},pe=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return pe.next=Se(0),pe.throw=Se(1),pe.return=Se(2),typeof Symbol=="function"&&(pe[Symbol.iterator]=function(){return this}),pe;function Se(Qe){return function(Ke){return function(de){if(ke)throw new TypeError("Generator is already executing.");for(;pe&&(pe=0,de[0]&&(ie=0)),ie;)try{if(ke=1,K&&(H=2&de[0]?K.return:de[0]?K.throw||((H=K.return)&&H.call(K),0):K.next)&&!(H=H.call(K,de[1])).done)return H;switch(K=0,H&&(de=[2&de[0],H.value]),de[0]){case 0:case 1:H=de;break;case 4:return ie.label++,{value:de[1],done:!1};case 5:ie.label++,K=de[1],de=[0];continue;case 7:de=ie.ops.pop(),ie.trys.pop();continue;default:if(!((H=(H=ie.trys).length>0&&H[H.length-1])||de[0]!==6&&de[0]!==2)){ie=0;continue}if(de[0]===3&&(!H||de[1]>H[0]&&de[1]<H[3])){ie.label=de[1];break}if(de[0]===6&&ie.label<H[1]){ie.label=H[1],H=de;break}if(H&&ie.label<H[2]){ie.label=H[2],ie.ops.push(de);break}H[2]&&ie.ops.pop(),ie.trys.pop();continue}de=Te.call(ct,ie)}catch(Fe){de=[6,Fe],K=0}finally{ke=H=0}if(5&de[0])throw de[1];return{value:de[0]?de[1]:void 0,done:!0}}([Qe,Ke])}}};
8Object.defineProperty(ye,"__esModule",{value:!0});var ht=Z(848),Nt=function(){function ct(){}return ct.prototype.initialize=function(){return Xe(this,void 0,void 0,function(){var Te,ke;return Vt(this,function(K){switch(K.label){case 0:return[4,ht.FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm")];case 1:return Te=K.sent(),ke=this,[4,ht.FaceLandmarker.createFromOptions(Te,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",delegate:"GPU"},outputFaceBlendshapes:!0,outputFacialTransformationMatrixes:!0,runningMode:"IMAGE",numFaces:1})];case 2:return ke.faceLandmarker=K.sent(),[2]}})})},ct.prototype.processFrame=function(Te){return Xe(this,void 0,void 0,function(){return Vt(this,function(ke){switch(ke.label){case 0:return this.faceLandmarker?[4,this.faceLandmarker.detect(Te)]:(console.error("FaceLandmarker is not loaded yet."),[2,null]);case 1:return[2,ke.sent()]}})})},ct}();ye.default=Nt},788:(Et,ye,Z)=>{Z.r(ye),Z.d(ye,{isAnyArray:()=>Vt});const Xe=Object.prototype.toString;function Vt(ht){const Nt=Xe.call(ht);return Nt.endsWith("Array]")&&!Nt.includes("Big")}},801:function(Et,ye,Z){var Xe;(function(Vt,ht,Nt){var ct,Te=256,ke=Nt.pow(Te,6),K=Nt.pow(2,52),H=2*K,ie=255;function pe(tt,Ee,Re){var pt=[],Ne=de(Ke((Ee=Ee==1?{entropy:!0}:Ee||{}).entropy?[tt,Fe(ht)]:tt??function(){try{var Be;return ct&&(Be=ct.randomBytes)?Be=Be(Te):(Be=new Uint8Array(Te),(Vt.crypto||Vt.msCrypto).getRandomValues(Be)),Fe(Be)}catch{var Ze=Vt.navigator,$t=Ze&&Ze.plugins;return[+new Date,Vt,$t,Vt.screen,Fe(ht)]}}(),3),pt),Pe=new Se(pt),G=function(){for(var Be=Pe.g(6),Ze=ke,$t=0;Be<K;)Be=(Be+$t)*Te,Ze*=Te,$t=Pe.g(1);for(;Be>=H;)Be/=2,Ze/=2,$t>>>=1;return(Be+$t)/Ze};return G.int32=function(){return 0|Pe.g(4)},G.quick=function(){return Pe.g(4)/4294967296},G.double=G,de(Fe(Pe.S),ht),(Ee.pass||Re||function(Be,Ze,$t,Wt){return Wt&&(Wt.S&&Qe(Wt,Pe),Be.state=function(){return Qe(Pe,{})}),$t?(Nt.random=Be,Ze):Be})(G,Ne,"global"in Ee?Ee.global:this==Nt,Ee.state)}function Se(tt){var Ee,Re=tt.length,pt=this,Ne=0,Pe=pt.i=pt.j=0,G=pt.S=[];for(Re||(tt=[Re++]);Ne<Te;)G[Ne]=Ne++;for(Ne=0;Ne<Te;Ne++)G[Ne]=G[Pe=ie&Pe+tt[Ne%Re]+(Ee=G[Ne])],G[Pe]=Ee;(pt.g=function(Be){for(var Ze,$t=0,Wt=pt.i,yn=pt.j,Jt=pt.S;Be--;)Ze=Jt[Wt=ie&Wt+1],$t=$t*Te+Jt[ie&(Jt[Wt]=Jt[yn=ie&yn+Ze])+(Jt[yn]=Ze)];return pt.i=Wt,pt.j=yn,$t})(Te)}function Qe(tt,Ee){return Ee.i=tt.i,Ee.j=tt.j,Ee.S=tt.S.slice(),Ee}function Ke(tt,Ee){var Re,pt=[],Ne=typeof tt;if(Ee&&Ne=="object")for(Re in tt)try{pt.push(Ke(tt[Re],Ee-1))}catch{}return pt.length?pt:Ne=="string"?tt:tt+"\0"}function de(tt,Ee){for(var Re,pt=tt+"",Ne=0;Ne<pt.length;)Ee[ie&Ne]=ie&(Re^=19*Ee[ie&Ne])+pt.charCodeAt(Ne++);return Fe(Ee)}function Fe(tt){return String.fromCharCode.apply(0,tt)}if(de(Nt.random(),ht),Et.exports){Et.exports=pe;try{ct=Z(234)}catch{}}else(Xe=function(){return pe}.call(ye,Z,ye,Et))===void 0||(Et.exports=Xe)})(typeof self<"u"?self:this,[],Math)},817:()=>{},833:function(Et,ye,Z){var Xe;(function(Vt,ht){function Nt(ke){var K=this;K.next=function(){var H,ie,pe=K.w,Se=K.X,Qe=K.i;return K.w=pe=pe+1640531527|0,ie=Se[Qe+34&127],H=Se[Qe=Qe+1&127],ie^=ie<<13,H^=H<<17,ie^=ie>>>15,H^=H>>>12,ie=Se[Qe]=ie^H,K.i=Qe,ie+(pe^pe>>>16)|0},function(H,ie){var pe,Se,Qe,Ke,de,Fe=[],tt=128;for(ie===(0|ie)?(Se=ie,ie=null):(ie+="\0",Se=0,tt=Math.max(tt,ie.length)),Qe=0,Ke=-32;Ke<tt;++Ke)ie&&(Se^=ie.charCodeAt((Ke+32)%ie.length)),Ke===0&&(de=Se),Se^=Se<<10,Se^=Se>>>15,Se^=Se<<4,Se^=Se>>>13,Ke>=0&&(de=de+1640531527|0,Qe=(pe=Fe[127&Ke]^=Se+de)==0?Qe+1:0);for(Qe>=128&&(Fe[127&(ie&&ie.length||0)]=-1),Qe=127,Ke=512;Ke>0;--Ke)Se=Fe[Qe+34&127],pe=Fe[Qe=Qe+1&127],Se^=Se<<13,pe^=pe<<17,Se^=Se>>>15,pe^=pe>>>12,Fe[Qe]=Se^pe;H.w=de,H.X=Fe,H.i=Qe}(K,ke)}function ct(ke,K){return K.i=ke.i,K.w=ke.w,K.X=ke.X.slice(),K}function Te(ke,K){ke==null&&(ke=+new Date);var H=new Nt(ke),ie=K&&K.state,pe=function(){return(H.next()>>>0)/4294967296};return pe.double=function(){do var Se=((H.next()>>>11)+(H.next()>>>0)/4294967296)/2097152;while(Se===0);return Se},pe.int32=H.next,pe.quick=pe,ie&&(ie.X&&ct(ie,H),pe.state=function(){return ct(H,{})}),pe}ht&&ht.exports?ht.exports=Te:Z.amdD&&Z.amdO?(Xe=function(){return Te}.call(ye,Z,ye,ht))===void 0||(ht.exports=Xe):this.xor4096=Te})(0,Et=Z.nmd(Et),Z.amdD)},848:(Et,ye)=>
8{Object.defineProperty(ye,"__esModule",{value:!0});var Z=typeof self<"u"?self:{};function Xe(u,f){e:{for(var x=["CLOSURE_FLAGS"],I=Z,C=0;C<x.length;C++)if((I=I[x[C]])==null){x=null;break e}x=I}return(u=x&&x[u])!=null?u:f}function Vt(){throw Error("Invalid UTF8")}function ht(u,f){return f=String.fromCharCode.apply(null,f),u==null?f:u+f}let Nt,ct;const Te=typeof TextDecoder<"u";let ke;const K=typeof TextEncoder<"u";function H(u){if(K)u=(ke||(ke=new TextEncoder)).encode(u);else{let x=0;const I=new Uint8Array(3*u.length);for(let C=0;C<u.length;C++){var f=u.charCodeAt(C);if(f<128)I[x++]=f;else{if(f<2048)I[x++]=f>>6|192;else{if(f>=55296&&f<=57343){if(f<=56319&&C<u.length){const D=u.charCodeAt(++C);if(D>=56320&&D<=57343){f=1024*(f-55296)+D-56320+65536,I[x++]=f>>18|240,I[x++]=f>>12&63|128,I[x++]=f>>6&63|128,I[x++]=63&f|128;continue}C--}f=65533}I[x++]=f>>12|224,I[x++]=f>>6&63|128}I[x++]=63&f|128}}u=x===I.length?I:I.subarray(0,x)}return u}var ie,pe=Xe(610401301,!1),Se=Xe(653718497,Xe(1,!0));const Qe=Z.navigator;function Ke(u){return!!pe&&!!ie&&ie.brands.some(({brand:f})=>f&&f.indexOf(u)!=-1)}function de(u){var f;return(f=Z.navigator)&&(f=f.userAgent)||(f=""),f.indexOf(u)!=-1}function Fe(){return!!pe&&!!ie&&ie.brands.length>0}function tt(){return Fe()?Ke("Chromium"):(de("Chrome")||de("CriOS"))&&!(!Fe()&&de("Edge"))||de("Silk")}function Ee(u){return Ee[" "](u),u}ie=Qe&&Qe.userAgentData||null,Ee[" "]=function(){};var Re=!Fe()&&(de("Trident")||de("MSIE"));!de("Android")||tt(),tt(),de("Safari")&&(tt()||!Fe()&&de("Coast")||!Fe()&&de("Opera")||!Fe()&&de("Edge")||(Fe()?Ke("Microsoft Edge"):de("Edg/"))||Fe()&&Ke("Opera"));var pt={},Ne=null;function Pe(){if(!Ne){Ne={};for(var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),f=["+/=","+/","-_=","-_.","-_"],x=0;x<5;x++){var I=u.concat(f[x].split(""));pt[x]=I;for(var C=0;C<I.length;C++){var D=I[C];Ne[D]===void 0&&(Ne[D]=C)}}}}var G=typeof Uint8Array<"u",Be=!Re&&typeof btoa=="function";function Ze(u){if(!Be){var f;f===void 0&&(f=0),Pe(),f=pt[f];var x=Array(Math.floor(u.length/3)),I=f[64]||"";let re=0,ut=0;for(;re<u.length-2;re+=3){var C=u[re],D=u[re+1],W=u[re+2],fe=f[C>>2];C=f[(3&C)<<4|D>>4],D=f[(15&D)<<2|W>>6],W=f[63&W],x[ut++]=fe+C+D+W}switch(fe=0,W=I,u.length-re){case 2:W=f[(15&(fe=u[re+1]))<<2]||I;case 1:u=u[re],x[ut]=f[u>>2]+f[(3&u)<<4|fe>>4]+W+I}return x.join("")}for(f="",x=0,I=u.length-10240;x<I;)f+=String.fromCharCode.apply(null,u.subarray(x,x+=10240));return f+=String.fromCharCode.apply(null,x?u.subarray(x):u),btoa(f)}const $t=/[-_.]/g,Wt={"-":"+",_:"/",".":"="};function yn(u){return Wt[u]||""}function Jt(u){if(!Be)return function(x){var I=x.length,C=3*I/4;C%3?C=Math.floor(C):"=.".indexOf(x[I-1])!=-1&&(C="=.".indexOf(x[I-2])!=-1?C-2:C-1);var D=new Uint8Array(C),W=0;return function(fe,re){function ut(tr){for(;qt<fe.length;){var Qi=fe.charAt(qt++),Ji=Ne[Qi];if(Ji!=null)return Ji;if(!/^[\s\xa0]*$/.test(Qi))throw Error("Unknown base64 encoding at char: "+Qi)}return tr}Pe();for(var qt=0;;){var un=ut(-1),rn=ut(0),pr=ut(64),br=ut(64);if(br===64&&un===-1)break;re(un<<2|rn>>4),pr!=64&&(re(rn<<4&240|pr>>2),br!=64&&re(pr<<6&192|br))}}(x,function(fe){D[W++]=fe}),W!==C?D.subarray(0,W):D}(u);$t.test(u)&&(u=u.replace($t,yn)),u=atob(u);const f=new Uint8Array(u.length);for(let x=0;x<u.length;x++)f[x]=u.charCodeAt(x);return f}function fn(u){return G&&u!=null&&u instanceof Uint8Array}var cn={};let Yn;function Dn(u){if(u!==cn)throw Error("illegal external caller")}function zn(){return Yn||(Yn=new Ye(null,cn))}function De(u){Dn(cn);var f=u.g;return(f=f==null||fn(f)?f:typeof f=="string"?Jt(f):null)==null?f:u.g=f}var Ye=class{constructor(u,f){if(Dn(f),this.g=u,u!=null&&u.length===0)throw Error("ByteString should be constructed with non-empty values")}h(){return new Uint8Array(De(this)||0)}};function rt(u,f){u.__closure__error__context__984382||(u.__closure__error__context__984382={}),u.__closure__error__context__984382.severity=f}let qe;function He(){const u=Error();rt(u,"incident"),function(f){Z.setTimeout(()=>{throw f},0)}(u)}function At(u){return rt(u=Error(u),"warning"),u}function Ut(){return typeof BigInt=="function"}function at(u){return Array.prototype.slice.call(u)}var Kt=typeof Symbol=="function"&&typeof Symbol()=="symbol";function M(u){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?Symbol():u}var S=M(),b=M("0di"),k=M("2ex"),E=M("1oa"),F=Kt?(u,f)=>{u[S]|=f}:(u,f)=>{u.G!==void 0?u.G|=f:Object.defineProperties(u,{G:{value:f,configurable:!0,writable:!0,enumerable:!1}})},B=Kt?(u,f)=>{u[S]&=~f}:(u,f)=>{u.G!==void 0&&(u.G&=~f)},Q=Kt?u=>0|u[S]:u=>0|u.G,te=Kt?u=>u[S]:u=>u.G,Ce=Kt?(u,f)=>{u[S]=f}:(u,f)=>{u.G!==void 0?u.G=f:Object.defineProperties(u,{G:{value:f,configurable:!0,writable:!0,enumerable:!1}})};function Ae(u){return F(u,34),u}function mt(u,f){Ce(f,-30975&u)}function et(u,f){Ce(f,-30941&u|34)}var it,A={},ge={};function Ve(u){return!(!u||typeof u!="object"||u.Ja!==ge)}function j(u){return u!==null&&typeof u=="object"&&!Array.isArray(u)&&u.constructor===Object}function oe(u,f,x){if(u!=null){if(typeof u=="string")u=u?new Ye(u,cn):zn();else if(u.constructor!==Ye)if(fn(u))u=u.length?new Ye(x?u:new Uint8Array(u),cn):zn();else{if(!f)throw Error();u=void 0}}return u}function Y(u){return!(!Array.isArray(u)||u.length||!(1&Q(u)))}const le=[];function ue(u){if(2&u)throw Error()}Ce(le,55),it=Object.freeze(le);class vt{constructor(f,x,I){this.l=0,this.g=f,this.h=x,this.m=I}next(){if(this.l<this.g.length){const f=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,f):f}}return{done:!0,value:void 0}}[Symbol.iterator](){return new vt(this.g,this.h,this.m)}}let Me;function en(u,f){(f=Me?f[Me]:void 0)&&(u[Me]=at(f))}var jt=Object.freeze({}),q=Object.freeze({}),Le=Object.freeze({});function Oe(u){return u.Qa=!0,u}var je=Oe(u=>typeof u=="number"),_t=Oe(u=>typeof u=="string"),Zt=Oe(u=>typeof u=="boolean"),hn=typeof Z.BigInt=="function"&&typeof Z.BigInt(0)=="bigint",an=Oe(u=>hn?u>=fr&&u<=Qn:u[0]==="-"?Hr(u,ve):Hr(u,Zn));const ve=Number.MIN_SAFE_INTEGER.toString(),fr=hn?BigInt(Number.MIN_SAFE_INTEGER):void 0,Zn=Number.MAX_SAFE_INTEGER.toString(),Qn=hn?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Hr(u,f){if(u.length>f.length)return!1;if(u.length<f.length||u===f)return!0;for(let x=0;x<u.length;x++){const I=u[x],C=f[x];if(I>C)return!1;if(I<C)return!0}}const ft=typeof Uint8Array.prototype.slice=="function";let St,wt=0,bt=0;function Ge(u){const f=u>>>0;wt=f,bt=(u-f)/4294967296>>>0}function Zs(u){if(u<0){Ge(-u);const[f,x]=Qs(wt,bt);wt=f>>>0,bt=x>>>0}else Ge(u)}function Ss(u){const f=St||(St=new DataView(new ArrayBuffer(8)));
8f.setFloat32(0,+u,!0),bt=0,wt=f.getUint32(0,!0)}function Ph(u,f){return 4294967296*f+(u>>>0)}function Ku(u,f){const x=2147483648&f;return x&&(f=~f>>>0,(u=1+~u>>>0)==0&&(f=f+1>>>0)),u=Ph(u,f),x?-u:u}function Er(u,f){if(u>>>=0,(f>>>=0)<=2097151)var x=""+(4294967296*f+u);else Ut()?x=""+(BigInt(f)<<BigInt(32)|BigInt(u)):(u=(16777215&u)+6777216*(x=16777215&(u>>>24|f<<8))+6710656*(f=f>>16&65535),x+=8147497*f,f*=2,u>=1e7&&(x+=u/1e7>>>0,u%=1e7),x>=1e7&&(f+=x/1e7>>>0,x%=1e7),x=f+Bh(x)+Bh(u));return x}function Bh(u){return u=String(u),"0000000".slice(u.length)+u}function ts(u){if(u.length<16)Zs(Number(u));else if(Ut())u=BigInt(u),wt=Number(u&BigInt(4294967295))>>>0,bt=Number(u>>BigInt(32)&BigInt(4294967295));else{const f=+(u[0]==="-");bt=wt=0;const x=u.length;for(let I=f,C=(x-f)%6+f;C<=x;I=C,C+=6){const D=Number(u.slice(I,C));bt*=1e6,wt=1e6*wt+D,wt>=4294967296&&(bt+=Math.trunc(wt/4294967296),bt>>>=0,wt>>>=0)}if(f){const[I,C]=Qs(wt,bt);wt=I,bt=C}}}function Qs(u,f){return f=~f,u?u=1+~u:f+=1,[u,f]}function Fs(u){return u==null||typeof u=="number"?u:u==="NaN"||u==="Infinity"||u==="-Infinity"?Number(u):void 0}function Ya(u){return u==null||typeof u=="boolean"?u:typeof u=="number"?!!u:void 0}const Qf=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function mc(u){const f=typeof u;switch(f){case"bigint":return!0;case"number":return Number.isFinite(u)}return f==="string"&&Qf.test(u)}function qu(u){if(u==null)return u;if(typeof u=="string"){if(!u)return;u=+u}return typeof u=="number"&&Number.isFinite(u)?0|u:void 0}function xe(u){if(u==null)return u;if(typeof u=="string"){if(!u)return;u=+u}return typeof u=="number"&&Number.isFinite(u)?u>>>0:void 0}function Vh(u){return u[0]!=="-"&&(u.length<20||u.length===20&&Number(u.substring(0,6))<184467)}function gc(u){return u=Math.trunc(u),Number.isSafeInteger(u)||(Zs(u),u=Ku(wt,bt)),u}function Uh(u){var f=Math.trunc(Number(u));if(Number.isSafeInteger(f))return String(f);if((f=u.indexOf("."))!==-1&&(u=u.substring(0,f)),!(u[0]==="-"?u.length<20||u.length===20&&Number(u.substring(0,7))>-922337:u.length<19||u.length===19&&Number(u.substring(0,6))<922337))if(ts(u),u=wt,2147483648&(f=bt))if(Ut())u=""+(BigInt(0|f)<<BigInt(32)|BigInt(u>>>0));else{const[x,I]=Qs(u,f);u="-"+Er(x,I)}else u=Er(u,f);return u}function Xu(u){return u==null?u:typeof u=="bigint"?(an(u)?u=Number(u):(u=BigInt.asIntN(64,u),u=an(u)?Number(u):String(u)),u):mc(u)?typeof u=="number"?gc(u):Uh(u):void 0}function Yu(u){if(typeof u!="string")throw Error();return u}function Da(u){if(u!=null&&typeof u!="string")throw Error();return u}function Js(u){return u==null||typeof u=="string"?u:void 0}function bi(u,f,x,I){if(u!=null&&typeof u=="object"&&u.X===A)return u;if(!Array.isArray(u))return x?2&I?(u=f[b])?f=u:(Ae((u=new f).u),f=f[b]=u):f=new f:f=void 0,f;let C=x=Q(u);return C===0&&(C|=32&I),C|=2&I,C!==x&&Ce(u,C),new f(u)}function yc(u,f,x){if(f)e:{if(!mc(f=u))throw At("int64");switch(typeof f){case"string":f=Uh(f);break e;case"bigint":if(u=f=BigInt.asIntN(64,f),_t(u)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(u))throw Error(String(u))}else if(je(u)&&!Number.isSafeInteger(u))throw Error(String(u));f=hn?BigInt(f):Zt(f)?f?"1":"0":_t(f)?f.trim()||"0":String(f);break e;default:f=gc(f)}}else f=Xu(u);return typeof(x=(u=f)==null?x?0:void 0:u)=="string"&&(f=+x,Number.isSafeInteger(f))?f:x}function bc(u){if(wi===void 0&&(wi=typeof Proxy=="function"?Qu(Proxy):null),!wi||!wc())return u;let f=xi?.get(u);return f||(Math.random()>.01?u:(function(x){if(go===void 0){const I=new wi([],{});go=Array.prototype.concat.call([],I).length===1}go&&typeof Symbol=="function"&&Symbol.isConcatSpreadable&&(x[Symbol.isConcatSpreadable]=!0)}(u),f=new wi(u,{set:(x,I,C)=>(He(),x[I]=C,!0)}),function(x,I){(xi||(xi=new pa)).set(x,I),(Zu||(Zu=new pa)).set(I,x)}(u,f),f))}let xi,Zu,wi,pa,go,Za,vi,Jo,xc;function wc(){return pa===void 0&&(pa=typeof WeakMap=="function"?Qu(WeakMap):null),pa}function Qu(u){try{return u.toString().indexOf("[native code]")!==-1?u:null}catch{return null}}function Ju(u,f,x){if(wc()){if(Za?.get(f)?.get(u)){if(x)return}else if(Math.random()>.01)return;var I=u.length;x={length:I};for(var C=0;C<Math.min(I,10);C++){if(I<=10)var D=C;else{D=I/10;const W=Math.floor(C*D);D=W+Math.floor(Math.random()*(Math.floor((C+1)*D)-W))}x[D]=u[D]}el(u,x)?((C=(I=Za||(Za=new pa)).get(f))||(C=new pa,I.set(f,C)),C.set(u,x)):(He(),ki(u,f))}}function yo(u,f){const x=Za?.get(f)?.get(u);x&&!el(u,x)&&(He(),ki(u,f))}function el(u,f){if(u.length!==f.length)return!1;for(const C in f){var x,I=Number(C);if((x=Number.isInteger(I))&&(x=u[I],I=f[I],x=!(Number.isNaN(x)?Number.isNaN(I):x===I)),x)return!1}return!0}function eu(u){if(u&&Za?.has(u)){var f=u.u;if(f)for(let x=0;x<f.length;x++){const I=f[x];if(x===f.length-1&&j(I))for(const C in I){const D=I[C];Array.isArray(D)&&yo(D,u)}else Array.isArray(I)&&yo(I,u)}}}function ki(u,f){Za?.get(f)?.delete(u)}function Ni(u,f,x){return u=vc(u,f[0],f[1],x?1:2),f!==Jo&&x&&F(u,16384),u}function vc(u,f,x,I){if(I=I??0,u==null&&(u=vi),vi=void 0,u==null){var C=96;x?(u=[x],C|=512):u=[],f&&(C=-33521665&C|(1023&f)<<15)}else{if(!Array.isArray(u))throw Error("narr");if(2048&(C=Q(u)))throw Error("farr");if(64&C)return u;if(I===1||I===2||(C|=64),x&&(C|=512,x!==u[0]))throw Error("mid");e:{if(I=(x=u).length){const D=I-1;if(j(x[D])){if((f=D-(+!!(512&(C|=256))-1))>=1024)throw Error("pvtlmt");C=-33521665&C|(1023&f)<<15;break e}}if(f){if((f=Math.max(f,I-(+!!(512&C)-1)))>1024)throw Error("spvt");C=-33521665&C|(1023&f)<<15}}}return Ce(u,C),u}const tl={};
8let nl=function(){try{return Ee(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class bo{constructor(){this.g=new Map}get(f){return this.g.get(f)}set(f,x){return this.g.set(f,x),this.size=this.g.size,this}delete(f){return f=this.g.delete(f),this.size=this.g.size,f}clear(){this.g.clear(),this.size=this.g.size}has(f){return this.g.has(f)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(f,x){return this.g.forEach(f,x)}[Symbol.iterator](){return this.entries()}}const Wh=nl?(Object.setPrototypeOf(bo.prototype,Map.prototype),Object.defineProperties(bo.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),bo):class extends Map{constructor(){super()}};function rl(u){return u}function tu(u){if(2&u.M)throw Error("Cannot mutate an immutable Map")}var ds=class extends Wh{constructor(u,f,x=rl,I=rl){super();let C=Q(u);C|=64,Ce(u,C),this.M=C,this.T=f,this.S=x,this.Z=this.T?Gh:I;for(let D=0;D<u.length;D++){const W=u[D],fe=x(W[0],!1,!0);let re=W[1];f?re===void 0&&(re=null):re=I(W[1],!1,!0,void 0,void 0,C),super.set(fe,re)}}pa(u=sl){if(this.size!==0)return this.Y(u)}Y(u=sl){const f=[],x=super.entries();for(var I;!(I=x.next()).done;)(I=I.value)[0]=u(I[0]),I[1]=u(I[1]),f.push(I);return f}clear(){tu(this),super.clear()}delete(u){return tu(this),super.delete(this.S(u,!0,!1))}entries(){var u=this.oa();return new vt(u,kc,this)}keys(){return this.Ia()}values(){var u=this.oa();return new vt(u,ds.prototype.get,this)}forEach(u,f){super.forEach((x,I)=>{u.call(f,this.get(I),I,this)})}set(u,f){return tu(this),(u=this.S(u,!0,!1))==null?this:f==null?(super.delete(u),this):super.set(u,this.Z(f,!0,!0,this.T,!1,this.M))}Oa(u){const f=this.S(u[0],!1,!0);u=u[1],u=this.T?u===void 0?null:u:this.Z(u,!1,!0,void 0,!1,this.M),super.set(f,u)}has(u){return super.has(this.S(u,!1,!1))}get(u){u=this.S(u,!1,!1);const f=super.get(u);if(f!==void 0){var x=this.T;return x?((x=this.Z(f,!1,!0,x,this.ta,this.M))!==f&&super.set(u,x),x):f}}oa(){return Array.from(super.keys())}Ia(){return super.keys()}[Symbol.iterator](){return this.entries()}};function Gh(u,f,x,I,C,D){return u=bi(u,I,x,D),C&&(u=wo(u)),u}function sl(u){return u}function kc(u){return[u,this.get(u)]}let Hh;function Nc(){return Hh||(Hh=new ds(Ae([]),void 0,void 0,void 0,tl))}function xo(u,f,x,I,C){if(u!=null){if(Array.isArray(u))u=Y(u)?void 0:C&&2&Q(u)?u:Ii(u,f,x,I!==void 0,C);else if(j(u)){const D={};for(let W in u)D[W]=xo(u[W],f,x,I,C);u=D}else u=f(u,I);return u}}function Ii(u,f,x,I,C){const D=I||x?Q(u):0;I=I?!!(32&D):void 0;const W=at(u);for(let fe=0;fe<W.length;fe++)W[fe]=xo(W[fe],f,x,I,C);return x&&(en(W,u),x(D,W)),W}function jh(u){return xo(u,nu,void 0,void 0,!1)}function nu(u){return u.X===A?u.toJSON():u instanceof ds?u.pa(jh):function(f){switch(typeof f){case"number":return isFinite(f)?f:String(f);case"bigint":return an(f)?Number(f):String(f);case"boolean":return f?1:0;case"object":if(f)if(Array.isArray(f)){if(Y(f))return}else{if(fn(f))return Ze(f);if(f instanceof Ye){const x=f.g;return x==null?"":typeof x=="string"?x:f.g=Ze(x)}if(f instanceof ds)return f.pa()}}return f}(u)}function al(u,f,x=et){if(u!=null){if(G&&u instanceof Uint8Array)return f?u:new Uint8Array(u);if(Array.isArray(u)){var I=Q(u);return 2&I?u:(f&&(f=I===0||!!(32&I)&&!(64&I||!(16&I))),f?(Ce(u,-12293&I|34),u):Ii(u,al,4&I?et:x,!0,!0))}return u.X===A?(x=u.u,u=2&(I=te(x))?u:il(u,x,I,!0)):u instanceof ds&&!(2&u.M)&&(x=Ae(u.Y(al)),u=new ds(x,u.T,u.S,u.Z)),u}}function il(u,f,x,I){return eu(u),u=u.constructor,vi=f=Ic(f,x,I),f=new u(f),vi=void 0,f}function Ic(u,f,x){const I=x||2&f?et:mt,C=!!(32&f);return u=function(D,W,fe){const re=at(D);var ut=re.length;const qt=256&W?re[ut-1]:void 0;for(ut+=qt?-1:0,W=512&W?1:0;W<ut;W++)re[W]=fe(re[W]);if(qt){W=re[W]={};for(const un in qt)W[un]=fe(qt[un])}return en(re,D),re}(u,f,D=>al(D,C,I)),F(u,32|(x?2:0)),u}function wo(u){const f=u.u,x=te(f);return 2&x?il(u,f,x,!1):u}function Sc(u,f,x,I){return!(4&f&&x==null)}function Fa(u,f){return Ms(u=u.u,te(u),f)}function Tc(u,f,x,I){if(!((f=I+(+!!(512&f)-1))<0||f>=u.length||f>=x))return u[f]}function Ms(u,f,x,I){if(x===-1)return null;const C=f>>15&1023||536870912;if(!(x>=C)){var D=u.length;return I&&256&f&&(I=u[D-1][x])!=null?(Tc(u,f,C,x)&&k!=null&&((f=(u=qe??(qe={}))[k]||0)>
8=4||(u[k]=f+1,He())),I):Tc(u,f,C,x)}return 256&f?u[u.length-1][x]:void 0}function On(u,f,x){const I=u.u;let C=te(I);return ue(C),jn(I,C,f,x),u}function jn(u,f,x,I){const C=f>>15&1023||536870912;if(x>=C){let D,W=f;if(256&f)D=u[u.length-1];else{if(I==null)return W;D=u[C+(+!!(512&f)-1)]={},W|=256}return D[x]=I,x<C&&(u[x+(+!!(512&f)-1)]=void 0),W!==f&&Ce(u,W),W}return u[x+(+!!(512&f)-1)]=I,256&f&&x in(u=u[u.length-1])&&delete u[x],f}function Si(u,f,x,I,C){var D=2&f;C=Ms(u,f,x,C),Array.isArray(C)||(C=it);const W=!(2&I);I=!(1&I);const fe=!!(32&f);let re=Q(C);return re!==0||!fe||D||W?1&re||(re|=1,Ce(C,re)):(re|=33,Ce(C,re)),D?(u=!1,2&re||(Ae(C),u=!!(4&re)),(I||u)&&Object.freeze(C)):(D=!!(2&re)||!!(2048&re),I&&D?(C=at(C),D=1,fe&&!W&&(D|=32),Ce(C,D),jn(u,f,x,C)):W&&32&re&&!D&&B(C,32)),C}function Ti(u,f){u=u.u;let x=te(u);const I=Ms(u,x,f),C=Fs(I);return C!=null&&C!==I&&jn(u,x,f,C),C}function Ec(u){u=u.u;let f=te(u);const x=Ms(u,f,1),I=oe(x,!0,!!(34&f));return I!=null&&I!==x&&jn(u,f,1,I),I}function fa(){return jt===void 0?2:5}function Qa(u,f,x,I,C,D){const W=u.u;let fe=te(W);I=2&fe?1:I,D=!!D,C=ru(W,fe,f,C);var re=Q(C),ut=C;if(yo(ut,u),I!==2&&I!==1||ki(ut,u),Sc(u,re,void 0)){4&re&&(C=at(C),re=ei(re,fe),fe=jn(W,fe,f,C));let un=ut=0;for(;ut<C.length;ut++){const rn=x(C[ut]);rn!=null&&(C[un++]=rn)}un<ut&&(C.length=un),re=-4097&(re=ol(re,fe))|20,Ce(C,re&=-8193),2&re&&Object.freeze(C)}let qt;return I===1||I===4&&32&re?Os(re)||(u=re,(re|=2)!==u&&Ce(C,re),Object.freeze(C)):(x=I===5&&(!!(32&re)||Os(re)||!!xi?.get(C)),(I===2||x)&&Os(re)&&(C=at(C),re=Ei(re=ei(re,fe),fe,D),Ce(C,re),fe=jn(W,fe,f,C)),Os(re)||(f=re,(re=Ei(re,fe,D))!==f&&Ce(C,re)),x?(qt=bc(C),Ju(C,u,!0)):I!==2||D||xi?.delete(C)),qt||C}function ru(u,f,x,I){return u=Ms(u,f,x,I),Array.isArray(u)?u:it}function ol(u,f){return u===0&&(u=ei(u,f)),1|u}function Os(u){return!!(2&u)&&!!(4&u)||!!(2048&u)}function ul(u){u=at(u);for(let f=0;f<u.length;f++){const x=u[f]=at(u[f]);Array.isArray(x[1])&&(x[1]=Ae(x[1]))}return u}function vo(u,f,x,I){u=u.u;let C=te(u);ue(C),jn(u,C,f,(I==="0"?Number(x)===0:x===I)?void 0:x)}function ll(u,f){var x=si;return ko(cl(u=u.u),u,te(u),x)===f?f:-1}function cl(u){if(Kt)return u[E]??(u[E]=new Map);if(E in u)return u[E];const f=new Map;return Object.defineProperty(u,E,{value:f}),f}function Cc(u,f,x,I){const C=cl(u),D=ko(C,u,f,x);return D!==I&&(D&&(f=jn(u,f,D)),C.set(x,I)),f}function ko(u,f,x,I){let C=u.get(I);if(C!=null)return C;C=0;for(let D=0;D<I.length;D++){const W=I[D];Ms(f,x,W)!=null&&(C!==0&&(x=jn(f,x,C)),C=W)}return u.set(I,C),C}function No(u,f,x,I){let C,D=te(u);if((I=Ms(u,D,x,I))!=null&&I.X===A)return(f=wo(I))!==I&&jn(u,D,x,f),f.u;if(Array.isArray(I)){const W=Q(I);C=2&W?Ni(Ic(I,W,!1),f,!0):64&W?I:Ni(C,f,!0)}else C=Ni(void 0,f,!0);return C!==I&&jn(u,D,x,C),C}function hl(u,f,x,I){u=u.u;let C=te(u);return(f=bi(I=Ms(u,C,x,I),f,!1,C))!==I&&f!=null&&jn(u,C,x,f),f}function xn(u,f,x,I=!1){if((f=hl(u,f,x,I))==null)return f;if(u=u.u,!(2&(I=te(u)))){const C=wo(f);C!==f&&jn(u,I,x,f=C)}return f}function $c(u,f,x,I,C,D,W){const fe=u.u;var re=!!(2&f);C=re?1:C,D=!!D,W&&(W=!re),re=ru(fe,f,I);var ut=Q(re),qt=re;if(yo(qt,u),C!==2&&C!==1||ki(qt,u),!(qt=!!(4&ut))){var un=re,rn=f;const br=!!(2&(ut=ol(ut,f)));br&&(rn|=2);let tr=!br,Qi=!0,Ji=0,ui=0;for(;Ji<un.length;Ji++){const Ru=bi(un[Ji],x,!1,rn);if(Ru instanceof x){if(!br){const Cd=!!(2&Q(Ru.u));tr&&(tr=!Cd),Qi&&(Qi=Cd)}un[ui++]=Ru}}ui<Ji&&(un.length=ui),ut|=4,ut=Qi?16|ut:-17&ut,Ce(un,ut=tr?8|ut:-9&ut),br&&Object.freeze(un)}if(W&&!(8&ut||!re.length&&(C===1||C===4&&32&ut))){for(Os(ut)?(re=at(re),ut=ei(ut,f),f=jn(fe,f,I,re)):ki(re,u),x=re,W=ut,un=0;un<x.length;un++)(ut=x[un])!==(rn=wo(ut))&&(x[un]=rn);W|=8,W=x.length?-17&W:16|W,Ce(x,W),ut=W}let pr;return C===1||C===4&&32&ut?Os(ut)||(u=ut,(ut|=!re.length||16&ut&&(!qt||32&ut)?2:2048)!==u&&Ce(re,ut),Object.freeze(re)):(qt=C===5&&(!!(32&ut)||Os(ut)||!!xi?.get(re)),(C===2||qt)&&Os(ut)&&(re=at(re),ut=Ei(ut=ei(ut,f),f,D),Ce(re,ut),f=jn(fe,f,I,re)),Os(ut)||(I=ut,(ut=Ei(ut,f,D))!==I&&Ce(re,ut)),qt?(pr=bc(re),Ju(re,u,!0)):C!==2||D||xi?.delete(re)),pr||re}function ea(u,f,x){const I=te(u.u);return $c(u,I,f,x,fa(),!1,!(2&I))}function Ht(u,f,x,I){return I==null&&(I=void 0),On(u,x,I)}function Ja(u,f,x,I){I==null&&(I=void 0);e:{u=u.u;let C=te(u);if(ue(C),I==null){const D=cl(u);
8if(ko(D,u,C,x)!==f)break e;D.set(x,0)}else C=Cc(u,C,x,f);jn(u,C,f,I)}}function ei(u,f){return-2049&(2&f?2|u:-3&u)|32}function Ei(u,f,x){return 32&f&&x||(u&=-33),u}function Ci(u,f,x,I){const C=te(u.u);ue(C),u=$c(u,C,x,f,2,!0),I=I??new x,u.push(I),2&Q(I.u)?B(u,8):B(u,16)}function ps(u,f){return u??f}function ns(u,f){return qu(Fa(u,f))}function rr(u,f){return ps(Ti(u,f),0)}function Ls(u,f){return ps(Js(Fa(u,f)),"")}function $i(u,f,x){if(x!=null&&typeof x!="boolean")throw u=typeof x,Error(`Expected boolean but got ${u!="object"?u:x?Array.isArray(x)?"array":u:"null"}: ${x}`);On(u,f,x)}function ta(u,f,x){if(x!=null){if(typeof x!="number"||!Number.isFinite(x))throw At("int32");x|=0}On(u,f,x)}function Ft(u,f,x){if(x!=null&&typeof x!="number")throw Error(`Value of float/double field must be a number, found ${typeof x}: ${x}`);On(u,f,x)}function Ai(u,f,x){{const fe=u.u;let re=te(fe);if(ue(re),x==null)jn(fe,re,f);else{x=Zu?.get(x)||x;var I,C=Q(x),D=C,W=!!(2&C)||Object.isFrozen(x);if((I=!W)&&((I=Le===void 0)||(I=!!Se&&q!==void 0)),Sc(u,C)){C=21,W&&(x=at(x),D=0,C=Ei(C=ei(C,re),re,!0));for(let ut=0;ut<x.length;ut++)x[ut]=Yu(x[ut])}I?(x=at(x),D=0,C=Ei(C=ei(C,re),re,!0)):W||Ju(x,u),C!==D&&Ce(x,C),jn(fe,re,f,x)}}}function Io(u,f,x){ue(te(u.u)),Qa(u,f,Js,2,void 0,!0).push(Yu(x))}function dl(u,f){return Error(`Invalid wire type: ${u} (at position ${f})`)}function su(){return Error("Failed to read varint, encoding is invalid.")}function Jf(u,f){return Error(`Tried to read past the end of the data ${f} > ${u}`)}function Kh(u){if(typeof u=="string")return{buffer:Jt(u),O:!1};if(Array.isArray(u))return{buffer:new Uint8Array(u),O:!1};if(u.constructor===Uint8Array)return{buffer:u,O:!1};if(u.constructor===ArrayBuffer)return{buffer:new Uint8Array(u),O:!1};if(u.constructor===Ye)return{buffer:De(u)||new Uint8Array(0),O:!0};if(u instanceof Uint8Array)return{buffer:new Uint8Array(u.buffer,u.byteOffset,u.byteLength),O:!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 pp(u,f){let x,I=0,C=0,D=0;const W=u.h;let fe=u.g;do x=W[fe++],I|=(127&x)<<D,D+=7;while(D<32&&128&x);for(D>32&&(C|=(127&x)>>4),D=3;D<32&&128&x;D+=7)x=W[fe++],C|=(127&x)<<D;if(Oa(u,fe),x<128)return f(I>>>0,C>>>0);throw su()}function au(u){let f=0,x=u.g;const I=x+10,C=u.h;for(;x<I;){const D=C[x++];if(f|=D,!(128&D))return Oa(u,x),!!(127&f)}throw su()}function Ma(u){const f=u.h;let x=u.g,I=f[x++],C=127&I;if(128&I&&(I=f[x++],C|=(127&I)<<7,128&I&&(I=f[x++],C|=(127&I)<<14,128&I&&(I=f[x++],C|=(127&I)<<21,128&I&&(I=f[x++],C|=I<<28,128&I&&128&f[x++]&&128&f[x++]&&128&f[x++]&&128&f[x++]&&128&f[x++])))))throw su();return Oa(u,x),C}function So(u){return Ma(u)>>>0}function iu(u){var f=u.h;const x=u.g,I=f[x],C=f[x+1],D=f[x+2];return f=f[x+3],Oa(u,u.g+4),(I|C<<8|D<<16|f<<24)>>>0}function To(u){var f=iu(u);u=2*(f>>31)+1;const x=f>>>23&255;return f&=8388607,x==255?f?NaN:u*(1/0):x==0?1401298464324817e-60*u*f:u*Math.pow(2,x-150)*(f+8388608)}function Ac(u){return Ma(u)}function pl(u,f,{ca:x=!1}={}){u.ca=x,f&&(f=Kh(f),u.h=f.buffer,u.m=f.O,u.j=0,u.l=u.h.length,u.g=u.j)}function Oa(u,f){if(u.g=f,f>u.l)throw Jf(u.l,f)}function Rc(u,f){if(f<0)throw Error(`Tried to read a negative byte length: ${f}`);const x=u.g,I=x+f;if(I>u.l)throw Jf(f,u.l-x);return u.g=I,x}function _c(u,f){if(f==0)return zn();var x=Rc(u,f);return u.ca&&u.m?x=u.h.subarray(x,x+f):(u=u.h,x=x===(f=x+f)?new Uint8Array(0):ft?u.slice(x,f):new Uint8Array(u.subarray(x,f))),x.length==0?zn():new Ye(x,cn)}ds.prototype.toJSON=void 0,ds.prototype.Ja=ge;var fl=[];function ml(u){var f=u.g;if(f.g==f.l)return!1;u.l=u.g.g;var x=So(u.g);if(f=x>>>3,!((x&=7)>=0&&x<=5))throw dl(x,u.l);if(f<1)throw Error(`Invalid field number: ${f} (at position ${u.l})`);return u.m=f,u.h=x,!0}function Ri(u){switch(u.h){case 0:u.h!=0?Ri(u):au(u.g);break;case 1:Oa(u=u.g,u.g+8);break;case 2:if(u.h!=2)Ri(u);else{var f=So(u.g);Oa(u=u.g,u.g+f)}break;case 5:Oa(u=u.g,u.g+4);break;case 3:for(f=u.m;;){if(!ml(u))throw Error("Unmatched start-group tag: stream EOF");if(u.h==4){if(u.m!=f)throw Error("Unmatched end-group tag");break}Ri(u)}break;default:throw dl(u.h,u.l)}}function _i(u,f,x){const I=u.g.l,C=So(u.g),D=u.g.g+C;let W=D-I;if(W<=0&&(u.g.l=D,x(f,u,void 0,void 0,void 0),W=D-u.g.g),W)throw Error(`Message parsing ended unexpectedly. Expected to read ${C} bytes, instead read ${C-W} bytes, either the data ended unexpectedly or the message misreported its own length`);return u.g.g=D,u.g.l=I,f}function Eo(u){var f=So(u.g),x=Rc(u=u.g,f);if(u=u.h,Te){var I,C=u;(I=ct)||(I=ct=new TextDecoder("utf-8",{fatal:!0})),f=x+f,C=x===0&&f===C.length?C:C.subarray(x,f);try{var D=I.decode(C)}catch(fe){if(Nt===void 0){try{I.decode(new Uint8Array([128]))}catch{}try{I.decode(new Uint8Array([97])),Nt=!0}catch{Nt=!1}}throw!Nt&&(ct=void 0),fe}}else{f=(D=x)+f,x=[];let fe,re=null;for(;D<f;){var W=u[D++];W<128?x.push(W):W<224?D>=f?Vt():(fe=u[D++],W<194||(192&fe)!=128?(D--,Vt()):x.push((31&W)<<6|63&fe)):W<240?D>=f-1?Vt():(fe=u[D++],(192&fe)!=128||W===224&&fe<160||W===237&&fe>=160||(192&(I=u[D++]))!=128?(D--,Vt()):x.push((15&W)<<12|(63&fe)<<6|63&I)):W<=244?D>=f-2?Vt():(fe=u[D++],(192&fe)!=128||fe-144+(W<<28)>>30||(192&(I=u[D++]))!=128||(192&(C=u[D++]))!=128?(D--,Vt()):(W=(7&W)<<18|(63&fe)<<12|(63&I)<<6|63&C,W-=65536,x.push(55296+(W>>10&1023),56320+(1023&W)))):Vt(),x.length>=8192&&(re=ht(re,x),x.length=0)}D=ht(re,x)}return D}function Dc(u){const f=So(u.g);return _c(u.g,f)}function Di(u,f,x){var I=So(u.g);for(I=u.g.g+I;u.g.g<I;)x.push(f(u.g))}var Co=[];let $o;function zs(u,f,x){f.g?f.m(u,f.g,f.h,x,!0):f.m(u,f.h,x,!0)}var Mt=class{constructor(u,f){this.u=vc(u,f)}toJSON(){return Fc(this)}l(){var u=Ry;return u.g?u.l(this,u.g,u.h,!0):u.l(this,u.h,u.defaultValue,!0)}clone(){const u=this.u;return il(this,u,te(u),!1)}O(){return!!(2&Q(this.u))}};function Fc(u){eu(u),u=$o?u.u:Ii(u.u,nu,void 0,void 0,!1);{var f=!$o;let ut=u.length;if(ut){var x=u[ut-1],I=j(x);I?ut--:x=void 0;var C=u;if(I){e:{var D,W=x,fe=!1;if(W)for(let qt in W)isNaN(+qt)?(D??(D={}))[qt]=W[qt]:(I=W[qt],Array.isArray(I)&&(Y(I)||Ve(I)&&I.size===0)&&(I=null),I==null&&(fe=!0),I!=null&&((D??(D={}))[qt]=I));if(fe||(D=W),D)for(let qt in D){fe=D;break e}fe=null}W=fe==null?x!=null:fe!==x}for(;ut>0&&((D=C[ut-1])==null||Y(D)||Ve(D)&&D.size===0);ut--)var re=!0;(C!==u||W||re)&&(f?(re||W||fe)&&(C.length=ut):C=Array.prototype.slice.call(C,0,ut),fe&&C.push(fe)),re=C}else re=u}return re}function gl(u){return u?/^\d+$/.test(u)?(ts(u),new ou(wt,bt)):null:Mc||(Mc=new ou(0,0))}Mt.prototype.X=A,Mt.prototype.toString=function(){try{return $o=!0,Fc(this).toString()}finally{$o=!1}};var ou=class{constructor(u,f){this.h=u>>>0,this.g=f>>>0}};let Mc;function yl(u){return u?/^-?\d+$/.test(u)?(ts(u),new fp(wt,bt)):null:bl||(bl=new fp(0,0))}var fp=class{constructor(u,f){this.h=u>>>0,this.g=f>>>0}};let bl;function ti(u,f,x){for(;x>0||f>127;)u.g.push(127&f|128),f=(f>>>7|x<<25)>>>0,x>>>=7;u.g.push(f)}function Fi(u,f){for(;f>127;)u.g.push(127&f|128),f>>>=7;u.g.push(f)}function uu(u,f){if(f>=0)Fi(u,f);else{for(let x=0;x<9;x++)u.g.push(127&f|128),f>>=7;u.g.push(1)}}function Ao(u,f){u.g.push(f>>>0&255),u.g.push(f>>>8&255),u.g.push(f>>>16&255),u.g.push(f>>>24&255)}function Mi(u,f){f.length!==0&&(u.l.push(f),u.h+=f.length)}
8function Ts(u,f,x){Fi(u.g,8*f+x)}function xl(u,f){return Ts(u,f,2),f=u.g.end(),Mi(u,f),f.push(u.h),f}function Ro(u,f){var x=f.pop();for(x=u.h+u.g.length()-x;x>127;)f.push(127&x|128),x>>>=7,u.h++;f.push(x),u.h++}function Oi(u,f,x){Ts(u,f,2),Fi(u.g,x.length),Mi(u,u.g.end()),Mi(u,x)}function _o(u,f,x,I){x!=null&&(f=xl(u,f),I(x,u),Ro(u,f))}function Es(){const u=class{constructor(){throw Error()}};return Object.setPrototypeOf(u,u.prototype),u}var wl=Es(),vl=Es(),kl=Es(),Do=Es(),Nl=Es(),Fo=Es(),lu=Es(),Oc=Es(),Li=class{constructor(u,f,x){this.g=u,this.h=f,u=wl,this.l=!!u&&x===u||!1}};function cu(u,f){return new Li(u,f,wl)}function Il(u,f,x,I,C){_o(u,x,El(f,I),C)}const Sl=cu(function(u,f,x,I,C){return u.h===2&&(_i(u,No(f,I,x),C),!0)},Il),Lc=cu(function(u,f,x,I,C){return u.h===2&&(_i(u,No(f,I,x,!0),C),!0)},Il);var zi=Symbol(),Mo=Symbol(),hu=Symbol(),du=Symbol();let pu,fu;function La(u,f,x,I){var C=I[u];if(C)return C;(C={}).W=function(un){switch(typeof un){case"boolean":return Jo||(Jo=[0,void 0,!0]);case"number":return un>0?void 0:un===0?xc||(xc=[0,void 0]):[-un,void 0];case"string":return[0,un];case"object":return un}}(I[0]);var D=I[1];let W=1;D&&D.constructor===Object&&(C.ia=D,typeof(D=I[++W])=="function"&&(C.na=!0,pu??(pu=D),fu??(fu=I[W+1]),D=I[W+=2]));const fe={};for(;D&&Array.isArray(D)&&D.length&&typeof D[0]=="number"&&D[0]>0;){for(var re=0;re<D.length;re++)fe[D[re]]=D;D=I[++W]}for(re=1;D!==void 0;){let un;typeof D=="number"&&(re+=D,D=I[++W]);var ut=void 0;if(D instanceof Li?un=D:(un=Sl,W--),un?.l){D=I[++W],ut=I;var qt=W;typeof D=="function"&&(D=D(),ut[qt]=D),ut=D}for(qt=re+1,typeof(D=I[++W])=="number"&&D<0&&(qt-=D,D=I[++W]);re<qt;re++){const rn=fe[re];ut?x(C,re,un,ut,rn):f(C,re,un,rn)}}return I[u]=C}function Tl(u){return Array.isArray(u)?u[0]instanceof Li?u:[Lc,u]:[u,void 0]}function El(u,f){return u instanceof Mt?(eu(u),u.u):Array.isArray(u)?Ni(u,f,!1):void 0}function mu(u,f,x,I){const C=x.g;u[f]=I?(D,W,fe)=>C(D,W,fe,I):C}function Cl(u,f,x,I,C){const D=x.g;let W,fe;u[f]=(re,ut,qt)=>D(re,ut,qt,fe||(fe=La(Mo,mu,Cl,I).W),W||(W=$l(I)),C)}function $l(u){let f=u[hu];if(f!=null)return f;const x=La(Mo,mu,Cl,u);return f=x.na?(I,C)=>pu(I,C,x):(I,C)=>{const D=te(I);for(;ml(C)&&C.h!=4;){var W=C.m,fe=x[W];if(fe==null){var re=x.ia;re&&(re=re[W])&&(re=qh(re))!=null&&(fe=x[W]=re)}fe!=null&&fe(C,I,W)||(W=(fe=C).l,Ri(fe),fe.ha?fe=void 0:(re=fe.g.g-W,fe.g.g=W,fe=_c(fe.g,re)),W=I,fe&&(Me||(Me=Symbol()),(re=W[Me])?re.push(fe):W[Me]=[fe]))}return 16384&D&&Ae(I),!0},u[hu]=f}function qh(u){const f=(u=Tl(u))[0].g;if(u=u[1]){const x=$l(u),I=La(Mo,mu,Cl,u).W;return(C,D,W)=>f(C,D,W,I,x)}return f}function gu(u,f,x){u[f]=x.h}function yu(u,f,x,I){let C,D;const W=x.h;u[f]=(fe,re,ut)=>W(fe,re,ut,D||(D=La(zi,gu,yu,I).W),C||(C=bu(I)))}function bu(u){let f=u[du];if(!f){const x=La(zi,gu,yu,u);f=(I,C)=>zc(I,C,x),u[du]=f}return f}function zc(u,f,x){for(var I=Q(u),C=+!!(512&I)-1,D=u.length,W=512&I?1:0,fe=D+(256&I?-1:0);W<fe;W++){const re=u[W];if(re==null)continue;const ut=W-C,qt=Al(x,ut);qt&&qt(f,re,ut)}if(256&I){I=u[D-1];for(const re in I)C=+re,Number.isNaN(C)||(D=I[C])!=null&&(fe=Al(x,C))&&fe(f,D,C)}if(u=Me?u[Me]:void 0)for(Mi(f,f.g.end()),x=0;x<u.length;x++)Mi(f,De(u[x])||new Uint8Array(0))}function Al(u,f){var x=u[f];if(x)return x;if((x=u.ia)&&(x=x[f])){var I=(x=Tl(x))[0].h;if(x=x[1]){const C=bu(x),D=La(zi,gu,yu,x).W;x=u.na?fu(D,C):(W,fe,re)=>I(W,fe,re,D,C)}else x=I;return u[f]=x}}function Pi(u,f){if(Array.isArray(f)){var x=Q(f);if(4&x)return f;for(var I=0,C=0;I<f.length;I++){const D=u(f[I]);D!=null&&(f[C++]=D)}return C<I&&(f.length=C),Ce(f,-12289&x|5),2&x&&Object.freeze(f),f}}function rs(u,f,x){return new Li(u,f,x)}function Bi(u,f,x){return new Li(u,f,x)}function ss(u,f,x){jn(u,te(u),f,x)}var Rl=cu(function(u,f,x,I,C){return u.h===2&&(u=_i(u,Ni([void 0,void 0],I,!0),C),ue(I=te(f)),(C=Ms(f,I,x))instanceof ds?2&C.M?((C=C.Y()).push(u),jn(f,I,x,C
8)):C.Oa(u):Array.isArray(C)?(2&Q(C)&&jn(f,I,x,C=ul(C)),C.push(u)):jn(f,I,x,[u]),!0)},function(u,f,x,I,C){if(f instanceof ds)f.forEach((D,W)=>{_o(u,x,Ni([W,D],I,!1),C)});else if(Array.isArray(f))for(let D=0;D<f.length;D++){const W=f[D];Array.isArray(W)&&_o(u,x,Ni(W,I,!1),C)}});function xu(u,f,x){if(f=function(I){if(I==null)return I;const C=typeof I;if(C==="bigint")return String(BigInt.asIntN(64,I));if(mc(I)){if(C==="string")return Uh(I);if(C==="number")return gc(I)}}(f),f!=null&&(typeof f=="string"&&yl(f),f!=null))switch(Ts(u,x,0),typeof f){case"number":u=u.g,Zs(f),ti(u,wt,bt);break;case"bigint":x=BigInt.asUintN(64,f),x=new fp(Number(x&BigInt(4294967295)),Number(x>>BigInt(32))),ti(u.g,x.h,x.g);break;default:x=yl(f),ti(u.g,x.h,x.g)}}function wu(u,f,x){(f=qu(f))!=null&&f!=null&&(Ts(u,x,0),uu(u.g,f))}function vu(u,f,x){(f=Ya(f))!=null&&(Ts(u,x,0),u.g.g.push(f?1:0))}function Pc(u,f,x){(f=Js(f))!=null&&Oi(u,x,H(f))}function Bc(u,f,x,I,C){_o(u,x,El(f,I),C)}function Oo(u,f,x){(f=f==null||typeof f=="string"||fn(f)||f instanceof Ye?f:void 0)!=null&&Oi(u,x,Kh(f).buffer)}function Vc(u,f,x){return(u.h===5||u.h===2)&&(f=Si(f,te(f),x,2,!1),u.h==2?Di(u,To,f):f.push(To(u.g)),!0)}var na=rs(function(u,f,x){if(u.h!==1)return!1;var I=u.g;u=iu(I);const C=iu(I);I=2*(C>>31)+1;const D=C>>>20&2047;return u=4294967296*(1048575&C)+u,ss(f,x,D==2047?u?NaN:I*(1/0):D==0?5e-324*I*u:I*Math.pow(2,D-1075)*(u+4503599627370496)),!0},function(u,f,x){(f=Fs(f))!=null&&(Ts(u,x,1),u=u.g,(x=St||(St=new DataView(new ArrayBuffer(8)))).setFloat64(0,+f,!0),wt=x.getUint32(0,!0),bt=x.getUint32(4,!0),Ao(u,wt),Ao(u,bt))},Es()),mr=rs(function(u,f,x){return u.h===5&&(ss(f,x,To(u.g)),!0)},function(u,f,x){(f=Fs(f))!=null&&(Ts(u,x,5),u=u.g,Ss(f),Ao(u,wt))},Fo),Sy=Bi(Vc,function(u,f,x){if((f=Pi(Fs,f))!=null)for(let W=0;W<f.length;W++){var I=u,C=x,D=f[W];D!=null&&(Ts(I,C,5),I=I.g,Ss(D),Ao(I,wt))}},Fo),ku=Bi(Vc,function(u,f,x){if((f=Pi(Fs,f))!=null&&f.length){Ts(u,x,2),Fi(u.g,4*f.length);for(let I=0;I<f.length;I++)x=u.g,Ss(f[I]),Ao(x,wt)}},Fo),ra=rs(function(u,f,x){return u.h===0&&(ss(f,x,pp(u.g,Ku)),!0)},xu,Nl),_l=rs(function(u,f,x){return u.h===0&&(ss(f,x,(u=pp(u.g,Ku))===0?void 0:u),!0)},xu,Nl),Xh=rs(function(u,f,x){return u.h===0&&(ss(f,x,pp(u.g,Ph)),!0)},function(u,f,x){if((f=function(I){if(I==null)return I;var C=typeof I;if(C==="bigint")return String(BigInt.asUintN(64,I));if(mc(I)){if(C==="string")return C=Math.trunc(Number(I)),Number.isSafeInteger(C)&&C>=0?I=String(C):((C=I.indexOf("."))!==-1&&(I=I.substring(0,C)),Vh(I)||(ts(I),I=Er(wt,bt))),I;if(C==="number")return(I=Math.trunc(I))>=0&&Number.isSafeInteger(I)?I:function(D){if(D<0){Zs(D);const W=Er(wt,bt);return D=Number(W),Number.isSafeInteger(D)?D:W}return Vh(String(D))?D:(Zs(D),Ph(wt,bt))}(I)}}(f))!=null&&(typeof f=="string"&&gl(f),f!=null))switch(Ts(u,x,0),typeof f){case"number":u=u.g,Zs(f),ti(u,wt,bt);break;case"bigint":x=BigInt.asUintN(64,f),x=new ou(Number(x&BigInt(4294967295)),Number(x>>BigInt(32))),ti(u.g,x.h,x.g);break;default:x=gl(f),ti(u.g,x.h,x.g)}},Es()),Jn=rs(function(u,f,x){return u.h===0&&(ss(f,x,Ma(u.g)),!0)},wu,Do),Lo=Bi(function(u,f,x){return(u.h===0||u.h===2)&&(f=Si(f,te(f),x,2,!1),u.h==2?Di(u,Ma,f):f.push(Ma(u.g)),!0)},function(u,f,x){if((f=Pi(qu,f))!=null&&f.length){x=xl(u,x);for(let I=0;I<f.length;I++)uu(u.g,f[I]);Ro(u,x)}},Do),ni=rs(function(u,f,x){return u.h===0&&(ss(f,x,(u=Ma(u.g))===0?void 0:u),!0)},wu,Do),In=rs(function(u,f,x){return u.h===0&&(ss(f,x,au(u.g)),!0)},vu,vl),Uc=rs(function(u,f,x){return u.h===0&&(ss(f,x,(u=au(u.g))===!1?void 0:u),!0)},vu,vl),Cr=Bi(function(u,f,x){if(u.h!==2)return!1;u=Eo(u);const I=te(f);return ue(I),Si(f,I,x,2).push(u),!0},function(u,f,x){if((f=Pi(Js,f))!=null)for(let W=0;W<f.length;W++){var I=u,C=x,D=f[W];D!=null&&Oi(I,C,H(D))}},kl),ma=rs(function(u,f,x){return u.h===2&&(ss(f,x,(u=Eo(u))===""?void 0:u),!0)},Pc,kl),En=rs(function(u,f,x){return u.h===2&&(ss(f,x,Eo(u)),!0)},Pc,kl),$r=function(u,f,x=wl){return new Li(u,f,x)}(function(u,f,x,I,C){if(u.h!==2)return!1;I=Ni(void 0,I,!0);let D=te(f);ue(D);let W=Si(f,D,x,3);return D=te(f),4&Q(W)&&(W=at(W),Ce(W,-2079&Q(W)|1),jn(f,D,x,W)),W.push(I),_i(u,I,C),!0},function(u,f,x,I,C){if(Array.isArray(f))for(let D=0;D<f.length;D++)Bc(u,f[D],x,I,C)}),_n=cu(function(u,f,x,I,C,D){return u.h===2&&(Cc(f,Q(f),D,x),_i(u,f=No(f,I,x),C),!0)},Bc),Wc=rs(function(u,f,x){return u.h===2&&(ss(f,x,Dc(u)),!0)},Oo,lu),em=Bi(function(u,f,x){return(u.h===0||u.h===2)&&(f=Si(f,te(f),x,2,!1),u.h==2?Di(u,So,f):f.push(So(u.g)),!0)},function(u,f,x){if((f=Pi(xe,f))!=null)for(let W=0;W<f.length;W++){var I=u,C=x,D=f[W];D!=null&&(Ts(I,C,0),Fi(I.g,D))}},Es()),za=rs(function(u,f,x){return u.h===0&&(ss(f,x,Ma(u.g)),!0)},function(u,f,x){(f=qu(f))!=null&&(f=parseInt(f,10),Ts(u,x,0),uu(u.g,f))},Oc);class Ty{constructor(f,x){this.h=f,this.g=x,this.l=xn,this.m=Ht,this.defaultValue=void 0}}function Pa(u,f){return new Ty(u,f)}function ri(u,f){return(x,I)=>
8{if(Co.length){const D=Co.pop();D.o(I),pl(D.g,x,I),x=D}else x=new class{constructor(D,W){if(fl.length){const fe=fl.pop();pl(fe,D,W),D=fe}else D=new class{constructor(fe,re){this.h=null,this.m=!1,this.g=this.l=this.j=0,pl(this,fe,re)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ca=!1}}(D,W);this.g=D,this.l=this.g.g,this.h=this.m=-1,this.o(W)}o({ha:D=!1}={}){this.ha=D}}(x,I);try{const D=new u,W=D.u;$l(f)(W,x);var C=D}finally{x.g.clear(),x.m=-1,x.h=-1,Co.length<100&&Co.push(x)}return C}}function Gc(u){return function(){eu(this);const f=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const W=this.g;return this.g=[],W}}}};zc(this.u,f,La(zi,gu,yu,u)),Mi(f,f.g.end());const x=new Uint8Array(f.h),I=f.l,C=I.length;let D=0;for(let W=0;W<C;W++){const fe=I[W];x.set(fe,D),D+=fe.length}return f.l=[x],x}}var mp=class extends Mt{constructor(u){super(u)}},zo=[0,ma,rs(function(u,f,x){return u.h===2&&(ss(f,x,(u=Dc(u))===zn()?void 0:u),!0)},function(u,f,x){if(f!=null){if(f instanceof Mt){const I=f.Ra;return void(I&&(f=I(f),f!=null&&Oi(u,x,Kh(f).buffer)))}if(Array.isArray(f))return}Oo(u,f,x)},lu)];let Nu,gp=globalThis.trustedTypes;function Po(u){Nu===void 0&&(Nu=function(){let x=null;if(!gp)return x;try{const I=C=>C;x=gp.createPolicy("goog#html",{createHTML:I,createScript:I,createScriptURL:I})}catch{}return x}());var f=Nu;return new class{constructor(x){this.g=x}toString(){return this.g+""}}(f?f.createScriptURL(u):u)}function fs(u,...f){if(f.length===0)return Po(u[0]);let x=u[0];for(let I=0;I<f.length;I++)x+=encodeURIComponent(f[I])+u[I+1];return Po(x)}var Yh=[0,Jn,za,In,-1,Lo,za,-1],tm=class extends Mt{constructor(){super()}},Pn=[0,In,En,In,za,-1,Bi(function(u,f,x){return(u.h===0||u.h===2)&&(f=Si(f,te(f),x,2,!1),u.h==2?Di(u,Ac,f):f.push(Ma(u.g)),!0)},function(u,f,x){if((f=Pi(qu,f))!=null&&f.length){x=xl(u,x);for(let I=0;I<f.length;I++)uu(u.g,f[I]);Ro(u,x)}},Oc),En,-1,[0,In,-1],za,In,-1],yp=[0,En,-2],Rr=class extends Mt{constructor(){super()}},Vi=[0],Hc=[0,Jn,In,1,In,-3],Ps=class extends Mt{constructor(u){super(u,2)}},Bn={};Bn[336783863]=[0,En,In,-1,Jn,[0,[1,2,3,4,5,6,7],_n,Vi,_n,Pn,_n,yp,_n,Hc,_n,Yh,_n,[0,En,-2],_n,[0,En,za]],[0,En],In,[0,[1,3],[2,4],_n,[0,Lo],-1,_n,[0,Cr],-1,$r,[0,En,-1]],En];var Ui=[0,_l,-1,Uc,-3,_l,Lo,ma,ni,_l,-1,Uc,ni,Uc,-2,ma];function Fn(u,f){vo(u,2,Da(f),"")}function Kn(u,f){Io(u,3,f)}function dn(u,f){Io(u,4,f)}var gr=class extends Mt{constructor(u){super(u,500)}o(u){return Ht(this,0,7,u)}},lr=[-1,{}],Ba=[0,En,1,lr],nm=[0,En,Cr,lr];function sa(u,f){Ci(u,1,gr,f)}function sr(u,f){Io(u,10,f)}function $n(u,f){Io(u,15,f)}var jr=class extends Mt{constructor(u){super(u,500)}o(u){return Ht(this,0,1001,u)}},bp=[-500,$r,[-500,ma,-1,Cr,-3,[-2,Bn,In],$r,zo,ni,-1,Ba,nm,$r,[0,ma,Uc],ma,Ui,ni,Cr,987,Cr],4,$r,[-500,En,-1,[-1,{}],998,En],$r,[-500,En,Cr,-1,[-2,{},In],997,Cr,-1],ni,$r,[-500,En,Cr,lr,998,Cr],Cr,ni,Ba,nm,$r,[0,ma,-1,lr],Cr,-2,Ui,ma,-1,Uc,979,lr,$r,zo];jr.prototype.g=Gc(bp);var Zh=ri(jr,bp),jc=class extends Mt{constructor(u){super(u)}},kr=class extends Mt{constructor(u){super(u)}g(){return ea(this,jc,1)}},ga=[0,$r,[0,Jn,mr,En,-1]],Wi=ri(kr,ga),Sn=class extends Mt{constructor(u){super(u)}},_e=class extends Mt{constructor(u){super(u)}},Iu=class extends Mt{constructor(u){super(u)}h(){return xn(this,Sn,2)}g(){return ea(this,_e,5)}},Qh=ri(class extends Mt{constructor(u){super(u)}},[0,Cr,Lo,ku,[0,za,[0,Jn,-3],[0,mr,-3],[0,Jn,-1,[0,$r,[0,Jn,-2]]],$r,[0,mr,-1,En,mr]],En,-1,ra,$r,[0,Jn,mr],Cr,ra]),Jh=class extends Mt{constructor(u){super(u)}},Bo=ri(class extends Mt{constructor(u){super(u)}},[0,$r,[0,mr,-4]]),ed=class extends Mt{constructor(u){super(u)}},Su=ri(class extends Mt{constructor(u){super(u)}},[0,$r,[0,mr,-4]]),Ey=class extends Mt{constructor(u){super(u)}},Cs=[0,Jn,-1,ku,za],Kc=class extends Mt{constructor(){super()}};Kc.prototype.g=Gc([0,mr,-4,ra]);var rm=class extends Mt{constructor(u){super(u)}},sm=ri(class extends Mt{constructor(u){super(u)}},[0,$r,[0,1,Jn,En,ga],ra]),ar=class extends Mt{constructor(u){super(u)}},am=class extends Mt{constructor(u){super(u)}qa(){const u=Ec(this);return u??zn()}},td=class extends Mt{constructor(u){super(u)}},si=[1,2],im=ri(class extends Mt{constructor(u){super(u)}},[0,$r,[0,si,_n,[0,ku],_n,[0,Wc],Jn,En],ra]),qc=class extends Mt{constructor(u){super(u)}},xp=[0,En,Jn,mr,Cr,-1],Tu=class extends Mt{constructor(u){super(u)}},om=[0,In,-1],J=class extends Mt{constructor(u){super(u)}},nd=[1,2,3,4,5],Dl=class extends Mt{constructor(u){super(u)}g(){return Ec(this)!=null}h(){return Js(Fa(this,2))!=null}},cr=class extends Mt{constructor(u){super(u)}g(){return Ya(Fa(this,2))??!1}},rd=[0,Wc,En,[0,Jn,ra,-1],[0,Xh,ra]],yr=[0,rd,In,[0,nd,_n,Hc,_n,Pn,_n,Yh,_n,Vi,_n,yp],za],Kr=class extends Mt{constructor(u){super(u)}},ya=[0,yr,mr,-1,Jn],um=Pa(502141897,Kr);Bn[502141897]=ya;var lm=ri(class extends Mt{constructor(u){super(u)}},[0,[0,za,-1,Sy,em],Cs]),P=class extends Mt{constructor(u){super(u)}},Fl=class extends Mt{constructor(u){super(u)}},Xc=[0,yr,mr,[0,yr],In],ee=[0,yr,ya,Xc,mr,[0,[0,rd]]],Gi=Pa(508968150,Fl);Bn[508968150]=ee,Bn[508968149]=Xc;var Hi=class extends Mt{constructor(u){super(u)}},Bs=Pa(513916220,Hi);Bn[513916220]=[0,yr,ee,Jn];var ba=class extends Mt{constructor(u){super(u)}h(){return xn(this,qc,2)}g(){On(this,2)}},xa=[0,yr,xp];Bn[478825465]=xa;var Cy=class extends Mt{constructor(u){super(u)}},cm=class extends Mt{constructor(u){super(u)}},wp=class extends Mt{constructor(u){super(u)}},vp=class extends Mt{constructor(u){super(u)}},hm=class extends Mt{constructor(u){super(u)}},wa=[0,yr,[0,yr],xa,-1],sd=[0,yr,mr,Jn],kp=[0,yr,mr],be=[0,yr,sd,kp,mr],on=Pa(479097054,hm);Bn[479097054]=[0,yr,be,wa],Bn[463370452]=wa,Bn[464864288]=sd;var _r=Pa(462713202,vp);Bn[462713202]=be,Bn[474472470]=kp;var $y=class extends Mt{constructor(u){super(u)}},dm=class extends Mt{constructor(u){super(u)}},pm=class extends Mt{constructor(u){super(u)}},Np=class extends Mt{constructor(){super()}},Ip=[0,yr,mr,-1,Jn],Sp=[0,yr,mr,In];Np.prototype.g=Gc([0,yr,kp,[0,yr],ya,Xc,Ip,Sp]);var fm=class extends Mt{constructor(u){super(u)}},Tp=Pa(456383383,fm);Bn[456383383]=[0,yr,xp];var ad=class extends Mt{constructor(u){super(u)}},Ay=Pa(476348187,ad);Bn[476348187]=[0,yr,om];var ji=class extends Mt{constructor(u){super(u)}},id=class extends Mt{constructor(u){super(u)}},od=[0,za,-1],Ry=Pa(458105876,class extends Mt{constructor(u){super(u)}g(){var u=this.u;const f=te(u),x=2&f;return u=function(I,C,D){var W=id;const fe=2&C;let re=!1;if(D==null){if(fe)return Nc();D=[]}else if(D.constructor===ds){if(!(2&D.M)||fe)return D;D=D.Y()}else Array.isArray(D)?re=!!(2&Q(D)):D=[];if(fe){if(!D.length)return Nc();re||(re=!0,Ae(D))}else re&&(re=!1,D=ul(D));return re||(64&Q(D)?B(D,32):32&C&&F(D,32)),jn(I,C,2,W=new ds(D,W,yc,void 0)),W}(u,f,Ms(u,f,2)),!x&&id&&(u.ta=!0),u}});Bn[458105876]=[0,od,Rl,[!0,ra,[0,En,-1,Cr]]];var Ep=class extends Mt{constructor(u){super(u)}},Cp=Pa(458105758,Ep);Bn[458105758]=[0,yr,En,od];var $p=class extends Mt{constructor(u){super(u)}},mm=Pa(443442058,$p);Bn[443442058]=[0,yr,En,Jn,mr,Cr,-1],Bn[514774813]=Ip;var gm=class extends Mt{constructor(u){super(u)}}
8,Ap=Pa(516587230,gm);function ud(u,f){return f=f?f.clone():new qc,u.displayNamesLocale!==void 0?On(f,1,Da(u.displayNamesLocale)):u.displayNamesLocale===void 0&&On(f,1),u.maxResults!==void 0?ta(f,2,u.maxResults):"maxResults"in u&&On(f,2),u.scoreThreshold!==void 0?Ft(f,3,u.scoreThreshold):"scoreThreshold"in u&&On(f,3),u.categoryAllowlist!==void 0?Ai(f,4,u.categoryAllowlist):"categoryAllowlist"in u&&On(f,4),u.categoryDenylist!==void 0?Ai(f,5,u.categoryDenylist):"categoryDenylist"in u&&On(f,5),f}function ld(u,f=-1,x=""){return{categories:u.map(I=>({index:ps(ns(I,1),0)??-1,score:rr(I,2)??0,categoryName:Ls(I,3)??"",displayName:Ls(I,4)??""})),headIndex:f,headName:x}}function Rp(u){var f=Qa(u,3,Fs,fa()),x=Qa(u,2,qu,fa()),I=Qa(u,1,Js,fa()),C=Qa(u,9,Js,fa());const D={categories:[],keypoints:[]};for(let W=0;W<f.length;W++)D.categories.push({score:f[W],index:x[W]??-1,categoryName:I[W]??"",displayName:C[W]??""});if((f=xn(u,Iu,4)?.h())&&(D.boundingBox={originX:ns(f,1)??0,originY:ns(f,2)??0,width:ns(f,3)??0,height:ns(f,4)??0,angle:0}),xn(u,Iu,4)?.g().length)for(const W of xn(u,Iu,4).g())D.keypoints.push({x:Ti(W,1)??0,y:Ti(W,2)??0,score:Ti(W,4)??0,label:Js(Fa(W,3))??""});return D}function Yc(u){const f=[];for(const x of ea(u,ed,1))f.push({x:rr(x,1)??0,y:rr(x,2)??0,z:rr(x,3)??0,visibility:rr(x,4)??0});return f}function Eu(u){const f=[];for(const x of ea(u,Jh,1))f.push({x:rr(x,1)??0,y:rr(x,2)??0,z:rr(x,3)??0,visibility:rr(x,4)??0});return f}function cd(u){return Array.from(u,f=>f>127?f-256:f)}function Ml(u,f){if(u.length!==f.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${u.length} vs. ${f.length}).`);let x=0,I=0,C=0;for(let D=0;D<u.length;D++)x+=u[D]*f[D],I+=u[D]*u[D],C+=f[D]*f[D];if(I<=0||C<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return x/Math.sqrt(I*C)}let Cu;Bn[516587230]=[0,yr,Ip,Sp,mr],Bn[518928384]=Sp;
8const hr=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function ym(){if(Cu===void 0)try{await WebAssembly.instantiate(hr),Cu=!0}catch{Cu=!1}return Cu}async function Zc(u,f=fs``){const x=await ym()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${f}/${u}_${x}.js`,wasmBinaryPath:`${f}/${u}_${x}.wasm`}}var Vo=class{};function _p(){var u=navigator;return!(typeof OffscreenCanvas>"u"||function(f=navigator){return(f=f.userAgent).includes("Safari")&&!f.includes("Chrome")}(u)&&!((u=u.userAgent.match(/Version\/([\d]+).*Safari/))&&u.length>=1&&Number(u[1])>=17))}async function hd(u){if(typeof importScripts!="function"){const f=document.createElement("script");return f.src=u.toString(),f.crossOrigin="anonymous",new Promise((x,I)=>{f.addEventListener("load",()=>{x()},!1),f.addEventListener("error",C=>{I(C)},!1),document.body.appendChild(f)})}importScripts(u.toString())}function Uo(u){return u.videoWidth!==void 0?[u.videoWidth,u.videoHeight]:u.naturalWidth!==void 0?[u.naturalWidth,u.naturalHeight]:u.displayWidth!==void 0?[u.displayWidth,u.displayHeight]:[u.width,u.height]}function Ot(u,f,x){u.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),x(f=u.i.stringToNewUTF8(f)),u.i._free(f)}function Dp(u,f,x){if(!u.i.canvas)throw Error("No OpenGL canvas configured.");if(x?u.i._bindTextureToStream(x):u.i._bindTextureToCanvas(),!(x=u.i.canvas.getContext("webgl2")||u.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");u.i.gpuOriginForWebTexturesIsBottomLeft&&x.pixelStorei(x.UNPACK_FLIP_Y_WEBGL,!0),x.texImage2D(x.TEXTURE_2D,0,x.RGBA,x.RGBA,x.UNSIGNED_BYTE,f),u.i.gpuOriginForWebTexturesIsBottomLeft&&x.pixelStorei(x.UNPACK_FLIP_Y_WEBGL,!1);const[I,C]=Uo(f);return!u.l||I===u.i.canvas.width&&C===u.i.canvas.height||(u.i.canvas.width=I,u.i.canvas.height=C),[I,C]}function dd(u,f,x){u.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const I=new Uint32Array(f.length);for(let C=0;C<f.length;C++)I[C]=u.i.stringToNewUTF8(f[C]);f=u.i._malloc(4*I.length),u.i.HEAPU32.set(I,f>>2),x(f);for(const C of I)u.i._free(C);u.i._free(f)}function ms(u,f,x){u.i.simpleListeners=u.i.simpleListeners||{},u.i.simpleListeners[f]=x}function Ki(u,f,x){let I=[];u.i.simpleListeners=u.i.simpleListeners||{},u.i.simpleListeners[f]=(C,D,W)=>{D?(x(I,W),I=[]):I.push(C)}}function Fp(u,f){const x=xn(u.baseOptions,Dl,1)||new Dl;typeof f=="string"?(On(x,2,Da(f)),On(x,1)):f instanceof Uint8Array&&(On(x,1,oe(f,!1,!1)),On(x,2)),Ht(u.baseOptions,0,1,x)}function ai(u){try{const f=u.H.length;if(f===1)throw Error(u.H[0].message);if(f>1)throw Error("Encountered multiple errors: "+u.H.map(x=>x.message).join(", "))}finally{u.H=[]}}function Tt(u,f){u.B=Math.max(u.B,f)}function Qc(u,f){u.A=new gr,Fn(u.A,"PassThroughCalculator"),Kn(u.A,"free_memory"),dn(u.A,"free_memory_unused_out"),sr(f,"free_memory"),sa(f,u.A)}function Ol(u,f){Kn(u.A,f),dn(u.A,f+"_unused_out")}function pd(u){u.g.addBoolToStream(!0,"free_memory",u.B)}Vo.forVisionTasks=function(u){return Zc("vision",u)},Vo.forTextTasks=function(u){return Zc("text",u)},Vo.forGenAiExperimentalTasks=function(u){return Zc("genai_experimental",u)},Vo.forGenAiTasks=function(u){return Zc("genai",u)},Vo.forAudioTasks=function(u){return Zc("audio",u)},Vo.isSimdSupported=function(){return ym()};var fd=class{constructor(u){this.g=u,this.H=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(u,f=!0){if(f){const x=u.baseOptions||{};if(u.baseOptions?.modelAssetBuffer&&u.baseOptions?.modelAssetPath)throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!(xn(this.baseOptions,Dl,1)?.g()||xn(this.baseOptions,Dl,1)?.h()||u.baseOptions?.modelAssetBuffer||u.baseOptions?.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(I,C){let D=xn(I.baseOptions,J,3);if(!D){var W=D=new J,fe=new Rr;Ja(W,4,nd,fe)}"delegate"in C&&(C.delegate==="GPU"?(C=D,W=new tm,Ja(C,2,nd,W)):(C=D,W=new Rr,Ja(C,4,nd,W))),Ht(I.baseOptions,0,3,D)}(this,x),x.modelAssetPath)return fetch(x.modelAssetPath.toString()).then(I=>
8{if(I.ok)return I.arrayBuffer();throw Error(`Failed to fetch model: ${x.modelAssetPath} (${I.status})`)}).then(I=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(I),!0,!1,!1),Fp(this,"/model.dat"),this.m(),this.J()});if(x.modelAssetBuffer instanceof Uint8Array)Fp(this,x.modelAssetBuffer);else if(x.modelAssetBuffer)return async function(I){const C=[];for(var D=0;;){const{done:W,value:fe}=await I.read();if(W)break;C.push(fe),D+=fe.length}if(C.length===0)return new Uint8Array(0);if(C.length===1)return C[0];I=new Uint8Array(D),D=0;for(const W of C)I.set(W,D),D+=W.length;return I}(x.modelAssetBuffer).then(I=>{Fp(this,I),this.m(),this.J()})}return this.m(),this.J(),Promise.resolve()}J(){}ea(){let u;if(this.g.ea(f=>{u=Zh(f)}),!u)throw Error("Failed to retrieve CalculatorGraphConfig");return u}setGraph(u,f){this.g.attachErrorListener((x,I)=>{this.H.push(Error(I))}),this.g.Ma(),this.g.setGraph(u,f),this.A=void 0,ai(this)}finishProcessing(){this.g.finishProcessing(),ai(this)}close(){this.A=void 0,this.g.closeGraph()}};function $s(u,f){if(!u)throw Error(`Unable to obtain required WebGL resource: ${f}`);return u}fd.prototype.close=fd.prototype.close,function(u,f){u=u.split(".");var x,I=Z;for((u[0]in I)||I.execScript===void 0||I.execScript("var "+u[0]);u.length&&(x=u.shift());)u.length||f===void 0?I=I[x]&&I[x]!==Object.prototype[x]?I[x]:I[x]={}:I[x]=f}("TaskRunner",fd);class bm{constructor(f,x,I,C){this.g=f,this.h=x,this.m=I,this.l=C}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function Mp(u,f,x){const I=u.g;if(x=$s(I.createShader(x),"Failed to create WebGL shader"),I.shaderSource(x,f),I.compileShader(x),!I.getShaderParameter(x,I.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${I.getShaderInfoLog(x)}`);return I.attachShader(u.h,x),x}function xm(u,f){const x=u.g,I=$s(x.createVertexArray(),"Failed to create vertex array");x.bindVertexArray(I);const C=$s(x.createBuffer(),"Failed to create buffer");x.bindBuffer(x.ARRAY_BUFFER,C),x.enableVertexAttribArray(u.P),x.vertexAttribPointer(u.P,2,x.FLOAT,!1,0,0),x.bufferData(x.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),x.STATIC_DRAW);const D=$s(x.createBuffer(),"Failed to create buffer");return x.bindBuffer(x.ARRAY_BUFFER,D),x.enableVertexAttribArray(u.J),x.vertexAttribPointer(u.J,2,x.FLOAT,!1,0,0),x.bufferData(x.ARRAY_BUFFER,new Float32Array(f?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),x.STATIC_DRAW),x.bindBuffer(x.ARRAY_BUFFER,null),x.bindVertexArray(null),new bm(x,I,C,D)}function qi(u,f){if(u.g){if(f!==u.g)throw Error("Cannot change GL context once initialized")}else u.g=f}function Ll(u,f,x,I){return qi(u,f),u.h||(u.m(),u.C()),x?(u.s||(u.s=xm(u,!0)),x=u.s):(u.v||(u.v=xm(u,!1)),x=u.v),f.useProgram(u.h),x.bind(),u.l(),u=I(),x.g.bindVertexArray(null),u}function Wo(u,f,x){return qi(u,f),u=$s(f.createTexture(),"Failed to create texture"),f.bindTexture(f.TEXTURE_2D,u),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,x??f.LINEAR),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,x??f.LINEAR),f.bindTexture(f.TEXTURE_2D,null),u}function Xi(u,f,x){qi(u,f),u.A||(u.A=$s(f.createFramebuffer(),"Failed to create framebuffe.")),f.bindFramebuffer(f.FRAMEBUFFER,u.A),f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,x,0)}function qr(u){u.g?.bindFramebuffer(u.g.FRAMEBUFFER,null)}var Yi=class{H(){return`
9  precision mediump float;
10  varying vec2 vTex;
11  uniform sampler2D inputTexture;
12  void main() {
13    gl_FragColor = texture2D(inputTexture, vTex);
14  }
15 `}m(){const u=this.g;if(this.h=$s(u.createProgram(),"Failed to create WebGL program"),this.ba=Mp(this,`
16  attribute vec2 aVertex;
17  attribute vec2 aTex;
18  varying vec2 vTex;
19  void main(void) {
20    gl_Position = vec4(aVertex, 0.0, 1.0);
21    vTex = aTex;
22  }`,u.VERTEX_SHADER),this.aa=Mp(this,this.H(),u.FRAGMENT_SHADER),u.linkProgram(this.h),!u.getProgramParameter(this.h,u.LINK_STATUS))throw Error(`Error during program linking: ${u.getProgramInfoLog(this.h)}`);this.P=u.getAttribLocation(this.h,"aVertex"),this.J=u.getAttribLocation(this.h,"aTex")}C(){}l(){}close(){if(this.h){const u=this.g;u.deleteProgram(this.h),u.deleteShader(this.ba),u.deleteShader(this.aa)}this.A&&this.g.deleteFramebuffer(this.A),this.v&&this.v.close(),this.s&&this.s.close()}},wm=class extends Yi{H(){return`
23  precision mediump float;
24  uniform sampler2D backgroundTexture;
25  uniform sampler2D maskTexture;
26  uniform sampler2D colorMappingTexture;
27  varying vec2 vTex;
28  void main() {
29    vec4 backgroundColor = texture2D(backgroundTexture, vTex);
30    float category = texture2D(maskTexture, vTex).r;
31    vec4 categoryColor = texture2D(colorMappingTexture, vec2(category, 0.0));
32    gl_FragColor = mix(backgroundColor, categoryColor, categoryColor.a);
33  }
34 `}C(){const u=this.g;u.activeTexture(u.TEXTURE1),this.B=Wo(this,u,u.LINEAR),u.activeTexture(u.TEXTURE2),this.j=Wo(this,u,u.NEAREST)}m(){super.m();const u=this.g;this.L=$s(u.getUniformLocation(this.h,"backgroundTexture"),"Uniform location"),this.U=$s(u.getUniformLocation(this.h,"colorMappingTexture"),"Uniform location"),this.K=$s(u.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const u=this.g;u.uniform1i(this.K,0),u.uniform1i(this.L,1),u.uniform1i(this.U,2)}close(){this.B&&this.g.deleteTexture(this.B),this.j&&this.g.deleteTexture(this.j),super.close()}},_y=class extends Yi{H(){return`
35  precision mediump float;
36  uniform sampler2D maskTexture;
37  uniform sampler2D defaultTexture;
38  uniform sampler2D overlayTexture;
39  varying vec2 vTex;
40  void main() {
41    float confidence = texture2D(maskTexture, vTex).r;
42    vec4 defaultColor = texture2D(defaultTexture, vTex);
43    vec4 overlayColor = texture2D(overlayTexture, vTex);
44    // Apply the alpha from the overlay and merge in the default color
45    overlayColor = mix(defaultColor, overlayColor, overlayColor.a);
46    gl_FragColor = mix(defaultColor, overlayColor, confidence);
47  }
48 `}C(){const u=this.g;u.activeTexture(u.TEXTURE1),this.j=Wo(this,u),u.activeTexture(u.TEXTURE2),this.B=Wo(this,u)}m(){super.m();const u=this.g;this.K=$s(u.getUniformLocation(this.h,"defaultTexture"),"Uniform location"),this.L=$s(u.getUniformLocation(this.h,"overlayTexture"),"Uniform location"),this.I=$s(u.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const u=this.g;u.uniform1i(this.I,0),u.uniform1i(this.K,1),u.uniform1i(this.L,2)}close(){this.j&&this.g.deleteTexture(this.j),this.B&&this.g.deleteTexture(this.B),super.close()}};function Zi(u,f){switch(f){case 0:return u.g.find(x=>x instanceof Uint8Array);case 1:return u.g.find(x=>x instanceof Float32Array);case 2:return u.g.find(x=>typeof WebGLTexture<"u"&&x instanceof WebGLTexture);default:throw Error(`Type is not supported: ${f}`)}}function Op(u){var f=Zi(u,1);if(!f){if(f=Zi(u,0))f=new Float32Array(f).map(I=>I/255);else{f=new Float32Array(u.width*u.height);const I=zl(u);var x=ln(u);if(Xi(x,I,vm(u)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){x=new Float32Array(u.width*u.height*4),I.readPixels(0,0,u.width,u.height,I.RGBA,I.FLOAT,x);for(let C=0,D=0;C<f.length;++C,D+=4)f[C]=x[D]}else I.readPixels(0,0,u.width,u.height,I.RED,I.FLOAT,f)}u.g.push(f)}return f}function vm(u){let f=Zi(u,2);if(!f){const x=zl(u);f=gt(u);const I=Op(u),C=md(u);x.texImage2D(x.TEXTURE_2D,0,C,u.width,u.height,0,x.RED,x.FLOAT,I),va(u)}return f}function zl(u){if(!u.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return u.h||(u.h=$s(u.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),u.h}function md(u){if(u=zl(u),!Pl)if(u.getExtension("EXT_color_buffer_float")&&u.getExtension("OES_texture_float_linear")&&u.getExtension("EXT_float_blend"))Pl=u.R32F;else{if(!u.getExtension("EXT_color_buffer_half_float"))throw Error("GPU does not fully support 4-channel float32 or float16 formats");Pl=u.R16F}return Pl}function ln(u){return u.l||(u.l=new Yi),u.l}function gt(u){const f=zl(u);f.viewport(0,0,u.width,u.height),f.activeTexture(f.TEXTURE0);let x=Zi(u,2);return x||(x=Wo(ln(u),f,u.m?f.LINEAR:f.NEAREST),u.g.push(x),u.j=!0),f.bindTexture(f.TEXTURE_2D,x),x}function va(u){u.h.bindTexture(u.h.TEXTURE_2D,null)}var Pl,Ue=class{constructor(u,f,x,I,C,D,W){this.g=u,this.m=f,this.j=x,this.canvas=I,this.l=C,this.width=D,this.height=W,this.j&&--Jc===0&&console.error("You seem to be creating MPMask instances without invoking .close(). This leaks resources.")}Ha(){return!!Zi(this,0)}la(){return!!Zi(this,1)}R(){return!!Zi(this,2)}ka(){return(u=Zi(this,0))||(u=Op(this),u=new Uint8Array(u.map(f=>255*f)),this.g.push(u)),u;var u}ja(){return Op(this)}N(){return vm(this)}clone(){const u=[];for(const f of this.g){let x;if(f instanceof Uint8Array)x=new Uint8Array(f);else if(f instanceof Float32Array)x=new Float32Array(f);else{if(!(f instanceof WebGLTexture))throw Error(`Type is not supported: ${f}`);{const I=zl(this),C=ln(this);I.activeTexture(I.TEXTURE1),x=Wo(C,I,this.m?I.LINEAR:I.NEAREST),I.bindTexture(I.TEXTURE_2D,x);const D=md(this);I.texImage2D(I.TEXTURE_2D,0,D,this.width,this.height,0,I.RED,I.FLOAT,null),I.bindTexture(I.TEXTURE_2D,null),Xi(C,I,x),Ll(C,I,!1,()=>{gt(this),I.clearColor(0,0,0,0),I.clear(I.COLOR_BUFFER_BIT),I.drawArrays(I.TRIANGLE_FAN,0,4),va(this)}),qr(C),va(this)}}u.push(x)}return new Ue(u,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&zl(this).deleteTexture(Zi(this,2)),Jc=-1}};Ue.prototype.close=Ue.prototype.close,Ue.prototype.clone=Ue.prototype.clone,Ue.prototype.getAsWebGLTexture=Ue.prototype.N,Ue.prototype.getAsFloat32Array=Ue.prototype.ja,Ue.prototype.getAsUint8Array=Ue.prototype.ka,Ue.prototype.hasWebG
48LTexture=Ue.prototype.R,Ue.prototype.hasFloat32Array=Ue.prototype.la,Ue.prototype.hasUint8Array=Ue.prototype.Ha;var Jc=250;const Lt={color:"white",lineWidth:4,radius:6};function se(u){return{...Lt,fillColor:(u=u||{}).color,...u}}function qn(u,f){return u instanceof Function?u(f):u}function Mn(u,f,x){return Math.max(Math.min(f,x),Math.min(Math.max(f,x),u))}function mn(u){if(!u.l)throw Error("CPU rendering requested but CanvasRenderingContext2D not provided.");return u.l}function eh(u){if(!u.j)throw Error("GPU rendering requested but WebGL2RenderingContext not provided.");return u.j}function km(u,f,x){if(f.R())x(f.N());else{const I=f.la()?f.ja():f.ka();u.m=u.m??new Yi;const C=eh(u);x((u=new Ue([I],f.m,!1,C.canvas,u.m,f.width,f.height)).N()),u.close()}}function Nm(u,f,x,I){const C=function(fe){return fe.g||(fe.g=new wm),fe.g}(u),D=eh(u),W=Array.isArray(x)?new ImageData(new Uint8ClampedArray(x),1,1):x;Ll(C,D,!0,()=>{(function(re,ut,qt,un){const rn=re.g;if(rn.activeTexture(rn.TEXTURE0),rn.bindTexture(rn.TEXTURE_2D,ut),rn.activeTexture(rn.TEXTURE1),rn.bindTexture(rn.TEXTURE_2D,re.B),rn.texImage2D(rn.TEXTURE_2D,0,rn.RGBA,rn.RGBA,rn.UNSIGNED_BYTE,qt),re.I&&function(pr,br){if(pr!==br)return!1;pr=pr.entries(),br=br.entries();for(const[Qi,Ji]of pr){pr=Qi;const ui=Ji;var tr=br.next();if(tr.done)return!1;const[Ru,Cd]=tr.value;if(tr=Cd,pr!==Ru||ui[0]!==tr[0]||ui[1]!==tr[1]||ui[2]!==tr[2]||ui[3]!==tr[3])return!1}return!!br.next().done}(re.I,un))rn.activeTexture(rn.TEXTURE2),rn.bindTexture(rn.TEXTURE_2D,re.j);else{re.I=un;const pr=Array(1024).fill(0);un.forEach((br,tr)=>{if(br.length!==4)throw Error(`Color at index ${tr} is not a four-channel value.`);pr[4*tr]=br[0],pr[4*tr+1]=br[1],pr[4*tr+2]=br[2],pr[4*tr+3]=br[3]}),rn.activeTexture(rn.TEXTURE2),rn.bindTexture(rn.TEXTURE_2D,re.j),rn.texImage2D(rn.TEXTURE_2D,0,rn.RGBA,256,1,0,rn.RGBA,rn.UNSIGNED_BYTE,new Uint8Array(pr))}})(C,f,W,I),D.clearColor(0,0,0,0),D.clear(D.COLOR_BUFFER_BIT),D.drawArrays(D.TRIANGLE_FAN,0,4);const fe=C.g;fe.activeTexture(fe.TEXTURE0),fe.bindTexture(fe.TEXTURE_2D,null),fe.activeTexture(fe.TEXTURE1),fe.bindTexture(fe.TEXTURE_2D,null),fe.activeTexture(fe.TEXTURE2),fe.bindTexture(fe.TEXTURE_2D,null)})}function Im(u,f,x,I){const C=eh(u),D=function(re){return re.h||(re.h=new _y),re.h}(u),W=Array.isArray(x)?new ImageData(new Uint8ClampedArray(x),1,1):x,fe=Array.isArray(I)?new ImageData(new Uint8ClampedArray(I),1,1):I;Ll(D,C,!0,()=>{var re=D.g;re.activeTexture(re.TEXTURE0),re.bindTexture(re.TEXTURE_2D,f),re.activeTexture(re.TEXTURE1),re.bindTexture(re.TEXTURE_2D,D.j),re.texImage2D(re.TEXTURE_2D,0,re.RGBA,re.RGBA,re.UNSIGNED_BYTE,W),re.activeTexture(re.TEXTURE2),re.bindTexture(re.TEXTURE_2D,D.B),re.texImage2D(re.TEXTURE_2D,0,re.RGBA,re.RGBA,re.UNSIGNED_BYTE,fe),C.clearColor(0,0,0,0),C.clear(C.COLOR_BUFFER_BIT),C.drawArrays(C.TRIANGLE_FAN,0,4),C.bindTexture(C.TEXTURE_2D,null),(re=D.g).activeTexture(re.TEXTURE0),re.bindTexture(re.TEXTURE_2D,null),re.activeTexture(re.TEXTURE1),re.bindTexture(re.TEXTURE_2D,null),re.activeTexture(re.TEXTURE2),re.bindTexture(re.TEXTURE_2D,null)})}var gs=class{constructor(u,f){u instanceof CanvasRenderingContext2D||u instanceof OffscreenCanvasRenderingContext2D?(this.l=u,this.j=f):this.j=u}Aa(u,f){if(u){var x=mn(this);f=se(f),x.save();var I=x.canvas,C=0;for(const D of u)x.fillStyle=qn(f.fillColor,{index:C,from:D}),x.strokeStyle=qn(f.color,{index:C,from:D}),x.lineWidth=qn(f.lineWidth,{index:C,from:D}),(u=new Path2D).arc(D.x*I.width,D.y*I.height,qn(f.radius,{index:C,from:D}),0,2*Math.PI),x.fill(u),x.stroke(u),++C;
48x.restore()}}za(u,f,x){if(u&&f){var I=mn(this);x=se(x),I.save();var C=I.canvas,D=0;for(const W of f){I.beginPath(),f=u[W.start];const fe=u[W.end];f&&fe&&(I.strokeStyle=qn(x.color,{index:D,from:f,to:fe}),I.lineWidth=qn(x.lineWidth,{index:D,from:f,to:fe}),I.moveTo(f.x*C.width,f.y*C.height),I.lineTo(fe.x*C.width,fe.y*C.height)),++D,I.stroke()}I.restore()}}wa(u,f){const x=mn(this);f=se(f),x.save(),x.beginPath(),x.lineWidth=qn(f.lineWidth,{}),x.strokeStyle=qn(f.color,{}),x.fillStyle=qn(f.fillColor,{}),x.moveTo(u.originX,u.originY),x.lineTo(u.originX+u.width,u.originY),x.lineTo(u.originX+u.width,u.originY+u.height),x.lineTo(u.originX,u.originY+u.height),x.lineTo(u.originX,u.originY),x.stroke(),x.fill(),x.restore()}xa(u,f,x=[0,0,0,255]){this.l?function(I,C,D,W){const fe=eh(I);km(I,C,re=>{Nm(I,re,D,W),(re=mn(I)).drawImage(fe.canvas,0,0,re.canvas.width,re.canvas.height)})}(this,u,x,f):Nm(this,u.N(),x,f)}ya(u,f,x){this.l?function(I,C,D,W){const fe=eh(I);km(I,C,re=>{Im(I,re,D,W),(re=mn(I)).drawImage(fe.canvas,0,0,re.canvas.width,re.canvas.height)})}(this,u,f,x):Im(this,u.N(),f,x)}close(){this.g?.close(),this.g=void 0,this.h?.close(),this.h=void 0,this.m?.close(),this.m=void 0}};function Br(u,f){switch(f){case 0:return u.g.find(x=>x instanceof ImageData);case 1:return u.g.find(x=>typeof ImageBitmap<"u"&&x instanceof ImageBitmap);case 2:return u.g.find(x=>typeof WebGLTexture<"u"&&x instanceof WebGLTexture);default:throw Error(`Type is not supported: ${f}`)}}function th(u){var f=Br(u,0);if(!f){f=Bl(u);const x=Vl(u),I=new Uint8Array(u.width*u.height*4);Xi(x,f,Pt(u)),f.readPixels(0,0,u.width,u.height,f.RGBA,f.UNSIGNED_BYTE,I),qr(x),f=new ImageData(new Uint8ClampedArray(I.buffer),u.width,u.height),u.g.push(f)}return f}function Pt(u){let f=Br(u,2);if(!f){const x=Bl(u);f=ii(u);const I=Br(u,1)||th(u);x.texImage2D(x.TEXTURE_2D,0,x.RGBA,x.RGBA,x.UNSIGNED_BYTE,I),as(u)}return f}function Bl(u){if(!u.canvas)throw Error("Conversion to different image formats require that a canvas is passed when iniitializing the image.");return u.h||(u.h=$s(u.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),u.h}function Vl(u){return u.l||(u.l=new Yi),u.l}function ii(u){const f=Bl(u);f.viewport(0,0,u.width,u.height),f.activeTexture(f.TEXTURE0);let x=Br(u,2);return x||(x=Wo(Vl(u),f),u.g.push(x),u.m=!0),f.bindTexture(f.TEXTURE_2D,x),x}function as(u){u.h.bindTexture(u.h.TEXTURE_2D,null)}function st(u){const f=Bl(u);return Ll(Vl(u),f,!0,()=>function(x,I){const C=x.canvas;if(C.width===x.width&&C.height===x.height)return I();const D=C.width,W=C.height;return C.width=x.width,C.height=x.height,x=I(),C.width=D,C.height=W,x}(u,()=>{if(f.bindFramebuffer(f.FRAMEBUFFER,null),f.clearColor(0,0,0,0),f.clear(f.COLOR_BUFFER_BIT),f.drawArrays(f.TRIANGLE_FAN,0,4),!(u.canvas instanceof OffscreenCanvas))throw Error("Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas");return u.canvas.transferToImageBitmap()}))}gs.prototype.close=gs.prototype.close,gs.prototype.drawConfidenceMask=gs.prototype.ya,gs.prototype.drawCategoryMask=gs.prototype.xa,gs.prototype.drawBoundingBox=gs.prototype.wa,gs.prototype.drawConnectors=gs.prototype.za,gs.prototype.drawLandmarks=gs.prototype.Aa,gs.lerp=function(u,f,x,I,C){return Mn(I*(1-(u-f)/(x-f))+C*(1-(x-u)/(x-f)),I,C)},gs.clamp=Mn;var Vr=class{constructor(u,f,x,I,C,D,W){this.g=u,this.j=f,this.m=x,this.canvas=I,this.l=C,this.width=D,this.height=W,(this.j||this.m)&&--oi===0&&console.error("You seem to be creating MPImage instances without invoking .close(). This leaks resources.")}Ga(){return!!Br(this,0)}ma(){return!!Br(this,1)}R(){return!!Br(this,2)}Ea(){return th(this)}Da(){var u=Br(this,1);return u||(Pt(this),ii(this),u=st(this),as(this),this.g.push(u),this.j=!0),u}N(){return Pt(this)}clone(){const u=[];for(const f of this.g){let x;if(f instanceof ImageData)x=new ImageData(f.data,this.width,this.height);else if(f instanceof WebGLTexture){const I=Bl(this),C=Vl(this);I.activeTexture(I.TEXTURE1),x=Wo(C,I),I.bindTexture(I.TEXTURE_2D,x),I.texImage2D(I.TEXTURE_2D,0,I.RGBA,this.width,this.height,0,I.RGBA,I.UNSIGNED_BYTE,null),I.bindTexture(I.TEXTURE_2D,null),Xi(C,I,x),Ll(C,I,!1,()=>{ii(this),I.clearColor(0,0,0,0),I.clear(I.COLOR_BUFFER_BIT),I.drawArrays(I.TRIANGLE_FAN,0,4),as(this)}),qr(C),as(this)}else{if(!(f instanceof ImageBitmap))throw Error(`Type is not supported: ${f}`);Pt(this),ii(this),x=st(this),as(this)}u.push(x)}return new Vr(u,this.ma(),this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&Br(this,1).close(),this.m&&Bl(this).deleteTexture(Br(this,2)),oi=-1}};Vr.prototype.close=Vr.prototype.close,Vr.prototype.clone=Vr.prototype.clone,Vr.prototype.getAsWebGLTexture=Vr.prototype.N,Vr.prototype.getAsImageBitmap=Vr.prototype.Da,Vr.prototype.getAsImageData=Vr.prototype.Ea,Vr.prototype.hasWebG
vendor: 9,196 bytes, line 48
48LTexture=Vr.prototype.R,Vr.prototype.hasImageBitmap=Vr.prototype.ma,Vr.prototype.hasImageData=Vr.prototype.Ga;var oi=250;function aa(...u){return u.map(([f,x])=>({start:f,end:x}))}const $u=function(u){return class extends u{Ma(){this.i._registerModelResourcesGraphService()}}}((gd=class{constructor(u,f){this.l=!0,this.i=u,this.g=null,this.h=0,this.m=typeof this.i._addIntToInputStream=="function",f!==void 0?this.i.canvas=f:_p()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(u){const f=await(await fetch(u)).arrayBuffer();u=!(u.endsWith(".pbtxt")||u.endsWith(".textproto")),this.setGraph(new Uint8Array(f),u)}setGraphFromString(u){this.setGraph(new TextEncoder().encode(u),!1)}setGraph(u,f){const x=u.length,I=this.i._malloc(x);this.i.HEAPU8.set(u,I),f?this.i._changeBinaryGraph(x,I):this.i._changeTextGraph(x,I),this.i._free(I)}configureAudio(u,f,x,I,C){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),Ot(this,I||"input_audio",D=>{Ot(this,C=C||"audio_header",W=>{this.i._configureAudio(D,W,u,f??0,x)})})}setAutoResizeCanvas(u){this.l=u}setAutoRenderToScreen(u){this.i._setAutoRenderToScreen(u)}setGpuBufferVerticalFlip(u){this.i.gpuOriginForWebTexturesIsBottomLeft=u}ea(u){ms(this,"__graph_config__",f=>{u(f)}),Ot(this,"__graph_config__",f=>{this.i._getGraphConfig(f,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(u){this.i.errorListener=u}attachEmptyPacketListener(u,f){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[u]=f}addAudioToStream(u,f,x){this.addAudioToStreamWithShape(u,0,0,f,x)}addAudioToStreamWithShape(u,f,x,I,C){const D=4*u.length;this.h!==D&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(D),this.h=D),this.i.HEAPF32.set(u,this.g/4),Ot(this,I,W=>{this.i._addAudioToInputStream(this.g,f,x,W,C)})}addGpuBufferToStream(u,f,x){Ot(this,f,I=>{const[C,D]=Dp(this,u,I);this.i._addBoundTextureToStream(I,C,D,x)})}addBoolToStream(u,f,x){Ot(this,f,I=>{this.i._addBoolToInputStream(u,I,x)})}addDoubleToStream(u,f,x){Ot(this,f,I=>{this.i._addDoubleToInputStream(u,I,x)})}addFloatToStream(u,f,x){Ot(this,f,I=>{this.i._addFloatToInputStream(u,I,x)})}addIntToStream(u,f,x){Ot(this,f,I=>{this.i._addIntToInputStream(u,I,x)})}addUintToStream(u,f,x){Ot(this,f,I=>{this.i._addUintToInputStream(u,I,x)})}addStringToStream(u,f,x){Ot(this,f,I=>{Ot(this,u,C=>{this.i._addStringToInputStream(C,I,x)})})}addStringRecordToStream(u,f,x){Ot(this,f,I=>{dd(this,Object.keys(u),C=>{dd(this,Object.values(u),D=>{this.i._addFlatHashMapToInputStream(C,D,Object.keys(u).length,I,x)})})})}addProtoToStream(u,f,x,I){Ot(this,x,C=>{Ot(this,f,D=>{const W=this.i._malloc(u.length);this.i.HEAPU8.set(u,W),this.i._addProtoToInputStream(W,u.length,D,C,I),this.i._free(W)})})}addEmptyPacketToStream(u,f){Ot(this,u,x=>{this.i._addEmptyPacketToInputStream(x,f)})}addBoolVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateBoolVector(u.length);if(!C)throw Error("Unable to allocate new bool vector on heap.");for(const D of u)this.i._addBoolVectorEntry(C,D);this.i._addBoolVectorToInputStream(C,I,x)})}addDoubleVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateDoubleVector(u.length);if(!C)throw Error("Unable to allocate new double vector on heap.");for(const D of u)this.i._addDoubleVectorEntry(C,D);this.i._addDoubleVectorToInputStream(C,I,x)})}addFloatVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateFloatVector(u.length);if(!C)throw Error("Unable to allocate new float vector on heap.");for(const D of u)this.i._addFloatVectorEntry(C,D);this.i._addFloatVectorToInputStream(C,I,x)})}addIntVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateIntVector(u.length);if(!C)throw Error("Unable to allocate new int vector on heap.");for(const D of u)this.i._addIntVectorEntry(C,D);this.i._addIntVectorToInputStream(C,I,x)})}addUintVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateUintVector(u.length);if(!C)throw Error("Unable to allocate new unsigned int vector on heap.");for(const D of u)this.i._addUintVectorEntry(C,D);this.i._addUintVectorToInputStream(C,I,x)})}addStringVectorToStream(u,f,x){Ot(this,f,I=>{const C=this.i._allocateStringVector(u.length);if(!C)throw Error("Unable to allocate new string vector on heap.");for(const D of u)Ot(this,D,W=>{this.i._addStringVectorEntry(C,W)});this.i._addStringVectorToInputStream(C,I,x)})}addBoolToInputSidePacket(u,f){Ot(this,f,x=>{this.i._addBoolToInputSidePacket(u,x)})}addDoubleToInputSidePacket(u,f){Ot(this,f,x=>{this.i._addDoubleToInputSidePacket(u,x)})}addFloatToInputSidePacket(u,f){Ot(this,f,x=>{this.i._addFloatToInputSidePacket(u,x)})}addIntToInputSidePacket(u,f){Ot(this,f,x=>{this.i._addIntToInputSidePacket(u,x)})}addUintToInputSidePacket(u,f){Ot(this,f,x=>{this.i._addUintToInputSidePacket(u,x)})}addStringToInputSidePacket(u,f){Ot(this,f,x=>{Ot(this,u,I=>{this.i._addStringToInputSidePacket(I,x)})})}addProtoToInputSidePacket(u,f,x){Ot(this,x,I=>{Ot(this,f,C=>{const D=this.i._malloc(u.length);this.i.HEAPU8.set(u,D),this.i._addProtoToInputSidePacket(D,u.length,C,I),this.i._free(D)})})}addBoolVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateBoolVector(u.length);if(!I)throw Error("Unable to allocate new bool vector on heap.");for(const C of u)this.i._addBoolVectorEntry(I,C);this.i._addBoolVectorToInputSidePacket(I,x)})}addDoubleVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateDoubleVector(u.length);if(!I)throw Error("Unable to allocate new double vector on heap.");for(const C of u)this.i._addDoubleVectorEntry(I,C);this.i._addDoubleVectorToInputSidePacket(I,x)})}addFloatVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateFloatVector(u.length);if(!I)throw Error("Unable to allocate new float vector on heap.");for(const C of u)this.i._addFloatVectorEntry(I,C);this.i._addFloatVectorToInputSidePacket(I,x)})}addIntVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateIntVector(u.length);if(!I)throw Error("Unable to allocate new int vector on heap.");for(const C of u)this.i._addIntVectorEntry(I,C);this.i._addIntVectorToInputSidePacket(I,x)})}addUintVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateUintVector(u.length);if(!I)throw Error("Unable to allocate new unsigned int vector on heap.");for(const C of u)this.i._addUintVectorEntry(I,C);this.i._addUintVectorToInputSidePacket(I,x)})}addStringVectorToInputSidePacket(u,f){Ot(this,f,x=>{const I=this.i._allocateStringVector(u.length);if(!I)throw Error("Unable to allocate new string vector on heap.");for(const C of u)Ot(this,C,D=>{this.i._addStringVectorEntry(I,D)});this.i._addStringVectorToInputSidePacket(I,x)})}attachBoolListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachBoolListener(x)})}attachBoolVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachBoolVectorListener(x)})}attachIntListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachIntListener(x)})}attachIntVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachIntVectorListener(x)})}attachUintListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachUintListener(x)})}attachUintVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachUintVectorListener(x)})}attachDoubleListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachDoubleListener(x)})}attachDoubleVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachDoubleVectorListener(x)})}attachFloatListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachFloatListener(x)})}attachFloatVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachFloatVectorListener(x)})}attachStringListener(u,f){ms(this,u,f),Ot(this,u,x=>{this.i._attachStringListener(x)})}attachStringVectorListener(u,f){Ki(this,u,f),Ot(this,u,x=>{this.i._attachStringVectorListener(x)})}attachProtoListener(u,f,x){ms(this,u,f),Ot(this,u,I=>{this.i._attachProtoListener(I,x||!1)})}attachProtoVectorListener(u,f,x){Ki(this,u,f),Ot(this,u,I=>{this.i._attachProtoVectorListener(I,x||!1)})}attachAudioListener(u,f,x){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),ms(this,u,(I,C)=>{I=new Float32Array(I.buffer,I.byteOffset,I.length/4),f(I,C)}),Ot(this,u,I=>{this.i._attachAudioListener(I,x||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends gd{get ga(){return this.i}sa(u,f,x){Ot(this,f,I=>{const[C,D]=Dp(this,u,I);this.ga._addBoundTextureAsImageToStream(I,C,D,x)})}V(u,f){ms(this,u,f),Ot(this,u,x=>{this.ga._attachImageListener(x)})}da(u,f){Ki(this,u,f),Ot(this,u,x=>{this.ga._attachImageVectorListener(x)})}}));var gd,Ar=class extends $u{};async function ot(u,f,x){return async function(I,C,D,W){return async function(fe,re,ut,qt){return fe=await(async(un,rn,pr,br,tr)=>{if(rn&&await hd(rn),!self.ModuleFactory||pr&&(await hd(pr),!self.ModuleFactory)
48)throw Error("ModuleFactory not set.");return self.Module&&tr&&((rn=self.Module).locateFile=tr.locateFile,tr.mainScriptUrlOrBlob&&(rn.mainScriptUrlOrBlob=tr.mainScriptUrlOrBlob)),tr=await self.ModuleFactory(self.Module||tr),self.ModuleFactory=self.Module=void 0,new un(tr,br)})(fe,ut.wasmLoaderPath,ut.assetLoaderPath,re,{locateFile:un=>un.endsWith(".wasm")?ut.wasmBinaryPath.toString():ut.assetBinaryPath&&un.endsWith(".data")?ut.assetBinaryPath.toString():un}),await fe.o(qt),fe}(I,C,D,W)}(u,x.canvas??(_p()?void 0:document.createElement("canvas")),f,x)}function yd(u,f,x,I){if(u.U){const D=new Kc;if(x?.regionOfInterest){if(!u.ra)throw Error("This task doesn't support region-of-interest.");var C=x.regionOfInterest;if(C.left>=C.right||C.top>=C.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(C.left<0||C.top<0||C.right>1||C.bottom>1)throw Error("Expected RectF values to be in [0,1].");Ft(D,1,(C.left+C.right)/2),Ft(D,2,(C.top+C.bottom)/2),Ft(D,4,C.right-C.left),Ft(D,3,C.bottom-C.top)}else Ft(D,1,.5),Ft(D,2,.5),Ft(D,4,1),Ft(D,3,1);if(x?.rotationDegrees){if(x?.rotationDegrees%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ft(D,5,-Math.PI*x.rotationDegrees/180),x?.rotationDegrees%180!=0){const[W,fe]=Uo(f);x=rr(D,3)*fe/W,C=rr(D,4)*W/fe,Ft(D,4,x),Ft(D,3,C)}}u.g.addProtoToStream(D.g(),"mediapipe.NormalizedRect",u.U,I)}u.g.sa(f,u.ba,I??performance.now()),u.finishProcessing()}function An(u,f,x){if(u.baseOptions?.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");yd(u,f,x,u.B+1)}function ys(u,f,x,I){if(!u.baseOptions?.g())throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");yd(u,f,x,I)}function er(u,f,x,I){var C=f.data;const D=f.width,W=D*(f=f.height);if((C instanceof Uint8Array||C instanceof Float32Array)&&C.length!==W)throw Error("Unsupported channel count: "+C.length/W);return u=new Ue([C],x,!1,u.g.i.canvas,u.P,D,f),I?u.clone():u}var Gt=class extends fd{constructor(u,f,x,I){super(u),this.g=u,this.ba=f,this.U=x,this.ra=I,this.P=new Yi}l(u,f=!0){if("runningMode"in u&&$i(this.baseOptions,2,!!u.runningMode&&u.runningMode!=="IMAGE"),u.canvas!==void 0&&this.g.i.canvas!==u.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(u,f)}close(){this.P.close(),super.close()}};Gt.prototype.close=Gt.prototype.close;var Nr=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect_in",!1),this.j={detections:[]},Ht(u=this.h=new Kr,0,1,f=new cr),Ft(this.h,2,.5),Ft(this.h,3,.3)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return"minDetectionConfidence"in u&&Ft(this.h,2,u.minDetectionConfidence??.5),"minSuppressionThreshold"in u&&Ft(this.h,3,u.minSuppressionThreshold??.3),this.l(u)}D(u,f){return this.j={detections:[]},An(this,u,f),this.j}F(u,f,x){return this.j={detections:[]},ys(this,u,x,f),this.j}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect_in"),$n(u,"detections");const f=new Ps;zs(f,um,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect_in"),dn(x,"DETECTIONS:detections"),x.o(f),sa(u,x),this.g.attachProtoVectorListener("detections",(I,C)=>{for(const D of I)I=Qh(D),this.j.detections.push(Rp(I));Tt(this,C)}),this.g.attachEmptyPacketListener("detections",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Nr.prototype.detectForVideo=Nr.prototype.F,Nr.prototype.detect=Nr.prototype.D,Nr.prototype.setOptions=Nr.prototype.o,Nr.createFromModelPath=async function(u,f){return ot(Nr,u,{baseOptions:{modelAssetPath:f}})},Nr.createFromModelBuffer=function(u,f){return ot(Nr,u,{baseOptions:{modelAssetBuffer:f}})},Nr.createFromOptions=function(u,f){return ot(Nr,u,f)};var nh=aa([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),Ul=aa([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),rh=aa([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),bd=aa([474,475],[475,476],[476,477],[477,474]),Lp=aa([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),xd=aa([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Go=aa([469,470],[470,471],[471,472],[472,469]),zp=aa([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,3
4861],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),Sm=[...nh,...Ul,...rh,...Lp,...xd,...zp],Pp=aa
vendor: 14,070 bytes, line 48
48([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,23
vendor: 10,283 bytes, line 48
481],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function 
vendor: 10,687 bytes, line 48
48Bp(u){u.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var dr=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Ht(u=this.h=new Fl,0,1,f=new cr),this.v=new P,Ht(this.h,0,3,this.v),this.s=new Kr,Ht(this.h,0,2,this.s),ta(this.s,4,1),Ft(this.s,2,.5),Ft(this.v,2,.5),Ft(this.h,4,.5)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return"numFaces"in u&&ta(this.s,4,u.numFaces??1),"minFaceDetectionConfidence"in u&&Ft(this.s,2,u.minFaceDetectionConfidence??.5),"minTrackingConfidence"in u&&Ft(this.h,4,u.minTrackingConfidence??.5),"minFacePresenceConfidence"in u&&Ft(this.v,2,u.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in u&&(this.outputFaceBlendshapes=!!u.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in u&&(this.outputFacialTransformationMatrixes=!!u.outputFacialTransformationMatrixes),this.l(u)}D(u,f){return Bp(this),An(this,u,f),this.j}F(u,f,x){return Bp(this),ys(this,u,x,f),this.j}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"face_landmarks");const f=new Ps;zs(f,Gi,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"NORM_LANDMARKS:face_landmarks"),x.o(f),sa(u,x),this.g.attachProtoVectorListener("face_landmarks",(I,C)=>{for(const D of I)I=Su(D),this.j.faceLandmarks.push(Yc(I));Tt(this,C)}),this.g.attachEmptyPacketListener("face_landmarks",I=>{Tt(this,I)}),this.outputFaceBlendshapes&&($n(u,"blendshapes"),dn(x,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(I,C)=>{if(this.outputFaceBlendshapes)for(const D of I)I=Wi(D),this.j.faceBlendshapes.push(ld(I.g()??[]));Tt(this,C)}),this.g.attachEmptyPacketListener("blendshapes",I=>{Tt(this,I)})),this.outputFacialTransformationMatrixes&&($n(u,"face_geometry"),dn(x,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(I,C)=>{if(this.outputFacialTransformationMatrixes)for(const D of I)(I=xn(lm(D),Ey,2))&&this.j.facialTransformationMatrixes.push({rows:ps(ns(I,1),0)??0,columns:ps(ns(I,2),0)??0,data:Qa(I,3,Fs,fa()).slice()??[]});Tt(this,C)}),this.g.attachEmptyPacketListener("face_geometry",I=>{Tt(this,I)})),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};dr.prototype.detectForVideo=dr.prototype.F,dr.prototype.detect=dr.prototype.D,dr.prototype.setOptions=dr.prototype.o,dr.createFromModelPath=function(u,f){return ot(dr,u,{baseOptions:{modelAssetPath:f}})},dr.createFromModelBuffer=function(u,f){return ot(dr,u,{baseOptions:{modelAssetBuffer:f}})},dr.createFromOptions=function(u,f){return ot(dr,u,f)},dr.FACE_LANDMARKS_LIPS=nh,dr.FACE_LANDMARKS_LEFT_EYE=Ul,dr.FACE_LANDMARKS_LEFT_EYEBROW=rh,dr.FACE_LANDMARKS_LEFT_IRIS=bd,dr.FACE_LANDMARKS_RIGHT_EYE=Lp,dr.FACE_LANDMARKS_RIGHT_EYEBROW=xd,dr.FACE_LANDMARKS_RIGHT_IRIS=Go,dr.FACE_LANDMARKS_FACE_OVAL=zp,dr.FACE_LANDMARKS_CONTOURS=Sm,dr.FACE_LANDMARKS_TESSELATION=Pp;var ka=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!0),Ht(u=this.j=new Hi,0,1,f=new cr)}get baseOptions(){return xn(this.j,cr,1)}set baseOptions(u){Ht(this.j,0,1,u)}o(u){return super.l(u)}Pa(u,f,x){const I=typeof f!="function"?f:{};if(this.h=typeof f=="function"?f:x,An(this,u,I??{}),!this.h)return this.s}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"stylized_image");const f=new Ps;zs(f,Bs,this.j);const x=new gr;Fn(x,"mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"STYLIZED_IMAGE:stylized_image"),x.o(f),sa(u,x),this.g.V("stylized_image",(I,C)=>{var D=!this.h,W=I.data,fe=I.width;const re=fe*(I=I.height);if(W instanceof Uint8Array)if(W.length===3*re){const ut=new Uint8ClampedArray(4*re);for(let qt=0;qt<re;++qt)ut[4*qt]=W[3*qt],ut[4*qt+1]=W[3*qt+1],ut[4*qt+2]=W[3*qt+2],ut[4*qt+3]=255;W=new ImageData(ut,fe,I)}else{if(W.length!==4*re)throw Error("Unsupported channel count: "+W.length/re);W=new ImageData(new Uint8ClampedArray(W.buffer,W.byteOffset,W.length),fe,I)}else if(!(W instanceof WebGLTexture))throw Error(`Unsupported format: ${W.constructor.name}`);fe=new Vr([W],!1,!1,this.g.i.canvas,this.P,fe,I),this.s=D=D?fe.clone():fe,this.h&&this.h(D),Tt(this,C)}),this.g.attachEmptyPacketListener("stylized_image",I=>{this.s=null,this.h&&this.h(null),Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};ka.prototype.stylize=ka.prototype.Pa,ka.prototype.setOptions=ka.prototype.o,ka.createFromModelPath=function(u,f){return ot(ka,u,{baseOptions:{modelAssetPath:f}})},ka.createFromModelBuffer=function(u,f){return ot(ka,u,{baseOptions:{modelAssetBuffer:f}})},ka.createFromOptions=function(u,f){return ot(ka,u,f)};var sh=aa([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function wd(u){u.gestures=[],u.landmarks=[],u.worldLandmarks=[],u.handedness=[]}function Vp(u){return u.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:u.gestures,landmarks:u.landmarks,worldLandmarks:u.worldLandmarks,handedness:u.handedness,handednesses:u.handedness}}function vd(u,f=!0){const x=[];for(const C of u){var I=Wi(C);u=[];for(const D of I.g())I=f&&ns(D,1)!=null?ps(ns(D,1),0):-1,u.push({score:rr(D,2)??0,index:I,categoryName:Ls(D,3)??"",displayName:Ls(D,4)??""});x.push(u)}return x}var As=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ht(u=this.j=new hm,0,1,f=new cr),this.s=new vp,Ht(this.j,0,2,this.s),this.C=new wp,Ht(this.s,0,3,this.C),this.v=new cm,Ht(this.s,0,2,this.v),this.h=new Cy,Ht(this.j,0,3,this.h),Ft(this.v,2,.5),Ft(this.s,4,.5),Ft(this.C,2,.5)}get baseOptions(){return xn(this.j,cr,1)}set baseOptions(u){Ht(this.j,0,1,u)}o(u){if(ta(this.v,3,u.numHands??1),"minHandDetectionConfidence"in u&&Ft(this.v,2,u.minHandDetectionConfidence??.5),"minTrackingConfidence"in u&&Ft(this.s,4,u.minTrackingConfidence??.5),"minHandPresenceConfidence"in u&&Ft(this.C,2,u.minHandPresenceConfidence??.5),u.cannedGesturesClassifierOptions){var f=new ba,x=f,I=ud(u.cannedGesturesClassifierOptions,xn(this.h,ba,3)?.h());Ht(x,0,2,I),Ht(this.h,0,3,f)}else u.cannedGesturesClassifierOptions===void 0&&xn(this.h,ba,3)?.g();return u.customGesturesClassifierOptions?(Ht(x=f=new ba,0,2,I=ud(u.customGesturesClassifierOptions,xn(this.h,ba,4)?.h())),Ht(this.h,0,4,f)):u.customGesturesClassifierOptions===void 0&&xn(this.h,ba,4)?.g(),this.l(u)}Ka(u,f){return wd(this),An(this,u,f),Vp(this)}La(u,f,x){return wd(this),ys(this,u,x,f),Vp(this)}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"hand_gestures"),$n(u,"hand_landmarks"),$n(u,"world_hand_landmarks"),$n(u,"handedness");const f=new Ps;zs(f,on,this.j);const x=new gr;Fn(x,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"HAND_GESTURES:hand_gestures"),dn(x,"LANDMARKS:hand_landmarks"),dn(x,"WORLD_LANDMARKS:world_hand_landmarks"),dn(x,"HANDEDNESS:handedness"),x.o(f),sa(u,x),this.g.attachProtoVectorListener("hand_landmarks",(I,C)=>{for(const D of I){I=Su(D);const W=[];for(const fe of ea(I,ed,1))W.push({x:rr(fe,1)??0,y:rr(fe,2)??0,z:rr(fe,3)??0,visibility:rr(fe,4)??0});this.landmarks.push(W)}Tt(this,C)}),this.g.attachEmptyPacketListener("hand_landmarks",I=>{Tt(this,I)}),this.g.attachProtoVectorListener("world_hand_landmarks",(I,C)=>{for(const D of I){I=Bo(D);const W=[];for(const fe of ea(I,Jh,1))W.push({x:rr(fe,1)??0,y:rr(fe,2)??0,z:rr(fe,3)??0,visibility:rr(fe,4)??0});this.worldLandmarks.push(W)}Tt(this,C)}),this.g.attachEmptyPacketListener("world_hand_landmarks",I=>{Tt(this,I)}),this.g.attachProtoVectorListener("hand_gestures",(I,C)=>{this.gestures.push(...vd(I,!1)),Tt(this,C)}),this.g.attachEmptyPacketListener("hand_gestures",I=>{Tt(this,I)}),this.g.attachProtoVectorListener("handedness",(I,C)=>{this.handedness.push(...vd(I)),Tt(this,C)}),this.g.attachEmptyPacketListener("handedness",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};function kd(u){return{landmarks:u.landmarks,worldLandmarks:u.worldLandmarks,handednesses:u.handedness,handedness:u.handedness}}As.prototype.recognizeForVideo=As.prototype.La,As.prototype.recognize=As.prototype.Ka,As.prototype.setOptions=As.prototype.o,As.createFromModelPath=function(u,f){return ot(As,u,{baseOptions:{modelAssetPath:f}})},As.createFromModelBuffer=function(u,f){return ot(As,u,{baseOptions:{modelAssetBuffer:f}})},As.createFromOptions=function(u,f){return ot(As,u,f)},As.HAND_CONNECTIONS=sh;var Rs=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ht(u=this.h=new vp,0,1,f=new cr),this.s=new wp,Ht(this.h,0,3,this.s),this.j=new cm,Ht(this.h,0,2,this.j),ta(this.j,3,1),Ft(this.j,2,.5),Ft(this.s,2,.5),Ft(this.h,4,.5)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return"numHands"in u&&ta(this.j,3,u.numHands??1),"minHandDetectionConfidence"in u&&Ft(this.j,2,u.minHandDetectionConfidence??.5),"minTrackingConfidence"in u&&Ft(this.h,4,u.minTrackingConfidence??.5),"minHandPresenceConfidence"in u&&Ft(this.s,2,u.minHandPresenceConfidence??.5),this.l(u)}D(u,f){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],An(this,u,f),kd(this)}F(u,f,x){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ys(this,u,x,f),kd(this)}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"hand_landmarks"),$n(u,"world_hand_landmarks"),$n(u,"handedness");const f=new Ps;zs(f,_r,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"LANDMARKS:hand_landmarks"),dn(x,"WORLD_LANDMARKS:world_hand_landmarks"),dn(x,"HANDEDNESS:handedness"),x.o(f),sa(u,x),this.g.attachProtoVectorListener("hand_landmarks",(I,C)=>{for(const D of I)I=Su(D),this.landmarks.push(Yc(I));Tt(this,C)}),this.g.attachEmptyPacketListener("hand_landmarks",I=>{Tt(this,I)}),this.g.attachProtoVectorListener("world_hand_landmarks",(I,C)=>{for(const D of I)I=Bo(D),this.worldLandmarks.push(Eu(I));Tt(this,C)}),this.g.attachEmptyPacketListener("world_hand_landmarks",I=>{Tt(this,I)}),this.g.attachProtoVectorListener("handedness",(I,C)=>{var D=this.handedness,W=D.push;const fe=[];for(const re of I){I=Wi(re);const ut=[];for(const qt of I.g())ut.push({score:rr(qt,2)??0,index:ps(ns(qt,1),0)??-1,categoryName:Ls(qt,3)??"",dis
48playName:Ls(qt,4)??""});fe.push(ut)}W.call(D,...fe),Tt(this,C)}),this.g.attachEmptyPacketListener("handedness",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Rs.prototype.detectForVideo=Rs.prototype.F,Rs.prototype.detect=Rs.prototype.D,Rs.prototype.setOptions=Rs.prototype.o,Rs.createFromModelPath=function(u,f){return ot(Rs,u,{baseOptions:{modelAssetPath:f}})},Rs.createFromModelBuffer=function(u,f){return ot(Rs,u,{baseOptions:{modelAssetBuffer:f}})},Rs.createFromOptions=function(u,f){return ot(Rs,u,f)},Rs.HAND_CONNECTIONS=sh;var Tm=aa([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function Em(u){u.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function ah(u){try{if(!u.C)return u.h;u.C(u.h)}finally{pd(u)}}function Nd(u,f){u=Su(u),f.push(Yc(u))}var ir=class extends Gt{constructor(u,f){super(new Ar(u,f),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Ht(u=this.j=new Np,0,1,f=new cr),this.K=new wp,Ht(this.j,0,2,this.K),this.aa=new $y,Ht(this.j,0,3,this.aa),this.s=new Kr,Ht(this.j,0,4,this.s),this.I=new P,Ht(this.j,0,5,this.I),this.v=new dm,Ht(this.j,0,6,this.v),this.L=new pm,Ht(this.j,0,7,this.L),Ft(this.s,2,.5),Ft(this.s,3,.3),Ft(this.I,2,.5),Ft(this.v,2,.5),Ft(this.v,3,.3),Ft(this.L,2,.5),Ft(this.K,2,.5)}get baseOptions(){return xn(this.j,cr,1)}set baseOptions(u){Ht(this.j,0,1,u)}o(u){return"minFaceDetectionConfidence"in u&&Ft(this.s,2,u.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in u&&Ft(this.s,3,u.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in u&&Ft(this.I,2,u.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in u&&(this.outputFaceBlendshapes=!!u.outputFaceBlendshapes),"minPoseDetectionConfidence"in u&&Ft(this.v,2,u.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in u&&Ft(this.v,3,u.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in u&&Ft(this.L,2,u.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in u&&(this.outputPoseSegmentationMasks=!!u.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in u&&Ft(this.K,2,u.minHandLandmarksConfidence??.5),this.l(u)}D(u,f,x){const I=typeof f!="function"?f:{};return this.C=typeof f=="function"?f:x,Em(this),An(this,u,I),ah(this)}F(u,f,x,I){const C=typeof x!="function"?x:{};return this.C=typeof x=="function"?x:I,Em(this),ys(this,u,C,f),ah(this)}m(){var u=new jr;sr(u,"input_frames_image"),$n(u,"pose_landmarks"),$n(u,"pose_world_landmarks"),$n(u,"face_landmarks"),$n(u,"left_hand_landmarks"),$n(u,"left_hand_world_landmarks"),$n(u,"right_hand_landmarks"),$n(u,"right_hand_world_landmarks");const f=new Ps,x=new mp;vo(x,1,Da("type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),""),function(C,D){if(D!=null)if(Array.isArray(D))On(C,2,Ii(D,nu,void 0,void 0,!1));
48else{if(!(typeof D=="string"||D instanceof Ye||fn(D)))throw Error("invalid value in Any.value field: "+D+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");vo(C,2,oe(D,!1,!1),zn())}}(x,this.j.g());const I=new gr;Fn(I,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Ci(I,8,mp,x),Kn(I,"IMAGE:input_frames_image"),dn(I,"POSE_LANDMARKS:pose_landmarks"),dn(I,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),dn(I,"FACE_LANDMARKS:face_landmarks"),dn(I,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),dn(I,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),dn(I,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),dn(I,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),I.o(f),sa(u,I),Qc(this,u),this.g.attachProtoListener("pose_landmarks",(C,D)=>{Nd(C,this.h.poseLandmarks),Tt(this,D)}),this.g.attachEmptyPacketListener("pose_landmarks",C=>{Tt(this,C)}),this.g.attachProtoListener("pose_world_landmarks",(C,D)=>{var W=this.h.poseWorldLandmarks;C=Bo(C),W.push(Eu(C)),Tt(this,D)}),this.g.attachEmptyPacketListener("pose_world_landmarks",C=>{Tt(this,C)}),this.outputPoseSegmentationMasks&&(dn(I,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),Ol(this,"pose_segmentation_mask"),this.g.V("pose_segmentation_mask",(C,D)=>{this.h.poseSegmentationMasks=[er(this,C,!0,!this.C)],Tt(this,D)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",C=>{this.h.poseSegmentationMasks=[],Tt(this,C)})),this.g.attachProtoListener("face_landmarks",(C,D)=>{Nd(C,this.h.faceLandmarks),Tt(this,D)}),this.g.attachEmptyPacketListener("face_landmarks",C=>{Tt(this,C)}),this.outputFaceBlendshapes&&($n(u,"extra_blendshapes"),dn(I,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(C,D)=>{var W=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(C=Wi(C),W.push(ld(C.g()??[]))),Tt(this,D)}),this.g.attachEmptyPacketListener("extra_blendshapes",C=>{Tt(this,C)})),this.g.attachProtoListener("left_hand_landmarks",(C,D)=>{Nd(C,this.h.leftHandLandmarks),Tt(this,D)}),this.g.attachEmptyPacketListener("left_hand_landmarks",C=>{Tt(this,C)}),this.g.attachProtoListener("left_hand_world_landmarks",(C,D)=>{var W=this.h.leftHandWorldLandmarks;C=Bo(C),W.push(Eu(C)),Tt(this,D)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",C=>{Tt(this,C)}),this.g.attachProtoListener("right_hand_landmarks",(C,D)=>{Nd(C,this.h.rightHandLandmarks),Tt(this,D)}),this.g.attachEmptyPacketListener("right_hand_landmarks",C=>{Tt(this,C)}),this.g.attachProtoListener("right_hand_world_landmarks",(C,D)=>{var W=this.h.rightHandWorldLandmarks;C=Bo(C),W.push(Eu(C)),Tt(this,D)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",C=>{Tt(this,C)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};ir.prototype.detectForVideo=ir.prototype.F,ir.prototype.detect=ir.prototype.D,ir.prototype.setOptions=ir.prototype.o,ir.createFromModelPath=function(u,f){return ot(ir,u,{baseOptions:{modelAssetPath:f}})},ir.createFromModelBuffer=function(u,f){return ot(ir,u,{baseOptions:{modelAssetBuffer:f}})},ir.createFromOptions=function(u,f){return ot(ir,u,f)},ir.HAND_CONNECTIONS=sh,ir.POSE_CONNECTIONS=Tm,ir.FACE_LANDMARKS_LIPS=nh,ir.FACE_LANDMARKS_LEFT_EYE=Ul,ir.FACE_LANDMARKS_LEFT_EYEBROW=rh,ir.FACE_LANDMARKS_LEFT_IRIS=bd,ir.FACE_LANDMARKS_RIGHT_EYE=Lp,ir.FACE_LANDMARKS_RIGHT_EYEBROW=xd,ir.FACE_LANDMARKS_RIGHT_IRIS=Go,ir.FACE_LANDMARKS_FACE_OVAL=zp,ir.FACE_LANDMARKS_CONTOURS=Sm,ir.FACE_LANDMARKS_TESSELATION=Pp;var Yt=class extends Gt{constructor(u,f){super(new Ar(u,f),"input_image","norm_rect",!0),this.j={classifications:[]},Ht(u=this.h=new fm,0,1,f=new cr)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return Ht(this.h,0,2,ud(u,xn(this.h,qc,2))),this.l(u)}ua(u,f){return this.j={classifications:[]},An(this,u,f),this.j}va(u,f,x){return this.j={classifications:[]},ys(this,u,x,f),this.j}m(){var u=new jr;sr(u,"input_image"),sr(u,"norm_rect"),$n(u,"classifications");const f=new Ps;zs(f,Tp,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Kn(x,"IMAGE:input_image"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"CLASSIFICATIONS:classifications"),x.o(f),sa(u,x),this.g.attachProtoListener("classifications",(I,C)=>{this.j=function(D){const W={classifications:ea(D,rm,1).map(fe=>ld(xn(fe,kr,4)?.g()??[],ps(ns(fe,2),0),Ls(fe,3)))};return Xu(Fa(D,2))!=null&&(W.timestampMs=ps(Xu(Fa(D,2)),0)),W}(sm(I)),Tt(this,C)}),this.g.attachEmptyPacketListener("classifications",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Yt.prototype.classifyForVideo=Yt.prototype.va,Yt.prototype.classify=Yt.prototype.ua,Yt.prototype.setOptions=Yt.prototype.o,Yt.createFromModelPath=function(u,f){return ot(Yt,u,{baseOptions:{modelAssetPath:f}})},Yt.createFromModelBuffer=function(u,f){return ot(Yt,u,{baseOptions:{modelAssetBuffer:f}})},Yt.createFromOptions=function(u,f){return ot(Yt,u,f)};var Ur=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!0),this.h=new ad,this.embeddings={embeddings:[]},Ht(u=this.h,0,1,f=new cr)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){var f=this.h,x=xn(this.h,Tu,2);return x=x?x.clone():new Tu,u.l2Normalize!==void 0?$i(x,1,u.l2Normalize):"l2Normalize"in u&&On(x,1
48),u.quantize!==void 0?$i(x,2,u.quantize):"quantize"in u&&On(x,2),Ht(f,0,2,x),this.l(u)}Ba(u,f){return An(this,u,f),this.embeddings}Ca(u,f,x){return ys(this,u,x,f),this.embeddings}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"embeddings_out");const f=new Ps;zs(f,Ay,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"EMBEDDINGS:embeddings_out"),x.o(f),sa(u,x),this.g.attachProtoListener("embeddings_out",(I,C)=>{I=im(I),this.embeddings=function(D){return{embeddings:ea(D,td,1).map(W=>{const fe={headIndex:ps(ns(W,3),0)??-1,headName:Ls(W,4)??""};if(hl(W,ar,ll(W,1))!==void 0)W=Qa(W=xn(W,ar,ll(W,1)),1,Fs,fa()),fe.floatEmbedding=W.slice();else{const re=new Uint8Array(0);fe.quantizedEmbedding=xn(W,am,ll(W,2))?.qa()?.h()??re}return fe}),timestampMs:ps(Xu(Fa(D,2)),0)}}(I),Tt(this,C)}),this.g.attachEmptyPacketListener("embeddings_out",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Ur.cosineSimilarity=function(u,f){if(u.floatEmbedding&&f.floatEmbedding)u=Ml(u.floatEmbedding,f.floatEmbedding);else{if(!u.quantizedEmbedding||!f.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");u=Ml(cd(u.quantizedEmbedding),cd(f.quantizedEmbedding))}return u},Ur.prototype.embedForVideo=Ur.prototype.Ca,Ur.prototype.embed=Ur.prototype.Ba,Ur.prototype.setOptions=Ur.prototype.o,Ur.createFromModelPath=function(u,f){return ot(Ur,u,{baseOptions:{modelAssetPath:f}})},Ur.createFromModelBuffer=function(u,f){return ot(Ur,u,{baseOptions:{modelAssetBuffer:f}})},Ur.createFromOptions=function(u,f){return ot(Ur,u,f)};var Ho=class{constructor(u,f,x){this.confidenceMasks=u,this.categoryMask=f,this.qualityScores=x}close(){this.confidenceMasks?.forEach(u=>{u.close()}),this.categoryMask?.close()}};function Vn(u){u.categoryMask=void 0,u.confidenceMasks=void 0,u.qualityScores=void 0}function Au(u){try{const f=new Ho(u.confidenceMasks,u.categoryMask,u.qualityScores);if(!u.j)return f;u.j(f)}finally{pd(u)}}Ho.prototype.close=Ho.prototype.close;var Qt=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!1),this.s=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Ep,this.v=new ji,Ht(this.h,0,3,this.v),Ht(u=this.h,0,1,f=new cr)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return u.displayNamesLocale!==void 0?On(this.h,2,Da(u.displayNamesLocale)):"displayNamesLocale"in u&&On(this.h,2),"outputCategoryMask"in u&&(this.outputCategoryMask=u.outputCategoryMask??!1),"outputConfidenceMasks"in u&&(this.outputConfidenceMasks=u.outputConfidenceMasks??!0),super.l(u)}J(){(function(u){const f=ea(u.ea(),gr,1).filter(x=>Ls(x,1).includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(u.s=[],f.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");f.length===1&&(xn(f[0],Ps,7)?.l()?.g()??new Map).forEach((x,I)=>{u.s[Number(I)]=Ls(x,1)})})(this)}fa(u,f,x){const I=typeof f!="function"?f:{};return this.j=typeof f=="function"?f:x,Vn(this),An(this,u,I),Au(this)}Na(u,f,x,I){const C=typeof x!="function"?x:{};return this.j=typeof x=="function"?x:I,Vn(this),ys(this,u,C,f),Au(this)}Fa(){return this.s}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect");const f=new Ps;zs(f,Cp,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),x.o(f),sa(u,x),Qc(this,u),this.outputConfidenceMasks&&($n(u,"confidence_masks"),dn(x,"CONFIDENCE_MASKS:confidence_masks"),Ol(this,"confidence_masks"),this.g.da("confidence_masks",(I,C)=>{this.confidenceMasks=I.map(D=>er(this,D,!0,!this.j)),Tt(this,C)}),this.g.attachEmptyPacketListener("confidence_masks",I=>{this.confidenceMasks=[],Tt(this,I)})),this.outputCategoryMask&&($n(u,"category_mask"),dn(x,"CATEGORY_MASK:category_mask"),Ol(this,"category_mask"),this.g.V("category_mask",(I,C)=>{this.categoryMask=er(this,I,!1,!this.j),Tt(this,C)}),this.g.attachEmptyPacketListener("category_mask",I=>{this.categoryMask=void 0,Tt(this,I)})),$n(u,"quality_scores"),dn(x,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(I,C)=>
48{this.qualityScores=I,Tt(this,C)}),this.g.attachEmptyPacketListener("quality_scores",I=>{this.categoryMask=void 0,Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Qt.prototype.getLabels=Qt.prototype.Fa,Qt.prototype.segmentForVideo=Qt.prototype.Na,Qt.prototype.segment=Qt.prototype.fa,Qt.prototype.setOptions=Qt.prototype.o,Qt.createFromModelPath=function(u,f){return ot(Qt,u,{baseOptions:{modelAssetPath:f}})},Qt.createFromModelBuffer=function(u,f){return ot(Qt,u,{baseOptions:{modelAssetBuffer:f}})},Qt.createFromOptions=function(u,f){return ot(Qt,u,f)};var Id=class{constructor(u,f,x){this.confidenceMasks=u,this.categoryMask=f,this.qualityScores=x}close(){this.confidenceMasks?.forEach(u=>{u.close()}),this.categoryMask?.close()}};Id.prototype.close=Id.prototype.close;var Up=class extends Mt{constructor(u){super(u)}},Na=[0,Jn,-2],ih=[0,na,-3,In,na,-1],Wp=[0,ih],Cm=[0,ih,Jn,-1],Sd=class extends Mt{constructor(u){super(u)}},$m=[0,na,-1,In],Dy=class extends Mt{constructor(){super()}},Gp=class extends Mt{constructor(u){super(u)}},Wl=[1,2,3,4,5,6,7,8,9,10,14,15],Td=class extends Mt{constructor(){super()}};Td.prototype.g=Gc([0,$r,[0,Wl,_n,ih,_n,[0,ih,Na],_n,Wp,_n,[0,Wp,Na],_n,$m,_n,[0,na,-3,In,za],_n,[0,na,-3,In],_n,[0,En,na,-2,In,Jn,In,-1,2,na,Na],_n,Cm,_n,[0,Cm,Na],na,Na,En,_n,[0,na,-3,In,Na,-1],_n,[0,$r,$m]],En,[0,En,Jn,-1,In]]);var Vs=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Ep,this.s=new ji,Ht(this.h,0,3,this.s),Ht(u=this.h,0,1,f=new cr)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return"outputCategoryMask"in u&&(this.outputCategoryMask=u.outputCategoryMask??!1),"outputConfidenceMasks"in u&&(this.outputConfidenceMasks=u.outputConfidenceMasks??!0),super.l(u)}fa(u,f,x,I){const C=typeof x!="function"?x:{};this.j=typeof x=="function"?x:I,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,x=this.B+1,I=new Td;const D=new Gp;var W=new Up;if(ta(W,1,255),Ht(D,0,12,W),f.keypoint&&f.scribble)throw Error("Cannot provide both keypoint and scribble.");if(f.keypoint){var fe=new Sd;$i(fe,3,!0),Ft(fe,1,f.keypoint.x),Ft(fe,2,f.keypoint.y),Ja(D,5,Wl,fe)}else{if(!f.scribble)throw Error("Must provide either a keypoint or a scribble.");
vendor: 8,932 bytes, line 48
48for(fe of(W=new Dy,f.scribble))$i(f=new Sd,3,!0),Ft(f,1,fe.x),Ft(f,2,fe.y),Ci(W,1,Sd,f);Ja(D,15,Wl,W)}Ci(I,1,Gp,D),this.g.addProtoToStream(I.g(),"drishti.RenderData","roi_in",x),An(this,u,C);e:{try{const ut=new Id(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var re=ut;break e}this.j(ut)}finally{pd(this)}re=void 0}return re}m(){var u=new jr;sr(u,"image_in"),sr(u,"roi_in"),sr(u,"norm_rect_in");const f=new Ps;zs(f,Cp,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"ROI:roi_in"),Kn(x,"NORM_RECT:norm_rect_in"),x.o(f),sa(u,x),Qc(this,u),this.outputConfidenceMasks&&($n(u,"confidence_masks"),dn(x,"CONFIDENCE_MASKS:confidence_masks"),Ol(this,"confidence_masks"),this.g.da("confidence_masks",(I,C)=>{this.confidenceMasks=I.map(D=>er(this,D,!0,!this.j)),Tt(this,C)}),this.g.attachEmptyPacketListener("confidence_masks",I=>{this.confidenceMasks=[],Tt(this,I)})),this.outputCategoryMask&&($n(u,"category_mask"),dn(x,"CATEGORY_MASK:category_mask"),Ol(this,"category_mask"),this.g.V("category_mask",(I,C)=>{this.categoryMask=er(this,I,!1,!this.j),Tt(this,C)}),this.g.attachEmptyPacketListener("category_mask",I=>{this.categoryMask=void 0,Tt(this,I)})),$n(u,"quality_scores"),dn(x,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(I,C)=>{this.qualityScores=I,Tt(this,C)}),this.g.attachEmptyPacketListener("quality_scores",I=>{this.categoryMask=void 0,Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Vs.prototype.segment=Vs.prototype.fa,Vs.prototype.setOptions=Vs.prototype.o,Vs.createFromModelPath=function(u,f){return ot(Vs,u,{baseOptions:{modelAssetPath:f}})},Vs.createFromModelBuffer=function(u,f){return ot(Vs,u,{baseOptions:{modelAssetBuffer:f}})},Vs.createFromOptions=function(u,f){return ot(Vs,u,f)};var Dr=class extends Gt{constructor(u,f){super(new Ar(u,f),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Ht(u=this.h=new $p,0,1,f=new cr)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return u.displayNamesLocale!==void 0?On(this.h,2,Da(u.displayNamesLocale)):"displayNamesLocale"in u&&On(this.h,2),u.maxResults!==void 0?ta(this.h,3,u.maxResults):"maxResults"in u&&On(this.h,3),u.scoreThreshold!==void 0?Ft(this.h,4,u.scoreThreshold):"scoreThreshold"in u&&On(this.h,4),u.categoryAllowlist!==void 0?Ai(this.h,5,u.categoryAllowlist):"categoryAllowlist"in u&&On(this.h,5),u.categoryDenylist!==void 0?Ai(this.h,6,u.categoryDenylist):"categoryDenylist"in u&&On(this.h,6),this.l(u)}D(u,f){return this.j={detections:[]},An(this,u,f),this.j}F(u,f,x){return this.j={detections:[]},ys(this,u,x,f),this.j}m(){var u=new jr;sr(u,"input_frame_gpu"),sr(u,"norm_rect"),$n(u,"detections");const f=new Ps;zs(f,mm,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.ObjectDetectorGraph"),Kn(x,"IMAGE:input_frame_gpu"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"DETECTIONS:detections"),x.o(f),sa(u,x),this.g.attachProtoVectorListener("detections",(I,C)=>{for(const D of I)I=Qh(D),this.j.detections.push(Rp(I));Tt(this,C)}),this.g.attachEmptyPacketListener("detections",I=>{Tt(this,I)}),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Dr.prototype.detectForVideo=Dr.prototype.F,Dr.prototype.detect=Dr.prototype.D,Dr.prototype.setOptions=Dr.prototype.o,Dr.createFromModelPath=async function(u,f){return ot(Dr,u,{baseOptions:{modelAssetPath:f}})},Dr.createFromModelBuffer=function(u,f){return ot(Dr,u,{baseOptions:{modelAssetBuffer:f}})},Dr.createFromOptions=function(u,f){return ot(Dr,u,f)};var oh=class{constructor(u,f,x){this.landmarks=u,this.worldLandmarks=f,this.segmentationMasks=x}close(){this.segmentationMasks?.forEach(u=>{u.close()})}};function Am(u){u.landmarks=[],u.worldLandmarks=[],u.segmentationMasks=void 0}function Ed(u){try{const f=new oh(u.landmarks,u.worldLandmarks,u.segmentationMasks);if(!u.s)return f;u.s(f)}finally{pd(u)}}oh.prototype.close=oh.prototype.close;var Us=class extends Gt{constructor(u,f){super(new Ar(u,f),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Ht(u=this.h=new gm,0,1,f=new cr),this.v=new pm,Ht(this.h,0,3,this.v),this.j=new dm,Ht(this.h,0,2,this.j),ta(this.j,4,1),Ft(this.j,2,.5),Ft(this.v,2,.5),Ft(this.h,4,.5)}get baseOptions(){return xn(this.h,cr,1)}set baseOptions(u){Ht(this.h,0,1,u)}o(u){return"numPoses"in u&&ta(this.j,4,u.numPoses??1),"minPoseDetectionConfidence"in u&&Ft(this.j,2,u.minPoseDetectionConfidence??.5),"minTrackingConfidence"in u&&Ft(this.h,4,u.minTrackingConfidence??.5),"minPosePresenceConfidence"in u&&Ft(this.v,2,u.minPosePresenceConfidence??.5),"outputSegmentationMasks"in u&&(this.outputSegmentationMasks=u.outputSegmentationMasks??!1),this.l(u)}D(u,f,x){const I=typeof f!="function"?f:{};return this.s=typeof f=="function"?f:x,Am(this),An(this,u,I),Ed(this)}F(u,f,x,I){const C=typeof x!="function"?x:{};return this.s=typeof x=="function"?x:I,Am(this),ys(this,u,C,f),Ed(this)}m(){var u=new jr;sr(u,"image_in"),sr(u,"norm_rect"),$n(u,"normalized_landmarks"),$n(u,"world_landmarks"),$n(u,"segmentation_masks");const f=new Ps;zs(f,Ap,this.h);const x=new gr;Fn(x,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Kn(x,"IMAGE:image_in"),Kn(x,"NORM_RECT:norm_rect"),dn(x,"NORM_LANDMARKS:normalized_landmarks"),dn(x,"WORLD_LANDMARKS:world_landmarks"),x.o(f),sa(u,x),Qc(this,u),this.g.attachProtoVectorListener("normalized_landmarks",(I,C)=>{this.landmarks=[];for(const D of I)I=Su(D),this.landmarks.push(Yc(I));Tt(this,C)}),this.g.attachEmptyPacketListener("normalized_landmarks",I=>{this.landmarks=[],Tt(this,I)}),this.g.attachProtoVectorListener("world_landmarks",(I,C)=>{this.worldLandmarks=[];for(const D of I)I=Bo(D),this.worldLandmarks.push(Eu(I));Tt(this,C)}),this.g.attachEmptyPacketListener("world_landmarks",I=>{this.worldLandmarks=[],Tt(this,I)}),this.outputSegmentationMasks&&(dn(x,"SEGMENTATION_MASK:segmentation_masks"),Ol(this,"segmentation_masks"),this.g.da("segmentation_masks",(I,C)=>{this.segmentationMasks=I.map(D=>er(this,D,!0,!this.s)),Tt(this,C)}),this.g.attachEmptyPacketListener("segmentation_masks",I=>{this.segmentationMasks=[],Tt(this,I)})),u=u.g(),this.setGraph(new Uint8Array(u),!0)}};Us.prototype.detectForVideo=Us.prototype.F,Us.prototype.detect=Us.prototype.D,Us.prototype.setOptions=Us.prototype.o,Us.createFromModelPath=function(u,f){return ot(Us,u,{baseOptions:{modelAssetPath:f}})},Us.createFromModelBuffer=function(u,f){return ot(Us,u,{baseOptions:{modelAssetBuffer:f}})},Us.createFromOptions=function(u,f){return ot(Us,u,f)},Us.POSE_CONNECTIONS=Tm,ye.DrawingUtils=gs,ye.FaceDetector=Nr,ye.FaceLandmarker=dr,ye.FaceStylizer=ka,ye.FilesetResolver=Vo,ye.GestureRecognizer=As,ye.HandLandmarker=Rs,ye.HolisticLandmarker=ir,ye.ImageClassifier=Yt,ye.ImageEmbedder=Ur,ye.ImageSegmenter=Qt,ye.ImageSegmenterResult=Ho,ye.InteractiveSegmenter=Vs,ye.InteractiveSegmenterResult=Id,ye.MPImage=Vr,ye.MPMask=Ue,ye.ObjectDetector=Dr,ye.PoseLandmarker=Us,ye.VisionTaskRunner=Gt},951:(Et,ye,Z)=>{Z.r(ye),Z.d(ye,{Abs:()=>Yu,Acos:()=>Da,Acosh:()=>Js,AdadeltaOptimizer:()=>aa,AdagradOptimizer:()=>gd,AdamOptimizer:()=>yd,AdamaxOptimizer:()=>nh,Add:()=>bi,AddN:()=>yc,All:()=>bc,Any:()=>xi,ArgMax:()=>Zu,ArgMin:()=>wi,Asin:()=>pa,Asinh:()=>go,Atan:()=>Za,Atan2:()=>Jo,Atanh:()=>vi,AvgPool:()=>xc,AvgPool3D:()=>Qu,AvgPool3DGrad:()=>Ju,AvgPoolGrad:()=>wc,BatchMatMul:()=>yo,BatchToSpaceND:()=>el,Bincount:()=>eu,BitwiseAnd:()=>ki,BroadcastArgs:()=>vc,BroadcastTo:()=>Ni,Callback:()=>fk,CallbackList:()=>iv,Cast:()=>tl,Ceil:()=>nl,ClipByValue:()=>bo,Complex:()=>Wh,ComplexAbs:()=>rl,Concat:()=>tu,Conv2D:()=>ds,Conv2DBackpropFilter:()=>Gh,Conv2DBackpropInput:()=>sl,Conv3D:()=>kc,Conv3DBackpropFilterV2:()=>Hh,Conv3DBackpropInputV2:()=>Nc,Cos:()=>xo,Cosh:()=>Ii,CropAndResize:()=>al,Cumprod:()=>jh,Cumsum:()=>nu,CustomCallback:()=>uv,DataStorage:()=>k,DenseBincount:()=>il,DepthToSpace:()=>Ic,DepthwiseConv2dNative:()=>wo,DepthwiseConv2dNativeBackpropFilter:()=>Sc,DepthwiseConv2dNativeBackpropInput:()=>Fa,Diag:()=>Tc,Dilation2D:()=>Ms,Dilation2DBackpropFilter:()=>jn,Dilation2DBackpropInput:()=>On,Draw:()=>Si,ENV:()=>gc,EarlyStopping:()=>mk,Einsum:()=>Ec,Elu:()=>fa,EluGrad:()=>Qa,Environment:()=>mc,Equal:()=>ol,Erf:()=>ru,Exp:()=>Os,ExpandDims:()=>ul,Expm1:()=>vo,FFT:()=>ll,Fill:()=>cl,FlipLeftRight:()=>Cc,Floor:()=>ko,FloorDiv:()=>No,FromPixels:()=>_l,FusedBatchNorm:()=>hl,FusedConv2D:()=>Lo,FusedDepthwiseConv2D:()=>ni,GPGPUContext:()=>fy,GatherNd:()=>$c,GatherV2:()=>xn,GraphModel:()=>ux,Greater:()=>ea,GreaterEqual:()=>Ht,History:()=>ov,IFFT:()=>ei,Identity:()=>Ja,Imag:()=>Ei,InputSpec:()=>Gr,IsFinite:()=>Ci,IsInf:()=>ps,IsNan:()=>ns,KernelBackend:()=>E,LRN:()=>au,LRNGrad:()=>Ma,LayerVariable:()=>Q2,LayersModel:()=>Wu,LeakyRelu:()=>rr,Less:()=>Ls,LessEqual:()=>$i,LinSpace:()=>ta,Log:()=>Ft,Log1p:()=>Ai,LogSoftmax:()=>Kh,LogicalAnd:()=>Io,LogicalNot:()=>dl,LogicalOr:()=>su,LogicalXor:()=>Jf,LowerBound:()=>
48pp,MathBackendCPU:()=>Ff,MathBackendWebGL:()=>Hf,MatrixBandPart:()=>So,Max:()=>iu,MaxPool:()=>Ac,MaxPool3D:()=>Oa,MaxPool3DGrad:()=>Rc,MaxPoolGrad:()=>pl,MaxPoolWithArgmax:()=>_c,Maximum:()=>To,Mean:()=>fl,Min:()=>ml,Minimum:()=>Ri,MirrorPad:()=>_i,Mod:()=>Eo,MomentumOptimizer:()=>rh,Multinomial:()=>Dc,Multiply:()=>Di,Neg:()=>Co,NonMaxSuppressionV3:()=>zs,NonMaxSuppressionV4:()=>Mt,NonMaxSuppressionV5:()=>Fc,NotEqual:()=>$o,OP_SCOPE_SUFFIX:()=>Xc,OneHot:()=>ou,OnesLike:()=>gl,Optimizer:()=>oi,OptimizerConstructors:()=>Jx,Pack:()=>Mc,PadV2:()=>yl,Pool:()=>fp,Pow:()=>bl,Prelu:()=>ti,Prod:()=>Fi,RMSPropOptimizer:()=>bd,RNN:()=>co,RaggedGather:()=>uu,RaggedRange:()=>Ao,RaggedTensorToTensor:()=>Mi,Range:()=>Ts,Rank:()=>Qh,Real:()=>xl,RealDiv:()=>Ti,Reciprocal:()=>Ro,Reduction:()=>js,Relu:()=>Oi,Relu6:()=>Do,Reshape:()=>_o,ResizeBilinear:()=>vl,ResizeBilinearGrad:()=>kl,ResizeNearestNeighbor:()=>Es,ResizeNearestNeighborGrad:()=>wl,Reverse:()=>Nl,RotateWithOffset:()=>Xh,Round:()=>Fo,Rsqrt:()=>lu,SGDOptimizer:()=>Ul,ScatterNd:()=>Oc,SearchSorted:()=>cu,Select:()=>Il,Selu:()=>Sl,Sequential:()=>Nh,Sigmoid:()=>du,Sign:()=>hu,Sin:()=>zi,Sinh:()=>Mo,Slice:()=>Lc,Softmax:()=>mu,Softplus:()=>pu,SpaceToBatchND:()=>Tl,SparseFillEmptyRows:()=>Cl,SparseReshape:()=>$l,SparseSegmentMean:()=>qh,SparseSegmentSum:()=>gu,SparseToDense:()=>yu,SplitV:()=>El,Sqrt:()=>fu,Square:()=>zc,SquaredDifference:()=>bu,StaticRegexReplace:()=>Al,Step:()=>ra,StridedSlice:()=>Pi,StringNGrams:()=>rs,StringSplit:()=>Bi,StringToHashBucketFast:()=>ss,Sub:()=>Rl,Sum:()=>La,SymbolicTensor:()=>ao,Tan:()=>xu,Tanh:()=>wu,Tensor:()=>Sn,TensorBuffer:()=>kr,TensorScatterUpdate:()=>Li,Tile:()=>vu,TopK:()=>Pc,Transform:()=>Bc,Transpose:()=>Oo,Unique:()=>Vc,Unpack:()=>na,UnsortedSegmentSum:()=>mr,UpperBound:()=>Sy,Variable:()=>Iu,ZerosLike:()=>ku,_FusedMatMul:()=>Jn,abs:()=>An,acos:()=>My,acosh:()=>Oy,add:()=>Ue,addN:()=>ew,all:()=>Rm,any:()=>Hp,argMax:()=>uh,argMin:()=>Ly,asin:()=>zy,asinh:()=>Py,atan:()=>By,atan2:()=>Vy,atanh:()=>Uy,avgPool:()=>Xp,avgPool3d:()=>Hy,backend:()=>ad,backend_util:()=>de,basicLSTMCell:()=>tw,batchNorm:()=>Ad,batchNorm2d:()=>jy,batchNorm3d:()=>Ky,batchNorm4d:()=>qy,batchToSpaceND:()=>Yp,bincount:()=>Xy,bitwiseAnd:()=>nw,booleanMaskAsync:()=>zw,broadcastArgs:()=>rw,broadcastTo:()=>ch,broadcast_util:()=>ct,browser:()=>K,buffer:()=>ln,callbacks:()=>L$,cast:()=>gt,ceil:()=>Yy,clipByValue:()=>ia,clone:()=>va,complex:()=>Gi,concat:()=>Fr,concat1d:()=>Zy,concat2d:()=>Qy,concat3d:()=>Jy,concat4d:()=>e0,constraints:()=>tt,conv1d:()=>_m,conv2d:()=>Fu,conv2dTranspose:()=>Dm,conv3d:()=>n0,conv3dTranspose:()=>r0,copyRegisteredKernels:()=>Pa,cos:()=>Zp,cosh:()=>Fm,cosineWindow:()=>tg,cumprod:()=>Qp,cumsum:()=>Mm,customGrad:()=>Br,data:()=>Kt,denseBincount:()=>s0,deprecationWarn:()=>vp,depthToSpace:()=>a0,depthwiseConv2d:()=>Rd,deregisterOp:()=>P$,device_util:()=>ht,diag:()=>aw,dilation2d:()=>i0,disableDeprecationWarnings:()=>wp,dispose:()=>on,disposeVariables:()=>hm,div:()=>Lt,divNoNan:()=>o0,dot:()=>u0,dropout:()=>_0,einsum:()=>hh,elu:()=>_d,enableDebugMode:()=>cm,enableProdMode:()=>Cy,enclosingPowerOfTwo:()=>D0,engine:()=>wa,ensureShape:()=>iw,env:()=>xe,equal:()=>Ia,erf:()=>Om,euclideanNorm:()=>c0,exp:()=>oa,expandDims:()=>ws,expm1:()=>h0,eye:()=>Lm,fft:()=>hf,fill:()=>$u,findBackend:()=>Sp,findBackendFactory:()=>fm,floor:()=>Md,floorDiv:()=>Jc,forceHalfFloat:()=>pS,fused:()=>Qe,gather:()=>Od,gatherND:()=>Uw,gather_util:()=>H,getBackend:()=>Np,getGradient:()=>$r,getKernel:()=>En,getKernelsForBackend:()=>_n,gpgpu_util:()=>b,grad:()=>eh,grads:()=>km,greater:()=>Gs,greaterEqual:()=>Mu,ifft:()=>Bd,imag:()=>Ho,image:()=>hi,inTopKAsync:()=>Ww,initializers:()=>Ee,input:()=>Cv,io:()=>Te,irfft:()=>Ym,isFinite:()=>d0,isInf:()=>p0,isNaN:()=>f0,keep:()=>_r,kernel_impls:()=>Fe,layers:()=>Re,leakyRelu:()=>Jp,less:()=>Ld,lessEqual:()=>ql,linalg:()=>L0,linspace:()=>lw,loadGraphModel:()=>gA,loadGraphModelSync:()=>yA,loadLayersModel:()=>YE,localResponseNormalization:()=>m0,log:()=>Sa,log1p:()=>ef,logSigmoid:()=>g0,logSoftmax:()=>zm,logSumExp:()=>tf,logicalAnd:()=>ci,logicalNot:()=>nf,logicalOr:()=>Pm,logicalXor:()=>y0,losses:()=>t2,lowerBound:()=>hw,matMul:()=>Yt,math:()=>ke,max:()=>Va,maxPool:()=>rf,maxPool3d:()=>b0,maxPoolWithArgmax:()=>dw,maximum:()=>Nr,mean:()=>Sr,memory:()=>sd,meshgrid:()=>pw,metrics:()=>pt,min:()=>Dd,minimum:()=>Xl,mirrorPad:()=>x0,mod:()=>w0,model:()=>ZE,models:()=>Ne,moments:()=>sf,movingAverage:()=>Pw,mul:()=>se,multiRNNCell:()=>fw,multinomial:()=>mw,neg:()=>Vn,nextFrame:()=>z0,norm:()=>Fd,notEqual:()=>ph,oneHot:()=>Ur,ones:()=>ua,onesLike:()=>Ta,op:()=>ee,outerProduct:()=>gw,pad:()=>Ou,pad1d:()=>yw,pad2d:()=>bw,pad3d:()=>xw,pad4d:()=>ww,pool:()=>v0,pow:()=>Ar,prelu:()=>
48of,print:()=>Pl,prod:()=>k0,profile:()=>kp,raggedGather:()=>vw,raggedRange:()=>kw,raggedTensorToTensor:()=>Nw,rand:()=>Iw,randomGamma:()=>Sw,randomNormal:()=>Vm,randomStandardNormal:()=>Tw,randomUniform:()=>Yl,randomUniformInt:()=>Ew,range:()=>fh,ready:()=>pm,real:()=>Au,reciprocal:()=>I0,registerBackend:()=>Tp,registerCallbackConstructor:()=>JE,registerGradient:()=>em,registerKernel:()=>Wc,registerOp:()=>z$,regularizers:()=>Pe,relu:()=>to,relu6:()=>Um,removeBackend:()=>Ip,reshape:()=>he,reverse:()=>Wa,reverse1d:()=>Cw,reverse2d:()=>$w,reverse3d:()=>Aw,reverse4d:()=>Rw,rfft:()=>df,round:()=>Wm,rsqrt:()=>Gm,scalar:()=>Pt,scatterND:()=>Bw,scatter_util:()=>ie,searchSorted:()=>Bm,selu:()=>Hm,separableConv2d:()=>jm,sequential:()=>QE,serialization:()=>Nt,setBackend:()=>dm,setPlatform:()=>Ay,setWebGLContext:()=>cI,setdiff1dAsync:()=>_w,shared:()=>M,sigmoid:()=>eo,sign:()=>S0,signal:()=>e2,sin:()=>Km,sinh:()=>qm,slice:()=>Tn,slice1d:()=>uf,slice2d:()=>Xm,slice3d:()=>lf,slice4d:()=>Pd,slice_util:()=>pe,softmax:()=>cf,softplus:()=>dh,spaceToBatchND:()=>af,sparse:()=>n2,sparseToDense:()=>Vw,spectral:()=>Jw,split:()=>la,sqrt:()=>qn,square:()=>Mn,squaredDifference:()=>Zm,squeeze:()=>Zl,stack:()=>Hs,step:()=>mh,stridedSlice:()=>T0,string:()=>r2,sub:()=>ot,sum:()=>Dt,sumOutType:()=>Kc,tan:()=>E0,tanh:()=>jl,tensor:()=>Bs,tensor1d:()=>vs,tensor2d:()=>Ql,tensor3d:()=>Up,tensor4d:()=>Dw,tensor5d:()=>Fw,tensor6d:()=>Mw,tensorScatterUpdate:()=>Ow,tensor_util:()=>Vt,test_util:()=>Se,tidy:()=>be,tile:()=>Ua,time:()=>$y,topk:()=>C0,train:()=>gh,transpose:()=>Qt,truncatedNormal:()=>Qm,unique:()=>$0,unregisterGradient:()=>Ty,unregisterKernel:()=>za,unsortedSegmentSum:()=>Jm,unstack:()=>Ga,upcastType:()=>Cs,upperBound:()=>Lw,util:()=>Xe,valueAndGrad:()=>Nm,valueAndGrads:()=>Im,variable:()=>A0,variableGrads:()=>gs,version:()=>o6,version_converter:()=>Ck,version_core:()=>Qx,version_cpu:()=>jN,version_layers:()=>Lg,version_webgl:()=>dS,webgl:()=>BM,webgl_util:()=>S,where:()=>os,whereAsync:()=>R0,zeros:()=>Wr,zerosLike:()=>mn});var Xe={};Z.r(Xe),Z.d(Xe,{arraysEqual:()=>le,arraysEqualWithNull:()=>Y,assert:()=>A,assertNonNegativeIntegerDimensions:()=>ts,assertNonNull:()=>Ve,assertShapesMatch:()=>ge,bytesFromStringArray:()=>Zn,bytesPerElement:()=>fr,checkConversionForErrors:()=>hn,clamp:()=>te,computeStrides:()=>Ge,convertBackendValuesAndArrayBuffer:()=>Ph,createScalarValue:()=>Bn,createShuffledIndices:()=>en,decodeString:()=>gr,distSquared:()=>it,encodeString:()=>dn,fetch:()=>Kn,fingerPrint64:()=>Ps,flatten:()=>Ba,getArrayFromDType:()=>Zt,getTypedArrayFromDType:()=>_t,hasEncodingLoss:()=>ve,hexToLong:()=>Nu,indexToLoc:()=>Fs,inferDtype:()=>St,inferFromImplicitShape:()=>Le,isBoolean:()=>Hr,isFunction:()=>wt,isInt:()=>ue,isNumber:()=>ft,isPromise:()=>Ya,isScalarShape:()=>oe,isString:()=>Qn,isTypedArray:()=>lr,isValidDtype:()=>an,locToIndex:()=>Qs,makeOnesTypedArray:()=>Ku,makeZerosNestedTypedArray:()=>Bh,makeZerosTypedArray:()=>Er,nearestDivisor:()=>bt,nearestLargerEven:()=>Ce,now:()=>Fn,parseAxisParam:()=>Oe,randUniform:()=>et,repeatedTry:()=>q,rightPad:()=>jt,shuffle:()=>B,shuffleCombo:()=>Q,sizeFromShape:()=>j,sizeToSquarishShape:()=>Me,squeezeShape:()=>je,sum:()=>mt,swap:()=>Ae,tanh:()=>vt,toNestedArray:()=>Ss,toTypedArray:()=>Ui});var Vt={};Z.r(Vt),Z.d(Vt,{assertTypesMatch:()=>am,getTensorsInContainer:()=>si,isTensorInList:()=>td,makeTypesMatch:()=>ar});var ht={};Z.r(ht),Z.d(ht,{isBrowser:()=>yr,isMobile:()=>rd,mockIsMobile:()=>cr});var Nt={};Z.r(Nt),Z.d(Nt,{Serializable:()=>ii,SerializationMap:()=>as,getRegisteredName:()=>Vr,registerClass:()=>st});var ct={};Z.r(ct),Z.d(ct,{assertAndGetBroadcastShape:()=>Gt,getBroadcastDims:()=>ys,getReductionAxes:()=>er});var Te={};Z.r(Te),Z.d(Te,{CompositeArrayBuffer:()=>xa,browserFiles:()=>Sm,browserHTTPRequest:()=>As,concatenateArrayBuffers:()=>ld,copyModel:()=>Op,decodeWeights:()=>od,decodeWeightsStream:()=>mm,encodeWeights:()=>id,fromMemory:()=>Em,fromMemorySync:()=>ah,getLoadHandlers:()=>_p,getModelArtifactsForJSON:()=>cd,getModelArtifactsForJSONSync:()=>Eu,getModelArtifactsInfoForJSON:()=>Ml,getSaveHandlers:()=>Vo,getWeightSpecs:()=>Cu,http:()=>vd,isHTTPScheme:()=>wd,listModels:()=>_y,loadWeights:()=>dr,moveModel:()=>vm,registerLoadRouter:()=>Zc,registerSaveRouter:()=>ym,removeModel:()=>Zi,weightsLoaderFactory:()=>ka,withSaveHandler:()=>Nd,withSaveHandlerSync:()=>ir});var ke={};Z.r(ke),Z.d(ke,{confusionMatrix:()=>Id});var K={};Z.r(K),Z.d(K,{draw:()=>Dy,fromPixels:()=>Gp,fromPixelsAsync:()=>Cm,toPixels:()=>$m});var H={};Z.r(H),Z.d(H,{prepareAndValidate:()=>Wl});var ie={};Z.r(ie),Z.d(ie,{calculateShapes:()=>Dr,validateInput:()=>Vs,validateUpdateShape:()=>Td}
48);var pe={};Z.r(pe),Z.d(pe,{assertParamsValid:()=>Ed,computeFlatOffset:()=>un,computeOutShape:()=>u,getNormalizedAxes:()=>C,isSliceContinous:()=>qt,maskToAxes:()=>Us,parseSliceParams:()=>rn,sliceInfo:()=>pr,startForAxis:()=>re,startIndicesWithElidedDims:()=>D,stopForAxis:()=>ut,stopIndicesWithElidedDims:()=>W,stridesForAxis:()=>fe,stridesWithElidedDims:()=>f});var Se={};Z.r(Se),Z.d(Se,{TEST_EPSILON_FLOAT16:()=>Qi,createVideoElement:()=>dT,encodeStrings:()=>Zx,expectArrayBuffersEqual:()=>hT,expectArraysClose:()=>Ji,expectArraysEqual:()=>uT,expectNumbersClose:()=>lT,expectPromiseToFail:()=>Cd,expectValuesInRange:()=>cT,play:()=>pT,testEpsilon:()=>ui});var Qe={};Z.r(Qe),Z.d(Qe,{conv2d:()=>Gw,depthwiseConv2d:()=>gT,matMul:()=>M0});var Ke={};Z.r(Ke),Z.d(Ke,{collectGatherOpShapeInfo:()=>s1,computeOutShape:()=>E2,segOpComputeOptimalWindowSize:()=>T2});var de={};Z.r(de),Z.d(de,{ERF_A1:()=>H0,ERF_A2:()=>j0,ERF_A3:()=>K0,ERF_A4:()=>q0,ERF_A5:()=>X0,ERF_P:()=>G0,PARALLELIZE_THRESHOLD:()=>B0,RowPartitionType:()=>no,SELU_SCALE:()=>hg,SELU_SCALEALPHA:()=>cg,applyActivation:()=>sg,assertAndGetBroadcastShape:()=>Gt,assertAxesAreInnerMostDims:()=>xs,assertParamsConsistent:()=>P0,assignToTypedArray:()=>h2,axesAreInnerMostDims:()=>l0,calculateShapes:()=>Dr,checkEinsumDimSizes:()=>e1,checkPadOnDimRoundingMode:()=>Ws,combineLocations:()=>ow,combineRaggedTensorToTensorShapes:()=>s2,complexWithEvenIndex:()=>l2,complexWithOddIndex:()=>c2,computeConv2DInfo:()=>is,computeConv3DInfo:()=>Gl,computeDefaultPad:()=>Wy,computeDilation2DInfo:()=>jp,computeOptimalWindowSize:()=>lg,computeOutAndReduceShapes:()=>us,computeOutShape:()=>jo,computePool2DInfo:()=>li,computePool3DInfo:()=>_u,convertConv2DDataFormat:()=>Du,decodeEinsumEquation:()=>Q0,eitherStridesOrDilationsAreOne:()=>bs,expandShapeToKeepDim:()=>Mr,exponent:()=>p2,exponents:()=>d2,fromStringArrayToUint8:()=>C2,fromUint8ToStringArray:()=>Pu,getAxesPermutation:()=>Ir,getBroadcastDims:()=>ys,getComplexWithIndex:()=>Y0,getEinsumComputePath:()=>t1,getEinsumPermutation:()=>J0,getFusedBiasGradient:()=>rg,getFusedDyActivation:()=>ng,getImageCenter:()=>V0,getInnerMostAxes:()=>Or,getPermuted:()=>ff,getRaggedRank:()=>i2,getReductionAxes:()=>er,getReshaped:()=>pf,getReshapedPermuted:()=>mf,getRowPartitionTypesHelper:()=>a2,getSliceBeginCoords:()=>U0,getSliceSize:()=>W0,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>g2,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>y2,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>b2,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>t3,getSparseReshapeInputOutputMismatchErrorMessage:()=>k2,getSparseReshapeInputOutputMultipleErrorMessage:()=>v2,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>x2,getSparseReshapeNegativeOutputDimErrorMessage:()=>w2,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>S2,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>n3,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>N2,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>I2,getUndoAxesPermutation:()=>Kl,isIdentityPermutation:()=>n1,log:()=>Uc,mergeRealAndImagArrays:()=>zu,prepareAndValidate:()=>Wl,prepareSplitSize:()=>r1,segment_util:()=>Ke,shouldFuse:()=>ag,slice_util:()=>pe,splitRealAndImagArrays:()=>u2,stridesOrDilationsArePositive:()=>lh,tupleValuesAreOne:()=>Hl,upcastType:()=>Cs,validateDefaultValueShape:()=>o2,validateInput:()=>Vs,validateUpdateShape:()=>Td,warn:()=>In});var Fe={};Z.r(Fe),Z.d(Fe,{nonMaxSuppressionV3Impl:()=>ig,nonMaxSuppressionV4Impl:()=>og,nonMaxSuppressionV5Impl:()=>ug,whereImpl:()=>eg});var tt={};Z.r(tt),Z.d(tt,{maxNorm:()=>SE,minMaxNorm:()=>CE,nonNeg:()=>EE,unitNorm:()=>TE});var Ee={};Z.r(Ee),Z.d(Ee,{constant:()=>RE,glorotNormal:()=>zE,glorotUniform:()=>LE,heNormal:()=>PE,heUniform:()=>BE,identity:()=>ME,leCunNormal:()=>VE,leCunUniform:()=>UE,ones:()=>AE,orthogonal:()=>WE,randomNormal:()=>DE,randomUniform:()=>_E,truncatedNormal:()=>FE,varianceScaling:()=>OE,zeros:()=>$E});var Re={};Z.r(Re),Z.d(Re,{Layer:()=>bn,RNN:()=>co,RNNCell:()=>Cf,activation:()=>bC,add:()=>EC,alphaDropout:()=>c$,average:()=>CC,averagePooling1d:()=>Hb,averagePooling2d:()=>jb,averagePooling3d:()=>Kb,avgPool1d:()=>LC,avgPool2d:()=>PC,avgPool3d:()=>VC,avgPooling1d:()=>zC,avgPooling2d:()=>BC,avgPooling3d:()=>UC,batchNormalization:()=>FC,bidirectional:()=>n$,categoryEncoding:()=>m$,centerCrop:()=>p$,concatenate:()=>$C,conv1d:()=>lC,conv2d:()=>cC,conv2dTranspose:()=>hC,conv3d:()=>dC,conv3dTranspose:()=>pC,convLstm2d:()=>QC,convLstm2dCell:()=>JC,cropping2D:()=>mC,dense:()=>xC,depthwiseConv2d:()=>yC,dot:()=>DC,dropout:()=>wC,elu:()=>rC,embedding:()=>TC,flatten:()=>kC,gaussianDropout:()=>l$,gaussianNoise:()=>u$,globalAveragePooling1d:()=>WC,globalAveragePooling2d:()=>GC,globalMaxPool1d:()=>s$,globalMaxPool2d:()=>a$,globalMaxPooling1d:()=>ck,globalMaxPooling2d:()=>hk,gru:()=>jC,gruCell:()=>KC,input:()=>Cv,inputLayer:()=>nC,layerNormalization:()=>MC,leakyReLU:()=>aC,lstm:()=>qC,lstmCell:()=>XC,masking:()=>h$,maxPool1d:()=>i$,maxPool2d:()=>o$,maxPooling1d:()=>dk,maxPooling2d:()=>pk,maxPooling3d:()=>HC,maximum:()=>AC,minimum:()=>RC,multiply:()=>_C,permute:()=>SC,prelu:()=>iC,randomWidth:()=>g$,reLU:()=>sC,repeatVector:()=>NC,rescaling:()=>d$,reshape:()=>IC,resizing:()=>f$,rnn:()=>e$,separableConv2d:()=>fC,simpleRNN:()=>YC,simpleRNNCell:()=>ZC,softmax:()=>oC,spatialDropout1d:()=>vC,stackedRNNCells:()=>t$,thresholdedReLU:()=>uC,timeDistributed:()=>r$,upSampling2d:()=>gC,zeroPadding2d:()=>OC});var pt={};Z.r(pt),Z.d(pt,{MAPE:()=>E$,MSE:()=>A$,binaryAccuracy:()=>y$,binaryCrossentropy:()=>b$,categoricalAccuracy:()=>w$,categoricalCrossentropy:()=>v$,cosineProximity:()=>I$,mape:()=>C$,meanAbsoluteError:()=>S$,meanAbsolutePercentageError:()=>T$,meanSquaredError:()=>$$,mse:()=>R$,precision:()=>k$,r2Score:()=>_$,recall:()=>N$,sparseCategoricalAccuracy:()=>x$});var Ne={};Z.r(Ne),Z.d(Ne,{modelFromJSON:()=>XE});var Pe={};Z.r(Pe),Z.d(Pe,{l1:()=>F$,l1l2:()=>D$,l2:()=>M$});var G={};Z.r(G),Z.d(G,{json:()=>B$});var Be={};Z.r(Be),Z.d(Be,{json:()=>V$});var Ze={};Z.r(Ze),Z.d(Ze,{json:()=>U$});var $t={};Z.r($t),Z.d($t,{json:()=>W$});var Wt={};Z.r(Wt),Z.d(Wt,{json:()=>G$});var yn={};Z.r(yn),Z.d(yn,{json:()=>H$});var Jt={};Z.r(Jt),Z.d(Jt,{json:()=>j$});var fn={};Z.r(fn),Z.d(fn,{json:()=>K$});var cn={};Z.r(cn),Z.d(cn,{json:()=>q$});var Yn={};Z.r(Yn),Z.d(Yn,{json:()=>X$});var Dn={};Z.r(Dn),Z.d(Dn,{json:()=>Y$});var zn={};Z.r(zn),Z.d(zn,{json:()=>Z$});var De={};Z.r(De),Z.d(De,{json:()=>Q$});var Ye={};Z.r(Ye),Z.d(Ye,{json:()=>J$});var rt={};Z.r(rt),Z.d(rt,{json:()=>eA});var qe={};Z.r(qe),Z.d(qe,{json:()=>tA});var He={};Z.r(He),Z.d(He,{json:()=>nA});var At={};Z.r(At),Z.d(At,{json:()=>rA});var Ut={};Z.r(Ut),Z.d(Ut,{json:()=>sA});var at={};Z.r(at),Z.d(at,{OP_SCOPE_SUFFIX:()=>Xc,abs:()=>An,acos:()=>My,acosh:()=>Oy,add:()=>Ue,addN:()=>ew,all:()=>Rm,any:()=>Hp,argMax:()=>uh,argMin:()=>Ly,asin:()=>zy,asinh:()=>Py,atan:()=>By,atan2:()=>Vy,atanh:()=>Uy,avgPool:()=>Xp,avgPool3d:()=>Hy,basicLSTMCell:()=>tw,batchNorm:()=>Ad,batchNorm2d:()=>jy,batchNorm3d:()=>Ky,batchNorm4d:()=>qy,batchToSpaceND:()=>Yp,bincount:()=>Xy,bitwiseAnd:()=>nw,booleanMaskAsync:()=>zw,broadcastArgs:()=>rw,broadcastTo:()=>ch,buffer:()=>ln,cast:()=>gt,ceil:()=>Yy,clipByValue:()=>ia,clone:()=>va,complex:()=>Gi,concat:()=>Fr,concat1d:()=>Zy,concat2d:()=>Qy,concat3d:()=>Jy,concat4d:()=>e0,conv1d:()=>_m,conv2d:()=>Fu,conv2dTranspose:()=>Dm,conv3d:()=>n0,conv3dTranspose:()=>r0,cos:()=>Zp,cosh:()=>Fm,cosineWindow:()=>tg,cumprod:()=>Qp,cumsum:()=>Mm,denseBincount:()=>s0,depthToSpace:()=>a0,depthwiseConv2d:()=>Rd,diag:()=>aw,dilation2d:()=>i0,div:()=>Lt,divNoNan:()=>o0,dot:()=>u0,dropout:()=>_0,einsum:()=>hh,elu:()=>_d,enclosingPowerOfTwo:()=>D0,ensureShape:()=>iw,equal:()=>Ia,erf:()=>Om,euclideanNorm:()=>c0,exp:()=>oa,expandDims:()=>ws,expm1:()=>h0,eye:()=>Lm,fft:()=>hf,fill:()=>$u,floor:()=>Md,floorDiv:()=>Jc,fused:()=>Qe,gather:()=>Od,gatherND:()=>Uw,greater:()=>Gs,greaterEqual:()=>Mu,ifft:()=>Bd,imag:()=>Ho,image:()=>hi,inTopKAsync:()=>Ww,irfft:()=>Ym,isFinite:()=>d0,isInf:()=>p0,isNaN:()=>f0,leakyRelu:()=>Jp,less:()=>Ld,lessEqual:()=>ql,linalg:()=>L0,linspace:()=>lw,localResponseNormalization:()=>m0,log:()=>Sa,log1p:()=>ef,logSigmoid:()=>g0,logSoftmax:()=>zm,logSumExp:()=>tf,logicalAnd:()=>ci,logicalNot:()=>nf,logicalOr:()=>Pm,logicalXor:()=>y0,losses:()=>t2,lowerBound:()=>hw,matMul:()=>Yt,max:()=>Va,maxPool:()=>rf,maxPool3d:()=>b0,maxPoolWithArgmax:()=>dw,maximum:()=>Nr,mean:()=>Sr,meshgrid:()=>pw,min:()=>Dd,minimum:()=>Xl,mirrorPad:()=>x0,mod:()=>w0,moments:()=>sf,movingAverage:()=>Pw,mul:()=>se,multiRNNCell:()=>fw,multinomial:()=>mw,neg:()=>Vn,norm:()=>Fd,notEqual:()=>ph,oneHot:()=>Ur,ones:()=>ua,onesLike:()=>Ta,op:()=>ee,outerProduct:()=>gw,pad:()=>Ou,pad1d:()=>yw,pad2d:()=>bw,pad3d:()=>xw,pad4d:()=>ww,pool:()=>v0,pow:()=>Ar,prelu:()=>
48of,print:()=>Pl,prod:()=>k0,raggedGather:()=>vw,raggedRange:()=>kw,raggedTensorToTensor:()=>Nw,rand:()=>Iw,randomGamma:()=>Sw,randomNormal:()=>Vm,randomStandardNormal:()=>Tw,randomUniform:()=>Yl,randomUniformInt:()=>Ew,range:()=>fh,real:()=>Au,reciprocal:()=>I0,relu:()=>to,relu6:()=>Um,reshape:()=>he,reverse:()=>Wa,reverse1d:()=>Cw,reverse2d:()=>$w,reverse3d:()=>Aw,reverse4d:()=>Rw,rfft:()=>df,round:()=>Wm,rsqrt:()=>Gm,scalar:()=>Pt,scatterND:()=>Bw,searchSorted:()=>Bm,selu:()=>Hm,separableConv2d:()=>jm,setdiff1dAsync:()=>_w,sigmoid:()=>eo,sign:()=>S0,signal:()=>e2,sin:()=>Km,sinh:()=>qm,slice:()=>Tn,slice1d:()=>uf,slice2d:()=>Xm,slice3d:()=>lf,slice4d:()=>Pd,softmax:()=>cf,softplus:()=>dh,spaceToBatchND:()=>af,sparse:()=>n2,sparseToDense:()=>Vw,spectral:()=>Jw,split:()=>la,sqrt:()=>qn,square:()=>Mn,squaredDifference:()=>Zm,squeeze:()=>Zl,stack:()=>Hs,step:()=>mh,stridedSlice:()=>T0,string:()=>r2,sub:()=>ot,sum:()=>Dt,tan:()=>E0,tanh:()=>jl,tensor:()=>Bs,tensor1d:()=>vs,tensor2d:()=>Ql,tensor3d:()=>Up,tensor4d:()=>Dw,tensor5d:()=>Fw,tensor6d:()=>Mw,tensorScatterUpdate:()=>Ow,tile:()=>Ua,topk:()=>C0,transpose:()=>Qt,truncatedNormal:()=>Qm,unique:()=>$0,unsortedSegmentSum:()=>Jm,unstack:()=>Ga,upperBound:()=>Lw,variable:()=>A0,where:()=>os,whereAsync:()=>R0,zeros:()=>Wr,zerosLike:()=>mn});var Kt={};Z.r(Kt),Z.d(Kt,{CSVDataset:()=>Bk,Dataset:()=>Qd,FileDataSource:()=>Hk,TextLineDataset:()=>Lk,URLDataSource:()=>jk,array:()=>_A,csv:()=>BA,func:()=>VA,generator:()=>UA,microphone:()=>GA,version_data:()=>Kk,webcam:()=>WA,zip:()=>DA});var M={};Z.r(M),Z.d(M,{addImpl:()=>Yk,bincountImpl:()=>mx,bincountReduceImpl:()=>Zk,bitwiseAndImpl:()=>Qk,castImpl:()=>Xk,ceilImpl:()=>Jk,concatImpl:()=>eN,equalImpl:()=>tN,expImpl:()=>rN,expm1Impl:()=>aN,floorDivImpl:()=>oN,floorImpl:()=>iN,gatherNdImpl:()=>uN,gatherV2Impl:()=>lN,greaterEqualImpl:()=>hN,greaterImpl:()=>cN,lessEqualImpl:()=>pN,lessImpl:()=>dN,linSpaceImpl:()=>fN,logImpl:()=>mN,maxImpl:()=>gN,maximumImpl:()=>yN,minimumImpl:()=>bN,multiplyImpl:()=>gx,negImpl:()=>xN,notEqualImpl:()=>wN,prodImpl:()=>vN,raggedGatherImpl:()=>NN,raggedRangeImpl:()=>SN,raggedTensorToTensorImpl:()=>CN,rangeImpl:()=>$N,rsqrtImpl:()=>AN,scatterImpl:()=>ep,sigmoidImpl:()=>F4,simpleAbsImpl:()=>qk,sliceImpl:()=>_N,sparseFillEmptyRowsImpl:()=>DN,sparseReshapeImpl:()=>FN,sparseSegmentReductionImpl:()=>bx,sqrtImpl:()=>L4,squaredDifferenceImpl:()=>MN,staticRegexReplaceImpl:()=>ON,stridedSliceImpl:()=>LN,stringNGramsImpl:()=>zN,stringSplitImpl:()=>PN,stringToHashBucketFastImpl:()=>BN,subImpl:()=>VN,tileImpl:()=>UN,topKImpl:()=>GN,transposeImpl:()=>yx,uniqueImpl:()=>HN});var S={};Z.r(S),Z.d(S,{assertNotComplex:()=>sp,bindCanvasToFramebuffer:()=>CF,bindColorTextureToFramebuffer:()=>ly,bindTextureToProgramUniformSampler:()=>SI,bindTextureUnit:()=>kI,bindVertexBufferToProgramAttribute:()=>Ex,callAndCheck:()=>kt,canBeRepresented:()=>hI,createFragmentShader:()=>fI,createFramebuffer:()=>vI,createProgram:()=>mI,createStaticIndexBuffer:()=>bI,createStaticVertexBuffer:()=>yI,createTexture:()=>xI,createVertexShader:()=>pI,getBatchDim:()=>Ah,getExtensionOrThrow:()=>Bf,getFramebufferErrorMessage:()=>TI,getMaxTexturesInShader:()=>AI,getNumChannels:()=>TF,getProgramUniformLocation:()=>II,getProgramUniformLocationOrThrow:()=>NI,getRowsCols:()=>Rh,getShapeAs3D:()=>Uf,getTextureShapeFromLogicalShape:()=>CI,getWebGLDisjointQueryTimerVersion:()=>RI,getWebGLErrorMessage:()=>dI,getWebGLMaxTextureSize:()=>$I,hasExtension:()=>qa,isCapableOfRenderingToFloatTexture:()=>_I,isDownloadFloatTextureEnabled:()=>DI,isReshapeFree:()=>Wf,isWebGLFenceEnabled:()=>FI,isWebGLVersionEnabled:()=>$x,linkProgram:()=>gI,logShaderSourceAndInfoLog:()=>Tx,resetMaxTextureSize:()=>$F,resetMaxTexturesInShader:()=>AF,unbindColorTextureFromFramebuffer:()=>Cx,unbindTextureUnit:()=>EF,validateFramebuffer:()=>Vf,validateProgram:()=>uy,validateTextureSize:()=>wI});var b={};Z.r(b),Z.d(b,{bindVertexProgramAttributeStreams:()=>XI,createBufferFromOutputTexture:()=>QI,createFloat16MatrixTexture:()=>HI,createFloat16PackedMatrixTexture:()=>qI,createFloat32MatrixTexture:()=>GI,createIndexBuffer:()=>WI,createPackedMatrixTexture:()=>KI,createUnsignedBytesMatrixTexture:()=>jI,createVertexBuffer:()=>UI,createVertexShader:()=>VI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>eS,downloadFloat32MatrixFromBuffer:()=>JI,downloadMatrixFromPackedOutputTexture:()=>nS,downloadPackedMatrixFromBuffer:()=>tS,getInternalFormatForFloat16MatrixTexture:()=>Fx,getInternalFormatForFloat16PackedMatrixTexture:()=>Lx,getInternalFormatForFloat32MatrixTexture:()=>Dx,getInternalFormatForPackedMatrixTexture:()=>Ox,getInternalFormatForUnsignedBytesMatrixTexture:()=>Mx,uploadDenseMatrixToTexture:()=>YI,uploadPixelDataToTexture:()=>ZI});class k{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 E{refCount(e){return F("refCount")}incRef(e){return F("incRef")}timerAvailable(){return!0}time(e){return F("time")}read(e){return F("read")}readSync(e){return F("readSync")}readToGPU(e,t){return F("readToGPU")}numDataIds(){return F("numDataIds")}disposeData(e,t){return F("disposeData")}write(e,t,r){return F("write")}move(e,t,r,s,a){return F("move")}createTensorFromGPUData(e,t,r){return F("createTensorFromGPUData")}memory(){return F("memory")}floatPrecision(){return F("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return F("dispose")}}function F(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function B(n){let e=n.length,t=0;for(;e>0;)t=Math.random()*e|0,e--,Ae(n,e,t)}function Q(n,e){if(n.length!==e.length)throw new Error(`Array sizes must match to be shuffled together First array length 
48was ${n.length}Second array length was ${e.length}`);let t=n.length,r=0;for(;t>0;)r=Math.random()*t|0,t--,Ae(n,t,r),Ae(e,t,r)}function te(n,e,t){return Math.max(n,Math.min(e,t))}function Ce(n){return n%2==0?n:n+1}function Ae(n,e,t){const r=n[e];n[e]=n[t],n[t]=r}function mt(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t];return e}function et(n,e){const t=Math.random();return e*t+(1-t)*n}function it(n,e){let t=0;for(let r=0;r<n.length;r++){const s=Number(n[r])-Number(e[r]);t+=s*s}return t}function A(n,e){if(!n)throw new Error(typeof e=="string"?e:e())}function ge(n,e,t=""){A(le(n,e),()=>t+` Shapes ${n} and ${e} must match`)}function Ve(n){A(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function j(n){if(n.length===0)return 1;let e=n[0];for(let t=1;t<n.length;t++)e*=n[t];return e}function oe(n){return n.length===0}function Y(n,e){if(n===e)return!0;if(n==null||e==null||n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==null&&e[t]!==null&&n[t]!==e[t])return!1;return!0}function le(n,e){if(n===e)return!0;if(n==null||e==null||n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function ue(n){return n%1==0}function vt(n){if(Math.tanh!=null)return Math.tanh(n);if(n===1/0)return 1;if(n===-1/0)return-1;{const e=Math.exp(2*n);return(e-1)/(e+1)}}function Me(n){const e=Math.ceil(Math.sqrt(n));return[e,Math.ceil(n/e)]}function en(n){const e=new Uint32Array(n);for(let t=0;t<n;++t)e[t]=t;return B(e),e}function jt(n,e){return e<=n.length?n:n+" ".repeat(e-n.length)}function q(n,e=s=>0,t,r){return new Promise((s,a)=>{let i=0;const o=()=>{if(n())return void s();i++;const l=e(i);t!=null&&i>=t?a():r!=null?r(o,l):setTimeout(o,l)};o()})}function Le(n,e){let t=1,r=-1;for(let a=0;a<n.length;++a)if(n[a]>=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 Oe(n,e){const t=e.length;return A((n=n==null?e.map((r,s)=>s):[].concat(n)).every(r=>r>=-t&&r<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${n}`),A(n.every(r=>ue(r)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(r=>r<0?t+r:r)}function je(n,e){const t=[],r=[],s=e!=null&&Array.isArray(e)&&e.length===0,a=e==null||s?null:Oe(e,n).sort();let i=0;for(let o=0;o<n.length;++o){if(a!=null){if(a[i]===o&&n[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${n[o]}' is not 1`);(a[i]==null||a[i]>o)&&n[o]===1&&(t.push(n[o]),r.push(o)),a[i]<=o&&i++}n[o]!==1&&(t.push(n[o]),r.push(o))}return{newShape:t,keptDims:r}}function _t(n,e){return Zt(n,e)}function Zt(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")throw new Error(`Unknown data type ${n}`);t=new Array(e)}return t}function hn(n,e){for(let t=0;t<n.length;t++){const r=n[t];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${e} being uploaded contains ${r}.`)}}function an(n){return n==="bool"||n==="complex64"||n==="float32"||n==="int32"||n==="string"}function ve(n,e){return!(e==="complex64"||e==="float32"&&n!=="complex64"||e==="int32"&&n!=="float32"&&n!=="complex64"||e==="bool"&&n==="bool")}function fr(n){if(n==="float32"||n==="int32")return 4;if(n==="complex64")return 8;if(n==="bool")return 1;throw new Error(`Unknown dtype ${n}`)}function Zn(n){if(n==null)return 0;let e=0;return n.forEach(t=>e+=t.length),e}function Qn(n){return typeof n=="string"||n instanceof String}function Hr(n){return typeof n=="boolean"}function ft(n){return typeof n=="number"}function St(n){return Array.isArray(n)?St(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":ft(n)?"float32":Qn(n)?"string":Hr(n)?"bool":"float32"}function wt(n){return!!(n&&n.constructor&&n.call&&n.apply)}function bt(n,e){for(let t=e;t<n;++t)if(n%t===0)return t;return n}function Ge(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 Zs(n,e,t,r=!1){const s=new Array;
48if(e.length===1){const a=e[0]*(r?2:1);for(let i=0;i<a;i++)s[i]=t[n+i]}else{const a=e[0],i=e.slice(1),o=i.reduce((l,p)=>l*p)*(r?2:1);for(let l=0;l<a;l++)s[l]=Zs(n+l*o,i,t,r)}return s}function Ss(n,e,t=!1){if(n.length===0)return e[0];const r=n.reduce((s,a)=>s*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 Zs(0,n,e,t)}function Ph(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 Ku(n,e){const t=Er(n,e);for(let r=0;r<t.length;r++)t[r]=1;return t}function Er(n,e){if(e==null||e==="float32"||e==="complex64")return new Float32Array(n);if(e==="int32")return new Int32Array(n);if(e==="bool")return new Uint8Array(n);throw new Error(`Unknown data type ${e}`)}function Bh(n,e){const t=n.reduce((r,s)=>r*s,1);if(e==null||e==="float32")return Ss(n,new Float32Array(t));if(e==="int32")return Ss(n,new Int32Array(t));if(e==="bool")return Ss(n,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function ts(n){n.forEach(e=>{A(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Qs(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<n.length-1;++s)r+=t[s]*n[s];return r}function Fs(n,e,t){if(e===0)return[];if(e===1)return[n];const r=new Array(e);for(let s=0;s<r.length-1;++s)r[s]=Math.floor(n/t[s]),n-=r[s]*t[s];return r[r.length-1]=n,r}function Ya(n){return n&&n.then&&typeof n.then=="function"}const Qf="tfjsflags";class mc{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=qu,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(xe().getBool("IS_TEST")||xe().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,r){if(this.flagRegistry[e]={evaluationFn:t,setHook:r},this.urlFlags[e]!=null){const s=this.urlFlags[e];xe().getBool("IS_TEST")||xe().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${s}.`),this.set(e,s)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(Ya(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(this.global===void 0||this.global.location===void 0||this.global.location.search===void 0)return;const e=this.getQueryParams(this.global.location.search);Qf in e&&e[Qf].split(",").forEach(t=>{const[r,s]=t.split(":");this.urlFlags[r]=function(a,i){const o=i.toLowerCase();return o==="true"||o==="false"?o==="true":""+ +o===o?+o:i}(0,s)})}}function qu(n){const e={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...r)=>(function(s,a,i){s[decodeURIComponent(a)]=decodeURIComponent(i||"")}(e,r[0],r[1]),r.join("="))),e}function xe(){return gc}let Vh,gc=null;function Uh(){if(Vh==null){let n;if(typeof window<"u")n=window;else if(Z.g!==void 0)n=Z.g;else if(typeof process<"u")n=process;else{if(typeof self>"u")throw new Error("Could not find a global object");n=self}Vh=n}return Vh}function Xu(n,e){const t=function(){const r=Uh();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}();if(t.has(n))return t.get(n);{const r=e();return t.set(n,r),t.get(n)}}const Yu="Abs",Da="Acos",Js="Acosh",bi="Add",yc="AddN",bc="All",xi="Any",Zu="ArgMax",wi="ArgMin",pa="Asin",go="Asinh",Za="Atan",vi="Atanh",Jo="Atan2",xc="AvgPool",wc="AvgPoolGrad",Qu="AvgPool3D",Ju="AvgPool3DGrad",yo="BatchMatMul",el="BatchToSpaceND",eu="Bincount",ki="BitwiseAnd",Ni="BroadcastTo",vc="BroadcastArgs",tl="Cast",nl="Ceil",bo="ClipByValue",Wh="Complex",rl="ComplexAbs",tu="Concat",ds="Conv2D",Gh="Conv2DBackpropFilter",sl="Conv2DBackpropInput",kc="Conv3D",Hh="Conv3DBackpropFilterV2",Nc="Conv3DBackpropInputV2",xo="Cos",Ii="Cosh",jh="Cumprod",nu="Cumsum",al="CropAndResize",il="DenseBincount",Ic="DepthToSpace",wo="DepthwiseConv2dNative",Sc="DepthwiseConv2dNativeBackpropFilter",Fa="DepthwiseConv2dNativeBackpropInput",Tc="Diag",Ms="Dilation2D",On="Dilation2DBackpropInput",jn="Dilation2DBackpropFilter",Si="Draw",Ti="RealDiv",Ec="Einsum",fa="Elu",Qa="EluGrad",ru="Erf",ol="Equal",Os="Exp",ul="ExpandDims",vo="Expm1",ll="FFT",cl="Fill",Cc="FlipLeftRight",ko="Floor",No="FloorDiv",hl="FusedBatchNorm",xn="GatherV2",$c="GatherNd",ea="Greater",Ht="GreaterEqual",Ja="Identity",ei="IFFT",Ei="Imag",Ci="IsFinite",ps="IsInf",ns="IsNan",rr="LeakyRelu",Ls="Less",$i="LessEqual",ta="LinSpace",Ft="Log",Ai="Log1p",Io="LogicalAnd",dl="LogicalNot",su="LogicalOr",Jf="LogicalXor",Kh="LogSoftmax",pp="LowerBound",au="LRN",Ma="LRNGrad",So="MatrixBandPart",iu="Max",To="Maximum",Ac="MaxPool",pl="MaxPoolGrad",Oa="MaxPool3D",Rc="MaxPool3DGrad",_c="MaxPoolWithArgmax",fl="Mean",ml="Min",Ri="Minimum",_i="MirrorPad",Eo="Mod",Dc="Multinomial",Di="Multiply",Co="Neg",$o="NotEqual",zs="NonMaxSuppressionV3",Mt="NonMaxSuppressionV4",Fc="NonMaxSuppressionV5",gl="OnesLike",ou="OneHot",Mc="Pack",yl="PadV2",fp="Pool",bl="Pow",ti="Prelu",Fi="Prod",uu="RaggedGather",Ao="RaggedRange",Mi="RaggedTensorToTensor",Ts="Range",xl="Real",Ro="Reciprocal",Oi="Relu",_o="Reshape",Es="ResizeNearestNeighbor",wl="ResizeNearestNeighborGrad",vl="ResizeBilinear",kl="ResizeBilinearGrad",Do="Relu6",Nl="Reverse",Fo="Round",lu="Rsqrt",Oc="ScatterNd",Li="TensorScatterUpdate",cu="SearchSorted",Il="Select",Sl="Selu",Lc="Slice",zi="Sin",Mo="Sinh",hu="Sign",du="Sigmoid",pu="Softplus",fu="Sqrt",La="Sum",Tl="SpaceToBatchND",El="SplitV",mu="Softmax",Cl="SparseFillEmptyRows",$l="SparseReshape",qh="SparseSegmentMean",gu="SparseSegmentSum",yu="SparseToDense",bu="SquaredDifference",zc="Square",Al="StaticRegexReplace",Pi="StridedSlice",rs="StringNGrams",Bi="StringSplit",ss="StringToHashBucketFast",Rl="Sub",xu="Tan",wu="Tanh",vu="Tile",Pc="TopK",Bc="Transform",Oo="Transpose",Vc="Unique",na="Unpack",mr="UnsortedSegmentSum",Sy="UpperBound",ku="ZerosLike",ra="Step",_l="FromPixels",Xh="RotateWithOffset",Jn="_FusedMatMul",Lo="FusedConv2D",ni="FusedDepthwiseConv2D";function In(...n){xe().getBool("IS_TEST")||xe().getBool("PROD")||console.warn(...n)}function Uc(...n){xe().getBool("IS_TEST")||xe().getBool("PROD")||console.log(...n)}const Cr=Xu("kernelRegistry",()=>new Map),ma=Xu("gradRegistry",()=>new Map);function En(n,e){const t=ri(n,e);return Cr.get(t)}function $r(n){return ma.get(n)}function _n(n){const e=Cr.entries(),t=[];for(;;){const{done:r,value:s}=e.next();if(r)break;const[a,i]=s,[o]=a.split("_");o===n&&t.push(i)}return t}function Wc(n){const{kernelName:e,backendName:t}=n,r=ri(e,t);Cr.has(r)&&In(`The kernel '${e}' for backend '${t}' is already registered`),Cr.set(r,n)}function em(n){const{kernelName:e}=n;ma.has(e)&&xe().getBool("DEBUG")&&In(`Overriding the gradient for '${e}'`),ma.set(e,n)}function za(n,e){const t=ri(n,e);if(!Cr.has(t))throw new Error(`The kernel '${n}' for backend '${e}' is not registered`);Cr.delete(t)}function Ty(n){if(!ma.has(n))throw new Error(`The gradient '${n}' for backend is not registered`);ma.delete(n)}
48function Pa(n,e){_n(n).forEach(t=>{Wc(Object.assign({},t,{backendName:e}))})}function ri(n,e){return`${e}_${n}`}function Gc(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var mp=Z(570);const zo=Z.n(mp)()||mp;function Nu(n){return zo.fromString(n,!0,16)}const gp=Nu("c3a5c85c97cb3127"),Po=Nu("b492b66fbe98f273"),fs=Nu("9ae16a3b2f90404f");function Yh(n){return n.xor(n.shru(47))}function tm(n,e,t){const r=n.slice(e,e+t);return zo.fromBytes(Array.from(r),!0,!0)}function Pn(n,e){return tm(n,e,8)}function yp(n,e){return tm(n,e,4)}function Rr(n,e){return e===0?n:n.shru(e).or(n.shl(64-e))}function Vi(n,e,t=Nu("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 Hc(n,e,t,r){return function(s,a,i,o,l,p){l=l.add(s),p=Rr(p.add(l).add(o),21);const c=l;return l=(l=l.add(a)).add(i),p=p.add(Rr(l,44)),[l.add(o),p.add(c)]}(Pn(n,e),Pn(n,e+8),Pn(n,e+16),Pn(n,e+24),t,r)}function Ps(n,e=n.length){const t=zo.fromNumber(81,!0);if(e<=32)return e<=16?function(d,m=d.length){if(m>=8){const g=fs.add(2*m),y=Pn(d,0).add(fs),w=Pn(d,m-8);return Vi(Rr(w,37).mul(g).add(y),Rr(y,25).add(w).mul(g),g)}if(m>=4){const g=fs.add(2*m);return Vi(yp(d,0).shl(3).add(m),yp(d,m-4),g)}if(m>0){const g=d[0]+(d[m>>1]<<8),y=m+(d[m-1]<<2);return Yh(fs.mul(g).xor(gp.mul(y))).mul(fs)}return fs}(n,e):function(d,m=d.length){const g=fs.add(2*m),y=Pn(d,0).mul(Po),w=Pn(d,8),v=Pn(d,m-8).mul(g),N=Pn(d,m-16).mul(fs);return Vi(Rr(y.add(w),43).add(Rr(v,30)).add(N),y.add(Rr(w.add(fs),18)).add(v),g)}(n,e);if(e<=64)return function(d,m=d.length){const g=fs.add(2*m),y=Pn(d,0).mul(fs),w=Pn(d,8),v=Pn(d,m-8).mul(g),N=Pn(d,m-16).mul(fs),T=Rr(y.add(w),43).add(Rr(v,30)).add(N),$=Vi(T,y.add(Rr(w.add(fs),18)).add(v),g),_=Pn(d,16).mul(g),L=Pn(d,24),z=T.add(Pn(d,m-32)).mul(g),O=$.add(Pn(d,m-24)).mul(g);return Vi(Rr(_.add(L),43).add(Rr(z,30)).add(O),_.add(Rr(L.add(y),18)).add(z),g)}(n,e);let r=t,s=t.mul(Po).add(113),a=Yh(s.mul(fs).add(113)).mul(fs),i=[zo.UZERO,zo.UZERO],o=[zo.UZERO,zo.UZERO];r=r.mul(fs).add(Pn(n,0));let l=0;const p=64*(e-1>>6),c=p+(e-1&63)-63;do r=Rr(r.add(s).add(i[0]).add(Pn(n,l+8)),37).mul(Po),s=Rr(s.add(i[1]).add(Pn(n,l+48)),42).mul(Po),r=r.xor(o[1]),s=s.add(i[0]).add(Pn(n,l+40)),a=Rr(a.add(o[0]),33).mul(Po),i=Hc(n,l,i[1].mul(Po),r.add(o[0])),o=Hc(n,l+32,a.add(o[1]),s.add(Pn(n,l+16))),[a,r]=[r,a],l+=64;while(l!==p);const h=Po.add(a.and(255).shl(1));return l=c,o[0]=o[0].add(e-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),r=Rr(r.add(s).add(i[0]).add(Pn(n,l+8)),37).mul(h),s=Rr(s.add(i[1]).add(Pn(n,l+48)),42).mul(h),r=r.xor(o[1].mul(9)),s=s.add(i[0].mul(9).add(Pn(n,l+40))),a=Rr(a.add(o[0]),33).mul(h),i=Hc(n,l,i[1].mul(h),r.add(o[0])),o=Hc(n,l+32,a.add(o[1]),s.add(Pn(n,l+16))),[a,r]=[r,a],Vi(Vi(i[0],o[0],h).add(Yh(s).mul(gp)).add(a),Vi(i[1],o[1],h).add(r),h)}function Bn(n,e){return e==="string"?dn(n):Ui([n],e)}function Ui(n,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Ba(n)),xe().getBool("DEBUG")&&hn(n,e),function(t,r){return t instanceof Float32Array&&r==="float32"||t instanceof Int32Array&&r==="int32"||t instanceof Uint8Array&&r==="bool"}(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<t.length;++r)Math.round(n[r])!==0&&(t[r]=1);return t}throw new Error(`Unknown data type ${e}`)}function Fn(){return xe().platform.now()}function Kn(n,e){return xe().platform.fetch(n,e)}function dn(n,e="utf-8"){return e=e||"utf-8",xe().platform.encode(n,e)}function gr(n,e="utf-8"){return e=e||"utf-8",xe().platform.decode(n,e)}function lr(n){return xe().platform.isTypedArray!=null?xe().platform.isTypedArray(n):Gc(n)}function Ba(n,e=[],t=!1){if(e==null&&(e=[]),typeof n=="boolean"||typeof n=="number"||typeof n=="string"||Ya(n)||n==null||lr(n)&&t)e.push(n);else if(Array.isArray(n)||lr(n))for(let r=0;r<n.length;++r)Ba(n[r],e,t);else{let r=-1;for(const s of Object.keys(n))/^([1-9]+[0-9]*|0)$/.test(s)&&(r=Math.max(r,Number(s)));for(let s=0;s<=r;s++)Ba(n[s],e,t)}return e}class nm{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new sr)}profileKernel(e,t,r){let s;const a=()=>{s=r()};let i;const o=Fn();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(a);else{a();for(const l of s)l.dataSync();i=Promise.resolve({kernelMs:Fn()-o})}if(xe().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<s.length;l++){const p=s[l];p.data().then(c=>{sa(c,p.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:i.then(l=>l.kernelMs),extraInfo:i.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:r,timeMs:s,inputs:a,extraInfo:i}=e;r.forEach(o=>{Promise.all([o.data(),s,i]).then(l=>{this.logger.logKernelProfile(t,o,l[0],l[1],a,l[2])})})}}function sa(n,e,t){if(e!=="float32")return!1;for(let r=0;r<n.length;r++){const s=n[r];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${t}'`),!0}return!1}class sr{logKernelProfile(e,t,r,s,a,i){const o=typeof s=="number"?jt(`${s}ms`,9):s.error,l=jt(e,25),p=t.rank,c=t.size,h=jt(t.shape.toString(),14);let d="";for(const m in a){const g=a[m];if(g!=null){const y=g.shape||t.shape,w=y.length;d+=`${m}: ${w}D ${w>0?y:""} `}}console.log(`%c${l}	%c${o}	%c${p}D ${h}	%c${c}	%c${d}	%c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function $n(n,e,t,r){const s=Ge(e),a=function(p,c,h,d){const m=j(c),g=d[d.length-1],y=new Array(g).fill(0),w=c.length,v=h==="complex64"?jc(p):p;if(w>1)for(let N=0;N<m/g;N++){const T=N*g;for(let $=0;$<g;$++)y[$]=Math.max(y[$],jr(v[T+$],0,h).length)}return y}(n,e,t,s),i=e.length,o=Zh(n,e,t,s,a),l=["Tensor"];return r&&(l.push(`  dtype: ${t}`),l.push(`  rank: ${i}`),l.push(`  shape: [${e}]`),l.push("  values:")),l.push(o.map(p=>"    "+p).join(`
49`)),l.join(`
50`)}function jr(n,e,t){let r;return r=Array.isArray(n)?`${parseFloat(n[0].toFixed(7))} + ${parseFloat(n[1].toFixed(7))}j`:Qn(n)?`'${n}'`:t==="bool"?bp(n):parseFloat(n.toFixed(7)).toString(),jt(r,e)}function bp(n){return n===0?"false":"true"}function Zh(n,e,t,r,s,a=!0){const i=t==="complex64"?2:1,o=e[0],l=e.length;if(l===0)return t==="complex64"?[jr(jc(n)[0],0,t)]:t==="bool"?[bp(n[0])]:[n[0].toString()];if(l===1){if(o>20){const y=3*i;let w=Array.from(n.slice(0,y)),v=Array.from(n.slice((o-3)*i,o*i));return t==="complex64"&&(w=jc(w),v=jc(v)),["["+w.map((N,T)=>jr(N,s[T],t)).join(", ")+", ..., "+v.map((N,T)=>jr(N,s[o-3+T],t)).join(", ")+"]"]}return["["+(t==="complex64"?jc(n):Array.from(n)).map((y,w)=>jr(y,s[w],t)).join(", ")+"]"]}const p=e.slice(1),c=r.slice(1),h=r[0]*i,d=[];if(o>20){for(let y=0;y<3;y++){const w=y*h,v=w+h;d.push(...Zh(n.slice(w,v),p,t,c,s,!1))}d.push("...");for(let y=o-3;y<o;y++){const w=y*h,v=w+h;d.push(...Zh(n.slice(w,v),p,t,c,s,y===o-1))}}else for(let y=0;y<o;y++){const w=y*h,v=w+h;d.push(...Zh(n.slice(w,v),p,t,c,s,y===o-1))}const m=l===2?",":"";d[0]="["+(o>0?d[0]+m:"");for(let y=1;y<d.length-1;y++)d[y]=" "+d[y]+m;let g=`,
51`;for(let y=2;y<l;y++)g+=`
52`;
vendor: 4,080 bytes, line 52
52return d[d.length-1]=" "+d[d.length-1]+"]"+(a?"":g),d}function jc(n){const e=[];for(let t=0;t<n.length;t+=2)e.push([n[t],n[t+1]]);return e}class kr{constructor(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=j(e),r!=null){const s=r.length;A(s===this.size,()=>`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||Zt(t,this.size),this.strides=Ge(e)}set(e,...t){t.length===0&&(t=[0]),A(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;s<e.length-1;++s)r+=this.strides[s]*e[s];return this.values[r]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let r=0;r<e.length-1;++r)t+=this.strides[r]*e[r];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let r=0;r<t.length-1;++r)t[r]=Math.floor(e/this.strides[r]),e-=t[r]*this.strides[r];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return ga().makeTensor(this.values,this.shape,this.dtype)}}let ga=null,Wi=null;class Sn{constructor(e,t,r,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=j(e),this.strides=Ge(e),this.dataId=r,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Wi.buffer(this.shape,this.dtype,e)}bufferSync(){return Wi.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ss(this.shape,e,this.dtype==="complex64")}arraySync(){return Ss(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();const e=ga().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(r=>gr(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(),ga().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=ga().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>gr(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 ga().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),ga().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Wi.print(this,e)}clone(){return this.throwIfDisposed(),Wi.clone(this)}toString(e=!1){return $n(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Wi.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),ga().makeVariable(this,e,t,r)}}function _e(){return Xu("Tensor",()=>Sn)}Object.defineProperty(Sn,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null}),_e();class Iu extends Sn{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(!le(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ga().disposeTensor(this),this.dataId=e.dataId,ga().incRef(this,null)}dispose(){ga().disposeVariable(this),this.isDisposedInternal=!0}}var Qh,Jh,Bo,ed,Su;
52Object.defineProperty(Iu,Symbol.hasInstance,{value:n=>n instanceof Sn&&n.assign!=null&&n.assign instanceof Function}),function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"}(Qh||(Qh={})),function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"}(Jh||(Jh={})),function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"}(Bo||(Bo={})),function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"}(ed||(ed={})),function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"}(Su||(Su={}));const Ey={float32:ed,int32:Jh,bool:Bo,complex64:Su};function Cs(n,e){if(n==="string"||e==="string"){if(n==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${n} with ${e}`)}return Ey[n][e]}function Kc(n){return Cs(n,"int32")}function rm(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function sm(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}function ar(n,e){if(n.dtype===e.dtype)return[n,e];const t=Cs(n.dtype,e.dtype);return[n.cast(t),e.cast(t)]}function am(n,e){A(n.dtype===e.dtype,()=>`The dtypes of the first(${n.dtype}) and second(${e.dtype}) input must match`)}function td(n,e){return e.some(t=>t.id===n.id)}function si(n){const e=[];return im(n,e,new Set),e}function im(n,e,t){if(n==null)return;if(n instanceof Sn)return void e.push(n);if(r=n,!Array.isArray(r)&&typeof r!="object")return;var r;const s=n;for(const a in s){const i=s[a];t.has(i)||(t.add(i),im(i,e,t))}}function qc(n){return n.kernelName!=null}class xp{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 Tu{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new xp}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const r=e[t];if(await this.initializeBackend(r).success)return void await this.setBackend(r)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,r=1){return e in this.registryFactory?(In(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:r},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);
52if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:r}=this.initializeBackend(e);if(!(r?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new nm(this.backendInstance),!0}setupRegisteredKernels(){_n(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){_n(e).forEach(t=>{t.disposeFunc!=null&&t.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 E||typeof r.then!="function")return this.registry[e]=r,{success:!0,asyncInit:!1};{const s=++this.pendingBackendInitId,a=r.then(i=>!(s<this.pendingBackendInitId||(this.registry[e]=i,this.pendingBackendInit=null,0))).catch(i=>(s<this.pendingBackendInitId||(this.pendingBackendInit=null,In(`Initialization of backend ${e} failed`),In(i.stack||i.message)),!1));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}}catch(r){return In(`Initialization of backend ${e} failed`),In(r.stack||r.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const r=e[t],{success:s,asyncInit:a}=this.initializeBackend(r);if(a||s)return{name:r,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const r=this.state.tensorInfo.get(t),s=r.backend,a=this.readSync(t),i=s.refCount(t);s.disposeData(t,!0),r.backend=e,e.move(t,a,r.shape,r.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let r,s=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}return this.scopedRun(()=>this.startScope(s),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,r){e();try{const s=r();return t(),s}catch(s){throw t(),s}}nextTensorId(){return Tu.nextTensorId++}nextVariableId(){return Tu.nextVariableId++}clone(e){const t=J.runKernel(Ja,{x:e}),r={x:e};return this.addTapeNode(this.state.activeScope.name,r,[t],s=>({x:()=>{const a={x:s};return J.runKernel(tl,a,{dtype:"float32"})}}),[],{}),t}runKernel(e,t,r){if(this.backendName==null&&this.backend,En(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 i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-a-i;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,r=[];const s=this.isTapeOn(),a=this.state.numBytes,i=this.state.numTensors;let o,l;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),this.backendName==null&&this.backend;const p=qc(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(qc(e)){const{kernelName:g,inputs:y,attrs:w}=e;this.backendName==null&&this.backend;const v=En(g,this.backendName);A(v!=null,()=>`Cannot find registered kernel '${g}' for backend '${this.backendName}'`),o=()=>{const N=this.backend.numDataIds();
vendor: 10,287 bytes, line 52
52l=v.kernelFunc({inputs:y,attrs:w,backend:this.backend});const T=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(g,N,T);const $=T.map(_=>_.rank!=null?_:this.makeTensorFromTensorInfo(_));if(s){const _=this.getTensorsForGradient(g,y,$);r=this.saveTensorsForBackwardMode(_)}return $}}else{const{forwardFunc:g}=e,y=w=>{s&&(r=w.map(v=>this.keep(this.clone(v))))};o=()=>{const w=this.backend.numDataIds();l=this.tidy(()=>g(this.backend,y));const v=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,w,v),v}}const{inputs:c,attrs:h}=e,d=qc(e)?null:e.backwardsFunc;let m;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(m=this.profiler.profileKernel(p,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(m),t=m.outputs):t=o()}),s&&this.addTapeNode(p,c,t,d,r,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:p,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(g=>c[g]!=null?c[g].shape:null),outputShapes:t.map(g=>g.shape),kernelTimeMs:m.timeMs,extraInfo:m.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(r=>this.keep(this.clone(r)))}getTensorsForGradient(e,t,r){const s=$r(e);if(s!=null){const a=s.inputsToSave||[],i=s.outputsToSave||[];let o;s.saveAllInputs?(A(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(p=>t[p])):o=a.map(p=>t[p]);const l=r.filter((p,c)=>i[c]);return o.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"&&Qn(e[0])&&(a=e.map(l=>dn(l)));const i=s.write(a,t,r),o=new Sn(t,r,i,this.nextTensorId());if(this.trackTensor(o,s),r==="string"){const l=this.state.tensorInfo.get(i),p=Zn(a);this.state.numBytes+=p-l.bytes,l.bytes=p}return o}makeTensorFromDataId(e,t,r,s){const a={dataId:e,shape:t,dtype:r=r||"float32"};return this.makeTensorFromTensorInfo(a,s)}makeTensorFromTensorInfo(e,t){const{dataId:r,shape:s,dtype:a}=e,i=new Sn(s,a,r,this.nextTensorId());return this.trackTensor(i,t),i}makeVariable(e,t=!0,r,s){r=r||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));const a=new Iu(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*fr(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 Iu||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*fr(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,i){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:a},l=$r(e);l!=null&&(s=l.gradFunc),s!=null&&(o.gradient=p=>(p=p.map((c,h)=>{if(c==null){const d=r[h],m=Er(d.size,d.dtype);return this.makeTensor(m,d.shape,d.dtype)}return c}),s(p.length>1?p:p[0],a,i))),this.state.activeTape.push(o)}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=si(e),r=new Set(t.map(a=>a.id));for(let a=0;a<this.state.activeScope.track.length;a++){const i=this.state.activeScope.track[a];i.kept||r.has(i.id)||i.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(a=>{a.kept||a.scopeId!==s.id||this.track(a)})}gradients(e,t,r,s=!1){if(A(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(a instanceof Sn,()=>"The result y returned by f() must be a tensor.");const i=function(o,l,p){const c={},h={};for(let y=0;y<l.length;y++)c[l[y].id]=!0;for(let y=0;y<o.length;y++){const w=o[y],v=w.inputs;for(const N in v){const T=v[N];let $=!1;for(let _=0;_<l.length;_++)if(c[T.id]){w.outputs.forEach(L=>c[L.id]=!0),$=!0,h[w.id]=!0;break}if($)break}}const d={};d[p.id]=!0;const m={};for(let y=o.length-1;y>=0;y--){const w=o[y],v=w.inputs;for(let N=0;N<w.outputs.length;N++)if(d[w.outputs[N].id]){for(const T in v)d[v[T].id]=!0,m[w.id]=!0;break}}const g=[];for(let y=0;y<o.length;y++){const w=o[y];if(h[w.id]&&m[w.id]){const v={};for(const T in w.inputs){const $=w.inputs[T];c[$.id]&&(v[T]=$)}const N=Object.assign({},w);N.inputs=v,N.outputs=w.outputs,g.push(N)}}return g}(this.state.activeTape,t,a);if(!s&&i.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 o={};o[a.id]=r??function(p){const c=Ku(j(p),"float32");return J.makeTensor(c,p,"float32")}(a.shape),function(p,c,h,d){for(let m=c.length-1;m>=0;m--){const g=c[m],y=[];if(g.outputs.forEach(v=>{const N=p[v.id];N!=null?y.push(N):y.push(null)}),g.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${g.kernelName}.`);const w=g.gradient(y);for(const v in g.inputs){if(!(v in w))throw new Error(`Cannot backprop through input ${v}. Available gradients found: ${Object.keys(w)}.`);const N=h(()=>w[v]());if(N.dtype!=="float32")throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input ${v} must have 'float32' dtype, but has '${N.dtype}'`);const T=g.inputs[v];if(!le(N.shape,T.shape))throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input '${v}' has shape '${N.shape}', which does not match the shape of the input '${T.shape}'`);if(p[T.id]==null)p[T.id]=N;else{const $=p[T.id];p[T.id]=d($,N),$.dispose()}}}}(o,i,p=>this.tidy(p),nd);const l=t.map(p=>o[p.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(p=>{for(const c of p.saved)c.dispose()}),this.state.activeTape=null),{value:a,grads:l}})}customGrad(e){return A(wt(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let r;A(t.every(a=>a instanceof Sn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const s={};return t.forEach((a,i)=>{s[i]=a}),this.runKernelFunc({forwardFunc:(a,i)=>(r=e(...t,i),A(r.value instanceof Sn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(wt(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),backwardsFunc:(a,i)=>{const o=r.gradFunc(a,i),l=Array.isArray(o)?o:[o];A(l.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(...)."),A(l.every(c=>c instanceof Sn),()=>"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 p={};return l.forEach((c,h)=>{p[h]=()=>c}),p},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=Fn(),r=await this.backend.time(e);return r.wallMs=Fn()-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 xp;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}}function om(){const n=Uh();if(n._tfengine==null){const t=new mc(n);n._tfengine=new Tu(t)}
52var e;return e=n._tfengine.ENV,gc=e,ga=()=>n._tfengine,n._tfengine}Tu.nextTensorId=0,Tu.nextVariableId=0;const J=om();function nd(n,e){const t={a:n,b:e};return J.runKernel(bi,t)}let Dl;function cr(n){Dl=n}function rd(n){if(Dl!==void 0)return Dl;if(n||typeof navigator<"u"&&navigator!=null){if(n||(n=navigator),n.product==="ReactNative")return!0;const e=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");if(!e){const t=n;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function yr(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}const Kr=xe();function ya(n,e){let t=n;if(lr(n))return e==="string"?[]:[n.length];if(rm(n)){const s=n.channels||"RGBA";return[n.height,n.width*s.length]}if(sm(n))return[n.buffer.size/(e==null?4:fr(e))];if(!Array.isArray(n))return[];const r=[];for(;Array.isArray(t)||lr(t)&&e!=="string";)r.push(t.length),t=t[0];return Array.isArray(n)&&xe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&um(n,r,[]),r}function um(n,e,t){if(t=t||[],!Array.isArray(n)&&!lr(n))return void A(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);A(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${n.length} elements`),A(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<n.length;++s)um(n[s],r,t.concat(s))}function lm(n,e,t,r){if(n!=="string_or_numeric"){if(n==null)throw new Error("Expected dtype cannot be null.");if(n!=="numeric"&&n!==e||n==="numeric"&&e==="string")throw new Error(`Argument '${t}' passed to '${r}' must be ${n} tensor, but got ${e} tensor`)}}function P(n,e,t,r="numeric"){if(n instanceof _e())return lm(r,n.dtype,e,t),n;let s=St(n);if(s!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),lm(r,s,e,t),n==null||!lr(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const o=n==null?"null":n.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${o}'`)}const a=ya(n,s);lr(n)||Array.isArray(n)||(n=[n]);
52const i=s!=="string"?Ui(n,s):Ba(n,[],!0);return J.makeTensor(i,a,s)}function Fl(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((s,a)=>P(s,`${e}[${a}]`,t,r))}Kr.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.")}),Kr.registerFlag("IS_BROWSER",()=>yr()),Kr.registerFlag("IS_NODE",()=>typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0),Kr.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Kr.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Kr.registerFlag("PROD",()=>!1),Kr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Kr.getBool("DEBUG")),Kr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Kr.registerFlag("IS_TEST",()=>!1),Kr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Kr.getBool("DEBUG")),Kr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Kr.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Kr.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const Xc="__op";function ee(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+=Xc;const s=(...a)=>{J.startScope(t);try{const i=r(...a);return Ya(i)&&console.error("Cannot return a Promise inside of tidy."),J.endScope(i),i}catch(i){throw J.endScope(null),i}};return Object.defineProperty(s,"name",{value:t,configurable:!0}),s}const Gi=ee({complex_:function(n,e){const t=P(n,"real","complex"),r=P(e,"imag","complex");ge(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 J.runKernel(Wh,s)}});function Hi(n,e,t,r){if(r==null)r=St(n);else if(r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
52if(sm(n)||rm(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 J.backend.createTensorFromGPUData(n,e||t,r)}if(!lr(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){ts(e);const s=j(e),a=j(t);A(s===a,()=>`Based on the provided shape, [${e}], the tensor should have ${s} values but has ${a}`);for(let i=0;i<t.length;++i){const o=t[i],l=i!==t.length-1||o!==j(e.slice(i));A(t[i]===e[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return lr(n)||Array.isArray(n)||(n=[n]),e=e||t,n=r!=="string"?Ui(n,r):Ba(n,[],!0),J.makeTensor(n,e,r)}function Bs(n,e,t){return Hi(n,e,ya(n,t),t)}const ba={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class xa{static join(e){return new xa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,e==null||(e instanceof Array||(e=[e]),(e=e.map(r=>lr(r)?r.buffer:r)).length===0))return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let r=0;r<e.length;r++){const s=e[r];r!==e.length-1&&s.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const a=t+s.byteLength;this.shards.push({buffer:s,start:t,end:a}),t=a}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const r=this.findShardForByte(e);if(r===-1)throw new Error(`Could not find start shard for byte ${e}`);const s=new ArrayBuffer(t-e),a=new Uint8Array(s);let i=0;for(let o=r;o<this.shards.length;o++){const l=this.shards[o],p=e+i-l.start,c=i,h=Math.min(t,l.end)-l.start,d=new Uint8Array(l.buffer,p,h-p);if(a.set(d,c),i+=d.length,t<l.end)break}return s}findShardForByte(e){if(this.shards.length===0||e<0||e>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(s){return e<s.start?-1:e>=s.end?1:0}
52if(t(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const r=function(s,a){let i=0,o=s.length;for(;i<=o;){const l=Math.floor((o-i)/2)+i,p=a(s[l]);if(p===0)return l;p<0?o=l:i=l+1}return-1}(this.shards,t);return r===-1?-1:(this.previousShardIndex=r,this.previousShardIndex)}}function Cy(){xe().set("PROD",!0)}function cm(){xe().set("DEBUG",!0)}function wp(){xe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function vp(n){xe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function hm(){J.disposeVariables()}function wa(){return J}function sd(){return J.memory()}function kp(n){return J.profile(n)}function be(n,e){return J.tidy(n,e)}function on(n){si(n).forEach(e=>e.dispose())}function _r(n){return J.keep(n)}function $y(n){return J.time(n)}function dm(n){return J.setBackend(n)}function pm(){return J.ready()}function Np(){return J.backendName}function Ip(n){J.removeBackend(n)}function Sp(n){return J.findBackend(n)}function fm(n){return J.findBackendFactory(n)}function Tp(n,e,t=1){return J.registerBackend(n,e,t)}function ad(){return J.backend}function Ay(n,e){xe().setPlatform(n,e)}const ji=4;async function id(n,e){const t=[],r=[],s=Array.isArray(n)?n.map(a=>a.name):Object.keys(n);for(let a=0;a<s.length;++a){const i=s[a],o=Array.isArray(n)?n[a].tensor:n[i];if(o.dtype!=="float32"&&o.dtype!=="int32"&&o.dtype!=="bool"&&o.dtype!=="string"&&o.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const l={name:i,shape:o.shape,dtype:o.dtype};if(o.dtype==="string"){const p=new Promise(async c=>{const h=await o.bytes(),d=h.reduce((y,w)=>y+w.length,0)+ji*h.length,m=new Uint8Array(d);let g=0;for(let y=0;y<h.length;y++){const w=h[y],v=new Uint8Array(new Uint32Array([w.length]).buffer);m.set(v,g),g+=ji,m.set(w,g),g+=w.length}c(m)});r.push(p)}else r.push(o.data());e!=null&&(l.group=e),t.push(l)}return{data:gm(await Promise.all(r)),specs:t}}function od(n,e){const t=new xa(n),r={};let s=0;for(const a of e){const i=Ry(a,(o,l)=>t.slice(s+o,s+l));r[a.name]=Cp(a,t.slice(s,s+i)),s+=i}return r}function Ry(n,e){const t=j(n.shape);let r;if("quantization"in n){const s=n.quantization;r=ba[s.dtype]}else{if(n.dtype==="string"){let s=0;for(let a=0;a<t;a++)s+=ji+new Uint32Array(e(s,s+ji))[0];return s}r=ba[n.dtype]}return t*r}async function Ep(n,e){const t=j(n.shape);let r;if("quantization"in n){const s=n.quantization;r=ba[s.dtype]}else{if(n.dtype==="string"){let s=0;for(let a=0;a<t;a++)s+=ji+new Uint32Array(await e(s,s+ji))[0];return s}r=ba[n.dtype]}return t*r}function Cp(n,e){const t=n.name,r=n.dtype,s=n.shape,a=j(s);let i,o=0;if("quantization"in n){const l=n.quantization;if(l.dtype==="uint8"||l.dtype==="uint16"){if(!("min"in l)||!("scale"in l))throw new Error(`Weight ${n.name} with quantization ${l.dtype} doesn't have corresponding metadata min and scale.`)}else{if(l.dtype!=="float16")throw new Error(`Weight ${n.name} has unknown quantization dtype ${l.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if(r!=="float32")throw new Error(`Weight ${n.name} is quantized with ${l.dtype} which only supports weights of type float32 not ${r}.`)}const p=ba[l.dtype],c=l.dtype==="uint8"?new Uint8Array(e):new Uint16Array(e);if(r==="float32")if(l.dtype==="uint8"||l.dtype==="uint16"){i=new Float32Array(c.length);for(let h=0;h<c.length;h++){const d=c[h];i[h]=d*l.scale+l.min}}else{if(l.dtype!=="float16")throw new Error(`Unsupported quantization type ${l.dtype} for weight type float32.`);i=function(){const d=function(){const y=v=>{let N=v<<13,T=0;for(;!(8388608&N);)T-=8388608,N<<=1;return N&=-8388609,T+=947912704,N|T},w=new Uint32Array(2048);w[0]=0;for(let v=1;v<1024;v++)w[v]=y(v);for(let v=1024;v<2048;v++)w[v]=939524096+(v-1024<<13);return w}(),m=function(){const y=new Uint32Array(64);y[0]=0,y[31]=1199570944,y[32]=2147483648,y[63]=3347054592;for(let w=1;w<31;w++)y[w]=w<<23;for(let w=33;w<63;w++)y[w]=2147483648+(w-32<<23);return y}(),g=function(){const y=new Uint32Array(64);for(let w=0;w<64;w++)y[w]=1024;
52return y[0]=y[32]=0,y}();return y=>{const w=new ArrayBuffer(4*y.length),v=new Uint32Array(w);for(let N=0;N<y.length;N++){const T=y[N],$=d[g[T>>10]+(1023&T)]+m[T>>10];v[N]=$}return new Float32Array(w)}}()(c)}else{if(r!=="int32")throw new Error(`Unsupported dtype in weight '${t}': ${r}`);if(l.dtype!=="uint8"&&l.dtype!=="uint16")throw new Error(`Unsupported quantization type ${l.dtype} for weight type int32.`);i=new Int32Array(c.length);for(let h=0;h<c.length;h++){const d=c[h];i[h]=Math.round(d*l.scale+l.min)}}o+=a*p}else if(r==="string"){const l=j(n.shape);i=[];for(let p=0;p<l;p++){const c=new Uint32Array(e.slice(o,o+ji))[0];o+=ji;const h=new Uint8Array(e.slice(o,o+c));i.push(h),o+=c}}else{const l=ba[r];if(r==="float32")i=new Float32Array(e);else if(r==="int32")i=new Int32Array(e);else{if(r!=="bool"){if(r==="complex64"){i=new Float32Array(e);const p=new Float32Array(i.length/2),c=new Float32Array(i.length/2);for(let g=0;g<p.length;g++)p[g]=i[2*g],c[g]=i[2*g+1];const h=Bs(p,s,"float32"),d=Bs(c,s,"float32"),m=Gi(h,d);return h.dispose(),d.dispose(),m}throw new Error(`Unsupported dtype in weight '${t}': ${r}`)}i=new Uint8Array(e)}o+=a*l}return Bs(i,s,r)}async function $p(n,e,t){let r=new Uint8Array(e);for(;r.byteLength<t;){const{done:s,value:a}=await n.read();if(s&&a==null){const o=t-r.byteLength;throw new Error(`Reader is done but ${o} bytes are still expected`)}const i=new Uint8Array(r.length+a.byteLength);i.set(r,0),i.set(new Uint8Array(a),r.length),r=i}return r.buffer}async function mm(n,e){const t={},r=n.getReader();let s=new ArrayBuffer(0);for(const a of e){const i=await Ep(a,async(p,c)=>(s=await $p(r,s,c),s.slice(p,c)));s=await $p(r,s,i);const o=s.slice(0,i);s=s.slice(i);const l=Cp(a,o);if(t[a.name]=l,Np()==="webgpu"){const p=ad();"uploadToGPU"in p&&j(l.shape)>=xe().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&p.uploadToGPU(l.dataId)}}return t}function gm(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 Ap=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function ud(n){return Ap?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function ld(n){return xa.join(n)}function Rp(n){for(n=n.trim();n.endsWith("/");)n=n.slice(0,n.length-1);const e=n.split("/");return e[e.length-1]}function Yc(n,e){const t={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy,weightsManifest:e};return n.signature!=null&&(t.signature=n.signature),n.userDefinedMetadata!=null&&(t.userDefinedMetadata=n.userDefinedMetadata),n.modelInitializer!=null&&(t.modelInitializer=n.modelInitializer),n.initializerSignature!=null&&(t.initializerSignature=n.initializerSignature),n.trainingConfig!=null&&(t.trainingConfig=n.trainingConfig),t}function Eu(n,e,t){const r={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy};if(n.trainingConfig!=null&&(r.trainingConfig=n.trainingConfig),n.weightsManifest!=null){if(!e)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!t)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=e,r.weightData=t}return n.signature!=null&&(r.signature=n.signature),n.userDefinedMetadata!=null&&(r.userDefinedMetadata=n.userDefinedMetadata),n.modelInitializer!=null&&(r.modelInitializer=n.modelInitializer),n.initializerSignature!=null&&(r.initializerSignature=n.initializerSignature),r}async function cd(n,e){let t,r;return n.weightsManifest!=null&&([t,r]=await e(n.weightsManifest)),Eu(n,t,r)}function Ml(n){if(n.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:n.modelTopology==null?0:ud(JSON.stringify(n.modelTopology)),weightSpecsBytes:n.weightSpecs==null?0:ud(JSON.stringify(n.weightSpecs)),weightDataBytes:n.weightData==null?0:new xa(n.weightData).byteLength}}function Cu(n){const e=[];for(const t of n)e.push(...t.weights);return e}class hr{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return hr.instance==null&&(hr.instance=new hr),hr.instance}static registerSaveRouter(e){hr.getInstance().saveRouters.push(e)}static registerLoadRouter(e){hr.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return hr.getHandlers(e,"save")}static getLoadHandlers(e,t){return hr.getHandlers(e,"load",t)}static getHandlers(e,t,r){const s=[];return(t==="load"?hr.getInstance().loadRouters:hr.getInstance().saveRouters).forEac
52h(a=>{const i=a(e,r);i!==null&&s.push(i)}),s}}const ym=n=>hr.registerSaveRouter(n),Zc=n=>hr.registerLoadRouter(n),Vo=n=>hr.getSaveHandlers(n),_p=(n,e)=>hr.getLoadHandlers(n,e),hd="tensorflowjs",Uo="models_store",Ot="model_info_store";function Dp(){if(!xe().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 dd(n){const e=n.result;e.createObjectStore(Uo,{keyPath:"modelPath"}),e.createObjectStore(Ot,{keyPath:"modelPath"})}class ms{constructor(e){if(this.indexedDB=Dp(),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(hd,1);a.onupgradeneeded=()=>dd(a),a.onsuccess=()=>{const i=a.result;if(t==null){const o=i.transaction(Uo,"readonly"),l=o.objectStore(Uo).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return i.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(l.result.modelArtifacts)},l.onerror=p=>(i.close(),s(l.error)),o.oncomplete=()=>i.close()}else{t.weightData=xa.join(t.weightData);const o=Ml(t),l=i.transaction(Ot,"readwrite");let p,c,h=l.objectStore(Ot);try{p=h.put({modelPath:this.modelPath,modelArtifactsInfo:o})}catch(d){return s(d)}p.onsuccess=()=>{c=i.transaction(Uo,"readwrite");const d=c.objectStore(Uo);let m;try{m=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o})}catch(g){return s(g)}m.onsuccess=()=>r({modelArtifactsInfo:o}),m.onerror=g=>{h=l.objectStore(Ot);const y=h.delete(this.modelPath);y.onsuccess=()=>(i.close(),s(m.error)),y.onerror=w=>(i.close(),s(m.error))}},p.onerror=d=>(i.close(),s(p.error)),l.oncomplete=()=>{c==null?i.close():c.oncomplete=()=>i.close()}}},a.onerror=i=>s(a.error)})}}ms.URL_SCHEME="indexeddb://";const Ki=n=>{return xe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(ms.URL_SCHEME)?(e=n.slice(ms.URL_SCHEME.length),new ms(e)):null;var e};hr.registerSaveRouter(Ki),hr.registerLoadRouter(Ki);class Fp{constructor(){this.indexedDB=Dp()}async listModels(){return new Promise((e,t)=>{const r=this.indexedDB.open(hd,1);r.onupgradeneeded=()=>dd(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(Ot,"readonly"),i=a.objectStore(Ot).getAll();i.onsuccess=()=>{const o={};for(const l of i.result)o[l.modelPath]=l.modelArtifactsInfo;e(o)},i.onerror=o=>(s.close(),t(i.error)),a.oncomplete=()=>s.close()},r.onerror=s=>t(r.error)})}async removeModel(e){var t;return e=(t=e).startsWith(ms.URL_SCHEME)?t.slice(ms.URL_SCHEME.length):t,new Promise((r,s)=>{const a=this.indexedDB.open(hd,1);a.onupgradeneeded=()=>dd(a),a.onsuccess=()=>{const i=a.result,o=i.transaction(Ot,"readwrite"),l=o.objectStore(Ot),p=l.get(e);let c;p.onsuccess=()=>{if(p.result==null)return i.close(),s(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const h=l.delete(e),d=()=>{c=i.transaction(Uo,"readwrite");const m=c.objectStore(Uo).delete(e);m.onsuccess=()=>r(p.result.modelArtifactsInfo),m.onerror=g=>s(p.error)};h.onsuccess=d,h.onerror=m=>(d(),i.close(),s(p.error))}},p.onerror=h=>(i.close(),s(p.error)),o.oncomplete=()=>{c==null?i.close():c.oncomplete=()=>i.close()}},a.onerror=i=>s(a.error)})}}const ai="/",Tt="tensorflowjs_models",Qc="info",Ol="model_topology",pd="weight_specs",fd="weight_data",$s="model_metadata";function bm(n){return{info:[Tt,n,Qc].join(ai),topology:[Tt,n,Ol].join(ai),weightSpecs:[Tt,n,pd].join(ai),weightData:[Tt,n,fd].join(ai),modelMetadata:[Tt,n,$s].join(ai)}}function Mp(n){for(const e of Object.values(n))window.localStorage.removeItem(e)}function xm(n){const e=n.split(ai);if(e.length<3)throw new Error(`Invalid key format: ${n}`);return e.slice(1,e.length-1).join(ai)}
52class qi{constructor(e){if(!xe().getBool("IS_BROWSER")||typeof window>"u"||window.localStorage===void 0)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=bm(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=Ml(e),a=xa.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,function(o){if(Ap)return Buffer.from(o).toString("base64");const l=new Uint8Array(o);let p="";for(let c=0,h=l.length;c<h;c++)p+=String.fromCharCode(l[c]);return btoa(p)}(a));const i={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(i)),{modelArtifactsInfo:s}}catch{throw Mp(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 o=JSON.parse(a);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.initializerSignature!=null&&(t.initializerSignature=o.initializerSignature),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}const i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(o){if(Ap){const c=Buffer.from(o,"base64");return c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength)}const l=atob(o),p=new Uint8Array(l.length);for(let c=0;c<l.length;++c)p.set([l.charCodeAt(c)],c);return p.buffer}(i),t}}qi.URL_SCHEME="localstorage://";const Ll=n=>{return xe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(qi.URL_SCHEME)?(e=n.slice(qi.URL_SCHEME.length),new qi(e)):null;var e};hr.registerSaveRouter(Ll),hr.registerLoadRouter(Ll);class Wo{constructor(){A(xe().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window>"u"||window.localStorage!==void 0,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Tt+ai,r=ai+Qc;for(let s=0;s<this.LS.length;++s){const a=this.LS.key(s);a.startsWith(t)&&a.endsWith(r)&&(e[xm(a)]=JSON.parse(this.LS.getItem(a)))}return e}async removeModel(e){var t;const r=bm(e=(t=e).startsWith(qi.URL_SCHEME)?t.slice(qi.URL_SCHEME.length):t);if(this.LS.getItem(r.info)==null)throw new Error(`Cannot find model at path '${e}'`);const s=JSON.parse(this.LS.getItem(r.info));return Mp(r),s}}const Xi="://";class qr{constructor(){this.managers={}}static getInstance(){return qr.instance==null&&(qr.instance=new qr),qr.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Xi)&&(e=e.slice(0,e.indexOf(Xi))),A(e.length>0,()=>"scheme must not be an empty string.");const r=qr.getInstance();A(r.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),r.managers[e]=t}static getManager(e){const t=qr.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(qr.getInstance().managers)}}function Yi(n){if(n.indexOf(Xi)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${qr.getSchemes().join(",")}`);return{scheme:n.split(Xi)[0],path:n.split(Xi)[1]}}async function wm(n,e,t=!1){A(n!==e,()=>`Old path and new path are the same: '${n}'`);const r=hr.getLoadHandlers(n);A(r.length>0,()=>`Copying failed because no load handler is found for source URL ${n}.`),A(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${n}.`);const s=r[0],a=hr.getSaveHandlers(e);A(a.length>0,()=>
52`Copying failed because no save handler is found for destination URL ${e}.`),A(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${e}.`);const i=a[0],o=Yi(n).scheme,l=Yi(n).path,p=o===Yi(n).scheme,c=await s.load();t&&p&&await qr.getManager(o).removeModel(l);const h=await i.save(c);return t&&!p&&await qr.getManager(o).removeModel(l),h.modelArtifactsInfo}async function _y(){const n=qr.getSchemes(),e={};for(const t of n){const r=await qr.getManager(t).listModels();for(const s in r)e[t+Xi+s]=r[s]}return e}async function Zi(n){const e=Yi(n);return qr.getManager(e.scheme).removeModel(e.path)}async function Op(n,e){return wm(n,e,!1)}async function vm(n,e){return wm(n,e,!0)}class zl{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){typeof window<"u"&&xe().getBool("USE_SETTIMEOUTCUSTOM")?(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=>{r.source===window&&r.data.name===this.messageName&&(r.stopPropagation(),(0,this.functionRefs[r.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))},!0))):setTimeout(e,t)}isTypedArray(e){return Gc(e)}}if(xe().get("IS_BROWSER")){xe().setPlatform("browser",new zl);try{qr.registerManager(qi.URL_SCHEME,new Wo)}catch{}try{qr.registerManager(ms.URL_SCHEME,new Fp)}catch{}}let md;function ln(n,e="float32",t){return e=e||"float32",ts(n),new kr(n,e,t)}xe().get("IS_NODE")&&!xe().get("IS_BROWSER")&&xe().setPlatform("node",new class{constructor(){this.util=Z(590),this.textEncoder=new this.util.TextEncoder}fetch(n,e){return xe().global.fetch!=null?xe().global.fetch(n,e):(md==null&&(md=Z(817)),md(n,e))}now(){const n=process.hrtime();return 1e3*n[0]+n[1]/1e6}encode(n,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(n)}decode(n,e){return n.length===0?"":new this.util.TextDecoder(e).decode(n)}isTypedArray(n){return this.util.types.isFloat32Array(n)||this.util.types.isInt32Array(n)||this.util.types.isUint8Array(n)||this.util.types.isUint8ClampedArray(n)}});const gt=ee({cast_:function(n,e){const t=P(n,"x","cast");if(!an(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 J.runKernel(tl,r,s)}}),va=ee({clone_:function(n){const e={x:P(n,"x","clone","string_or_numeric")};return J.runKernel(Ja,e)}});function Pl(n,e=!1){console.log(n.toString(e))}om(),Wi={buffer:ln,cast:gt,clone:va,print:Pl};const Ue=ee({add_:function(n,e){let t=P(n,"a","add"),r=P(e,"b","add");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(bi,s)}}),Jc=ee({floorDiv_:function(n,e){let t=P(n,"a","floorDiv"),r=P(e,"b","floorDiv");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(No,s)}}),Lt=ee({div_:function(n,e){let t=P(n,"a","div"),r=P(e,"b","div");if([t,r]=ar(t,r),t.dtype==="int32"&&r.dtype==="int32")return Jc(t,r);const s={a:t,b:r};return J.runKernel(Ti,s,{})}}),se=ee({mul_:function(n,e){let t=P(n,"a","mul"),r=P(e,"b","mul");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(Di,s)}}),qn=ee({sqrt_:function(n){const e={x:P(n,"x","sqrt","float32")};return J.runKernel(fu,e)}}),Mn=ee({square_:function(n){const e=P(n,"x","square");return J.runKernel("Square",{x:e},{})}}),mn=ee({zerosLike_:function(n){const e={x:P(n,"x","zerosLike")};return J.runKernel(ku,e)}});function eh(n){return A(wt(n),()=>"The f passed in grad(f) must be a function"),(e,t)=>{const r=P(e,"x","tf.grad","string_or_numeric"),s=t!=null?P(t,"dy","tf.grad"):null;return J.tidy(()=>{const{value:a,grads:i}=J.gradients(()=>n(r),[r],s);return s!=null&&ge(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),th(i),i[0]})}}function km(n){return A(wt(n),()=>"The f passed in grads(f) must be a function"),(e,t)=>{A(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=Fl(e,"args","tf.grads","string_or_numeric"),s=t!=null?P(t,"dy","tf.grads"):null;return J.tidy(()=>{const{value:a,grads:i}=J.gradients(()=>n(...r),r,s);return s!=null&&ge(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),th(i),i})}}function Nm(n){return A(wt(n),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{A(e instanceof Sn,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(t==null||t instanceof Sn,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:s}=J.gradients(()=>n(e),[e],t);return th(r),{grad:r[0],value:s}}}function Im(n){return A(wt(n),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{A(Array.isArray(e)&&e.every(s=>s instanceof Sn),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(t==null||t instanceof Sn,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=J.gradients(()=>n(...e),e,t);return t!=null&&ge(r.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),th(r.grads),r}}function gs(n,e){A(wt(n),()=>"The f passed in variableGrads(f) must be a function"),A(e==null||Array.isArray(e)&&e.every(l=>l instanceof Iu),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const t=e!=null;if(!t){e=[];for(const l in J.registeredVariables)e.push(J.registeredVariables[l])}const r=t?e.filter(l=>!l.trainable):null,s=e.length;e=e.filter(l=>l.trainable),A(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);const{value:a,grads:i}=J.gradients(n,e,null,!0);A(i.some(l=>l!=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()."),A(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const o={};return e.forEach((l,p)=>{i[p]!=null&&(o[l.name]=i[p])}),r?.forEach(l=>o[l.name]=null),{value:a,grads:o}}function Br(n){return J.customGrad(n)}function th(n){if(n.filter(e=>e==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
53    the f you passed encloses all operations that lead from x to y.`)}function Pt(n,e){if((lr(n)&&e!=="string"||Array.isArray(n))&&e!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(e==="string"&&lr(n)&&!(n instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Hi(n,[],[],e)}const Bl=new Map,Vl=new Map;class ii{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class as{constructor(){this.classNameMap={}}static getMap(){return as.instance==null&&(as.instance=new as),as.instance}static register(e){as.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function st(n,e,t){A(n.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),A(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),e===void 0&&(e="Custom"),t===void 0&&(t=n.className);const r=e+">"+t;return as.register(n),Bl.set(r,n),Vl.set(n,r),n}function Vr(n){return Vl.has(n)?Vl.get(n):n.className}class oi extends ii{minimize(e,t=!1,r){const{value:s,grads:a}=this.computeGradients(e,r);if(r!=null){const i=r.map(o=>({name:o.name,tensor:a[o.name]}));this.applyGradients(i)}else this.applyGradients(a);return on(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 gs(e,t)}dispose(){this.iterations_!=null&&on(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Pt(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(oi,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});class aa extends oi{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=J.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>
53t.name):Object.keys(e)).forEach((t,r)=>{const s=J.registeredVariables[t],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accum_grad`,variable:be(()=>mn(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${t}/accum_var`,variable:be(()=>mn(s).variable(a))});const i=Array.isArray(e)?e[r].tensor:e[t];if(i==null)return;const o=this.accumulatedGrads[r].variable,l=this.accumulatedUpdates[r].variable;be(()=>{const p=Ue(se(o,this.rho),se(Mn(i),1-this.rho)),c=se(Lt(qn(Ue(l,this.epsilon)),qn(Ue(o,this.epsilon))),i),h=Ue(se(l,this.rho),se(Mn(c),1-this.rho));o.assign(p),l.assign(h);const d=Ue(se(c,-this.learningRate),s);s.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(on(this.accumulatedGrads.map(e=>e.variable)),on(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){const t=(e=await this.extractIterations(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,2*t).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)}}function $u(n,e,t){ts(n);const r={shape:n,value:e,dtype:t=t||St(e)};return J.runKernel(cl,{},r)}class gd extends oi{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(t=>t.name):Object.keys(e)).forEach((t,r)=>{const s=J.registeredVariables[t];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accumulator`,variable:be(()=>$u(s.shape,this.initialAccumulatorValue).variable(!1))});const a=Array.isArray(e)?e[r].tensor:e[t];if(a==null)return;const i=this.accumulatedGrads[r].variable;be(()=>{const o=Ue(i,Mn(a));i.assign(o);const l=Ue(se(Lt(a,qn(Ue(o,J.backend.epsilon()))),-this.learningRate),s);s.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&on(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),this.accumulatedGrads=e.map(t=>({originalName:t.name,variable:t.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}const Ar=ee({pow_:function(n,e){let t=P(n,"base","pow"),r=P(e,"exp","pow");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(bl,s)}}),ot=ee({sub_:function(n,e){let t=P(n,"a","sub"),r=P(e,"b","sub");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(Rl,s)}});class yd extends oi{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=[],be(()=>{this.accBeta1=Pt(t).variable(),this.accBeta2=Pt(r).variable()}),s==null&&(this.epsilon=J.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);be(()=>{const r=ot(1,this.accBeta1),s=ot(1,this.accBeta2);t.forEach((a,i)=>{const o=J.registeredVariables[a],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${a}/m`,variable:be(()=>mn(o).variable(l))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${a}/v`,variable:be(()=>mn(o).variable(l))});const p=Array.isArray(e)?e[i].tensor:e[a];if(p==null)return;const c=this.accumulatedFirstMoment[i].variable,h=this.accumulatedSecondMoment[i].variable,d=Ue(se(c,this.beta1),se(p,1-this.beta1)),m=Ue(se(h,this.beta2),se(Mn(p),1-this.beta2)),g=Lt(d,r),y=Lt(m,s);c.assign(d),h.assign(m);const w=Ue(se(Lt(g,Ue(qn(y),this.epsilon)),-this.learningRate),o);o.assign(w)}),this.accBeta1.assign(se(this.accBeta1,this.beta1)),this.accBeta2.assign(se(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&on(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&on(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}
vendor: 4,510 bytes, line 53
53)))}async setWeights(e){e=await this.extractIterations(e),be(()=>{this.accBeta1.assign(Ar(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ar(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,2*t).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)}}const An=ee({abs_:function(n){const e=P(n,"x","abs");if(e.dtype==="complex64"){const t={x:e};return J.runKernel(rl,t)}{const t={x:e};return J.runKernel(Yu,t)}}});function ys(n,e){const t=n.length,r=[];for(let s=0;s<t;s++){const a=t-1-s,i=n[a]||1;(e[e.length-1-s]||1)>1&&i===1&&r.unshift(a)}return r}function er(n,e){const t=[];for(let r=0;r<e.length;r++){const s=n[n.length-r-1],a=e.length-r-1,i=e[a];(s==null||s===1&&i>1)&&t.unshift(a)}return t}function Gt(n,e){const t=Math.max(n.length,e.length),r=new Array(t);for(let s=0;s<t;s++){let a=n[n.length-s-1];a==null&&(a=1);let i=e[e.length-s-1];if(i==null&&(i=1),a===1)r[t-s-1]=i;else if(i===1)r[t-s-1]=a;else{if(a!==i)throw Error(`Operands could not be broadcast together with shapes ${n} and ${e}.`);r[t-s-1]=a}}return r}const Nr=ee({maximum_:function(n,e){let t=P(n,"a","maximum"),r=P(e,"b","maximum");[t,r]=ar(t,r),t.dtype==="bool"&&(t=gt(t,"int32"),r=gt(r,"int32")),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(To,s)}});class nh extends oi{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=[],be(()=>{this.iteration=Pt(0).variable(),this.accBeta1=Pt(t).variable()}),s==null&&(this.epsilon=J.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);be(()=>{const r=ot(1,this.accBeta1),s=Lt(-this.learningRate,Ue(se(this.iteration,this.decay),1));t.forEach((a,i)=>{const o=J.registeredVariables[a],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${a}/m`,variable:mn(o).variable(l)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${a}/v`,variable:mn(o).variable(l)});const p=Array.isArray(e)?e[i].tensor:e[a];if(p==null)return;const c=this.accumulatedFirstMoment[i].variable,h=this.accumulatedWeightedInfNorm[i].variable,d=Ue(se(c,this.beta1),se(p,1-this.beta1)),m=se(h,this.beta2),g=An(p),y=Nr(m,g);c.assign(d),h.assign(y);const w=Ue(se(Lt(s,r),Lt(d,Ue(y,this.epsilon))),o);o.assign(w)}),this.iteration.assign(Ue(this.iteration,1)),this.accBeta1.assign(se(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&on(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&on(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)}}class Ul extends oi{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{const s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;const a=J.registeredVariables[t];be(()=>{const i=Ue(se(this.c,s),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=_r(Pt(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if((e=await this.extractIterations(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)}}class rh extends Ul{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=Pt(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>
53t.name):Object.keys(e)).forEach((t,r)=>{const s=J.registeredVariables[t];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${t}/momentum`,variable:be(()=>mn(s).variable(!1))});const a=this.accumulations[r].variable,i=Array.isArray(e)?e[r].tensor:e[t];i!=null&&be(()=>{let o;const l=Ue(se(this.m,a),i);o=this.useNesterov?Ue(se(this.c,Ue(i,se(l,this.m))),s):Ue(se(this.c,l),s),a.assign(l),s.assign(o)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&on(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),this.accumulations=e.map(t=>({originalName:t.name,variable:t.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class bd extends oi{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=J.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{const s=J.registeredVariables[t],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${t}/rms`,variable:be(()=>mn(s).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${t}/momentum`,variable:be(()=>mn(s).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${t}/mg`,variable:be(()=>mn(s).variable(a))});const i=Array.isArray(e)?e[r].tensor:e[t];if(i==null)return;const o=this.accumulatedMeanSquares[r].variable,l=this.accumulatedMoments[r].variable;be(()=>{const p=Ue(se(o,this.decay),se(Mn(i),1-this.decay));if(this.centered){const c=this.accumulatedMeanGrads[r].variable,h=Ue(se(c,this.decay),se(i,1-this.decay)),d=Lt(se(i,this.learningRate),qn(ot(p,Ue(Mn(h),this.epsilon)))),m=Ue(se(l,this.momentum),d);o.assign(p),c.assign(h),l.assign(m);const g=ot(s,m);s.assign(g)}else{const c=Ue(se(o,this.decay),se(Mn(i),1-this.decay)),h=Ue(se(l,this.momentum),Lt(se(i,this.learningRate),qn(Ue(c,this.epsilon))));o.assign(c),l.assign(h);const d=ot(s,h);s.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&on(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&on(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&on(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,2*t).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).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)}}const Lp=[aa,gd,yd,nh,rh,bd,Ul];function xd(n){return new Promise(e=>setTimeout(e)).then(n)}class Go{constructor(e){if(!xe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Go.URL_SCHEME)&&(e=e.slice(Go.URL_SCHEME.length)),e!=null&&e.length!==0||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}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=xa.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=Yc(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),a=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),i=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(i.download=this.modelJsonFileName,i.href=a,await xd(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=r,await xd(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ml(e)}}}}Go.URL_SCHEME="downloads://";class zp{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)=>
53{const r=new FileReader;r.onload=s=>{const a=JSON.parse(s.target.result),i=a.modelTopology;if(i==null)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(a.weightsManifest==null)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(this.weightsFiles.length===0)return void e({modelTopology:i});const o=cd(a,l=>this.loadWeights(l));e(o)},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 i of e)t.push(...i.weights),r.push(...i.paths);const s=this.checkManifestAndWeightFiles(e),a=r.map(i=>this.loadWeightsFile(i,s[i]));return Promise.all(a).then(i=>[t,i])}loadWeightsFile(e,t){return new Promise((r,s)=>{const a=new FileReader;a.onload=i=>{const o=i.target.result;r(o)},a.onerror=i=>s(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],r=this.weightsFiles.map(a=>Rp(a.name)),s={};for(const a of e)a.paths.forEach(i=>{const o=Rp(i);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),r.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[i]=this.weightsFiles[r.indexOf(o)]});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}}function Sm(n){return new zp(n)}function Pp(n,e,t,r){(function(a){A(a!=null&&Array.isArray(a)&&a.length>0,()=>"promises must be a none empty array")})(n),function(a,i){A(a>=0&&a<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${a}`),A(i>=0&&i<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${i}`),A(i>=a,()=>`startFraction must be no more than endFraction, but got startFraction ${a} and endFraction ${i}`)}(t=t??0,r=r??1);let s=0;return Promise.all(n.map(a=>(a.then(i=>{const o=t+ ++s/n.length*(r-t);return e(o),i}),a)))}async function Bp(n,e){e==null&&(e={});const t=e.fetchFunc==null?xe().platform.fetch:e.fetchFunc,r=n.map(a=>t(a,e.requestInit,{isBinary:!0})),s=(e.onProgress==null?await Promise.all(r):await Pp(r,e.onProgress,0,.5)).map(a=>a.arrayBuffer());return e.onProgress==null?await Promise.all(s):await Pp(s,e.onProgress,.5,1)}async function dr(n,e="",t,r){return ka(s=>Bp(s,{requestInit:r}))(n,e,t)}function ka(n){return async(e,t="",r)=>{const s=e.map(()=>!1),a={},i=r!=null?r.map(()=>!1):[],o=[];if(e.forEach((m,g)=>{let y=0;m.weights.forEach(w=>{const v="quantization"in w?w.quantization.dtype:w.dtype,N=ba[v]*j(w.shape),T=()=>{s[g]=!0,a[g]==null&&(a[g]=[]),a[g].push({manifestEntry:w,groupOffset:y,sizeBytes:N})};r!=null?r.forEach(($,_)=>{$===w.name&&(T(),i[_]=!0)}):T(),o.push(w.name),y+=N})}),!i.every(m=>m)){const m=r.filter((g,y)=>!i[y]);throw new Error(`Could not find weights in manifest with names: ${m.join(", ")}. 
54Manifest JSON has weights with names: ${o.join(", ")}.`)}const l=s.reduce((m,g,y)=>(g&&m.push(y),m),[]),p=[];l.forEach(m=>{e[m].paths.forEach(g=>{const y=t+(t.endsWith("/")?"":"/")+g;p.push(y)})});const c=await n(p),h={};let d=0;return l.forEach(m=>{const g=e[m].paths.length,y=new xa(c.slice(d,d+g));a[m].forEach(w=>{const v=od(y.slice(w.groupOffset,w.groupOffset+w.sizeBytes),[w.manifestEntry]);for(const N in v)h[N]=v[N]}),d+=g}),h}}hr.registerSaveRouter(n=>xe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Go.URL_SCHEME)?function(e="model"){return new Go(e)}(n.slice(Go.URL_SCHEME.length)):null);class sh{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(A(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=xe().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(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=Yc(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),e.weightData!=null){const a=xa.join(e.weightData);t.body.append("model.weights.bin",new Blob([a],{type:"application/octet-stream"}),"model.weights.bin")}const s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Ml(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.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 i=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?i+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":i+=" Please make sure the server is serving valid JSON for this request.",new Error(i)}const r=t.modelTopology,s=t.weightsManifest;if(r==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path}
54 contains neither model topology or manifest for weights.`);return t}async load(){return this.loadOptions.streamWeights?this.loadStream():cd(await this.loadModelJSON(),e=>this.loadWeights(e))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),r=Cu(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:r,getWeightStream:()=>function(s,a){var i;const o=a.fetchFunc==null?xe().platform.fetch:a.fetchFunc;let l,p=0;return(i=a.onProgress)===null||i===void 0||i.call(a,0),new ReadableStream({pull:async c=>{for(var h;p<s.length;){l||(l=(await o(s[p],a.requestInit,{isBinary:!0})).body.getReader());const{done:d,value:m}=await l.read();if(!d)return void c.enqueue(m);p++,l=void 0,(h=a.onProgress)===null||h===void 0||h.call(a,p/s.length)}c.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[r,s]=function(l){const p=l.lastIndexOf("/"),c=l.lastIndexOf("?");return[l.substring(0,p)+"/",c>p?l.substring(c):""]}(t),a=this.weightPathPrefix||r,i=[],o=[];for(const l of e)for(const p of l.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(p)):i.push(a+p+s);return this.weightUrlConverter&&i.push(...await Promise.all(o)),i}async loadWeights(e){const t=await this.getWeightUrls(e);return[Cu(e),await Bp(t,this.loadOptions)]}}function wd(n){return n.match(sh.URL_SCHEME_REGEX)!=null}sh.URL_SCHEME_REGEX=/^https?:\/\//;const Vp=(n,e)=>{if(typeof fetch>"u"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(t=Array.isArray(n)?n.every(r=>wd(r)):wd(n),t)return vd(n,e)}return null};function vd(n,e){return new sh(n,e)}function As(n,e){return vd(n,e)}hr.registerSaveRouter(Vp),hr.registerLoadRouter(Vp);class kd{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class Rs{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class Tm{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Em(n,e,t,r){return new Tm(ah(...arguments))}function ah(n,e,t,r){return arguments.length===1?n.modelTopology!=null||n.weightSpecs!=null?new kd(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 kd({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 kd({modelTopology:n,weightSpecs:e,weightData:t,trainingConfig:r}))}function Nd(n){return new Rs(n)}function ir(n){return new Rs(n)}const Yt=ee({matMul_:function(n,e,t=!1,r=!1){let s=P(n,"a","matMul"),a=P(e,"b","matMul");[s,a]=ar(s,a);const i={a:s,b:a},o={transposeA:t,transposeB:r};return J.runKernel(yo,i,o)}}),Ur=ee({oneHot_:function(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 a={indices:P(n,"indices","oneHot","int32")},i={dtype:s,depth:e,onValue:t,offValue:r};return J.runKernel(ou,a,i)}}),Ho=ee({imag_:function(n){const e={input:P(n,"input","imag")};return J.runKernel(Ei,e)}}),Vn=ee({neg_:function(n){const e={x:P(n,"x","neg")};return J.runKernel(Co,e)}}),Au=ee({real_:function(n){const e={input:P(n,"input","real")};return J.runKernel(xl,e)}}),Qt=ee({transpose_:function(n,e,t){const r=P(n,"x","transpose");if(e==null&&(e=r.shape.map((i,o)=>o).reverse()),A(r.rank===e.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${e}.`),e.forEach(i=>{A(i>=0&&i<r.rank,()=>"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"?be(()=>{let i=Au(r),o=Ho(r);return i=J.runKernel(Oo,{x:i},a),o=J.runKernel(Oo,{x:o},a),t&&(o=Vn(o)),Gi(i,o)}):J.runKernel(Oo,s,a)}}),Id=ee({confusionMatrix_:function(n,e,t){const r=P(n,"labels","confusionMatrix"),s=P(e,"predictions","confusionMatrix");A(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),A(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),A(s.rank===1,()=>`Expected the rank of predictions to be 1, but got ${s.rank}
54`),A(r.shape[0]===s.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`),A(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);const a=Ur(gt(r,"int32"),t),i=Ur(gt(s,"int32"),t),o=Qt(a),l=Yt(o,i);return gt(l,"int32")}});function Up(n,e,t){if(Ve(n),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=ya(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 Hi(n,e,r,t)}let Na,ih=!1;function Wp(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,i=!1,o=!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)i=!0;else{if(!(typeof ImageBitmap<"u"&&n instanceof ImageBitmap))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}`);o=!0}if(En(_l,J.backendName)!=null){const d={pixels:n},m={numChannels:e};return J.runKernel(_l,d,m)}const[l,p]=s?[n.videoWidth,n.videoHeight]:[n.width,n.height];let c,h;if(i)c=n.getContext("2d").getImageData(0,0,l,p).data;else if(r||t)c=n.data;else if(a||s||o){if(Na==null)if(typeof document>"u"){if(typeof OffscreenCanvas>"u"||typeof OffscreenCanvasRenderingContext2D>"u")throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Na=new OffscreenCanvas(1,1).getContext("2d")}else Na=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Na.canvas.width=l,Na.canvas.height=p,Na.drawImage(n,0,0,l,p),c=Na.getImageData(0,0,l,p).data}if(e===4)h=new Int32Array(c);else{const d=l*p;h=new Int32Array(d*e);for(let m=0;m<d;m++)for(let g=0;g<e;++g)h[m*e+g]=c[4*m+g]}return Up(h,[p,l,e],"int32")}async function Cm(n,e=3){let t=null;if(xe().getBool("WRAP_TO_IMAGEBITMAP")&&function(r){return typeof window<"u"&&typeof ImageBitmap<"u"&&window.hasOwnProperty("createImageBitmap")&&!(r instanceof ImageBitmap)&&function(s){return s!=null&&s.width!==0&&s.height!==0}(r)&&!function(s){return s!=null&&s.data instanceof Uint8Array}(r)}(n)){let r;try{r=await createImageBitmap(n,{premultiplyAlpha:"none"})}catch{r=null}t=r!=null&&r.width===n.width&&r.height===n.height?r:n}else t=n;return Wp(t,e)}function Sd(n){if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const e=n.rank===2?1:n.shape[2];if(e>4||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 $m(n,e){let t=P(n,"img","toPixels");if(!(n instanceof Sn)){const p=t;t=gt(p,"int32"),p.dispose()}Sd(t);const[r,s]=t.shape.slice(0,2),a=t.rank===2?1:t.shape[2],i=await t.data(),o=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(s*r*4);for(let p=0;p<r*s;++p){const c=[0,0,0,255];for(let d=0;d<a;d++){const m=i[p*a+d];if(t.dtype==="float32"){if(m<0||m>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${m}.`)}else if(t.dtype==="int32"&&(m<0||m>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${m}.`);a===1?(c[0]=m*o,c[1]=m*o,c[2]=m*o):c[d]=m*o}const h=4*p;l[h+0]=Math.round(c[0]),l[h+1]=Math.round(c[1]),l[h+2]=Math.round(c[2]),l[h+3]=Math.round(c[3])}if(e!=null){ih||En(Si,J.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),ih=!0),e.width=s,e.height=r;const p=e.getContext("2d"),c=new ImageData(l,s,r);p.putImageData(c,0,0)}return t!==n&&t.dispose(),l}function Dy(n,e,t){let r=P(n,"img","draw");if(!(n instanceof Sn)){const i=r;r=gt(i,"int32"),i.dispose()}Sd(r),function(i){const o=i?.alpha||1;if(o>1||o<0)throw new Error(`Alpha value ${o} is suppoed to be in range [0 - 1].`)}(t?.imageOptions);const s={image:r},a={canvas:e,options:t};J.runKernel(Si,s,a)}const Gp=ee({fromPixels_:Wp});function Wl(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(j(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 i=1;for(let h=0;h<s.length-1;++h)i*=s[h];const o=n.shape,l=s.slice();l.pop();let p=1;for(let h=a;h<t;++h)p*=o[h],l.push(o[h]);const c=[...Ge(n.shape).map(h=>h/p),1].slice(0,a);return[l,i,p,c]}function Td(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.rank<s)throw new Error(a+` update.rank < ${s}. `);
54if(n.length<r+(t.rank-s))throw new Error(a+` Output shape length < ${r+(t.rank-s)}`);if(t.rank!==s+n.length-r)throw new Error(a+" update.rank != "+(s+n.length-r));for(let i=0;i<s;++i)if(t.shape[i]!==e.shape[i])throw new Error(a+` updates.shape[${i}] (${t.shape[i]}) != indices.shape[${i}] (${e.shape[i]}).`);for(let i=0;i<t.rank-s;++i)if(t.shape[i+s]!==n[i+r])throw new Error(a+` updates.shape[${i+s}] (${t.shape[i+s]}) != shape[${i+s}] (${n[i+s]})`)}function Vs(n,e,t){if(e.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${e.rank}.`);if(n.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${n.rank}.`);if(e.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);if(t.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t}`);if(t.length===0){if(e.size===0)throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);if(n.size===0)throw new Error(`Updates specified for empty output. updates shape: ${n.shape}`)}Td(t,e,n)}function Dr(n,e,t){const r=e.shape.length,s=r>1?e.shape[r-1]:1,a=t.length;let i=1;for(let l=s;l<a;++l)i*=t[l];const o=s<1?1:s;return{sliceRank:s,numUpdates:j(e.shape)/o,sliceSize:i,strides:[...Ge(t.slice(0,s)),1],outputSize:j(t)}}const oh=-2,Am=-1;function Ed(n,e,t){const r=n.shape.length;A(r===e.length,()=>`Error in slice${r}D: Length of begin ${e} must match the rank of the array (${r}).`),A(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<r;++s)A(e[s]+t[s]<=n.shape[s],()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${e[s]+t[s]}) would overflow input.shape[${s}] (${n.shape[s]})`)}function Us(n){const e=[];let t=0;for(;n>0;)1&n&&e.push(t),n/=2,t++;return e}function u(n,e,t){const r=[];for(let s=0;s<n.length;s++)r[s]=Math.ceil((e[s]-n[s])/t[s]);return r}function f(n,e,t,r){const s=[...n];for(let a=s.length;a<r.length;a++)s.push(1);for(let a=0;a<t;a++)a===0?s[e]=1:(s.splice(e,0,1),s.pop());return s}function x(n,e,t){return t<=n?t:t-(e-1)}function I(n,e){const t=[];for(let r=0;r<n;r++)t.push(e+r);return t}function C(n,e,t,r,s,a,i,o,l){const p=n.length;let c=new Array(p),h=new Array(p),d=new Array(p);if(e.length&&t>0){const m=e[0],g=t+1;c=D(i,m,g,r,n),h=W(o,m,g,s,n),d=f(a,m,g,n)}else for(let m=0;m<p;m++)c[m]=re(i,r,a,n,m,l),h[m]=ut(o,s,a,n,m,l),d[m]=fe(a,m,l);return{begin:c,end:h,strides:d}}function D(n,e,t,r,s){const a=[...s],i=I(t,e);for(let o=0;o<a.length;o++)if(i.indexOf(o)>-1)a[o]=0;else{const l=x(e,t,o);let p=r[l];n&1<<l&&(p=0),a[o]=p}return a}function W(n,e,t,r,s){const a=[...s],i=I(t,e);for(let o=0;o<a.length;o++)if(i.indexOf(o)>-1)a[o]=Number.MAX_SAFE_INTEGER;else{const l=x(e,t,o);let p=r[l];n&1<<l&&(p=Number.MAX_SAFE_INTEGER),a[o]=p}for(let o=0;o<a.length;o++){const l=s[o];a[o]<0&&(a[o]+=l),a[o]=te(0,a[o],s[o])}return a}function fe(n,e,t){let r=n[e];return(t&1<<e||r==null)&&(r=1),r}function re(n,e,t,r,s,a){let i=e[s];const o=t[s]||1;(n&1<<s||a&1<<s||i==null)&&(i=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=r[s];return i<0&&(i+=l),i=te(0,i,l-1),i}function ut(n,e,t,r,s,a){let i=e[s];const o=t[s]||1;(n&1<<s||a&1<<s||i==null)&&(i=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=r[s];return i<0&&(i+=l),i=o>0?te(0,i,l):te(-1,i,l-1),i}function qt(n,e,t){let r=t.length;for(let s=0;s<t.length;s++)if(t[s]>1){r=s;break}for(let s=r+1;s<t.length;s++)if(e[s]>0||t[s]!==n[s])return!1;return!0}function un(n,e){let t=n.length>0?n[n.length-1]:1;for(let r=0;r<n.length-1;r++)t+=n[r]*e[r];return t}function rn(n,e,t){let r;const s=n.shape.length;let a;return r=typeof e=="number"?[e,...new Array(s-1).fill(0)]:e.length<s?e.concat(new Array(s-e.length).fill(0)):e.slice(),r.forEach(i=>{A(i!==-1,()=>"slice() does not support negative begin indexing.")}),a=t==null?new Array(s).fill(-1):typeof t=="number"?[t,...new Array(s-1).fill(-1)]:t.length<s?t.concat(new Array(s-t.length).fill(-1)):t,a=a.map((i,o)=>i>=0?i:(A(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),n.shape[o]-r[o])),[r,a]}function pr(n,e,t,r,s,a,i,o,l){let p;if(r==null?(p=new Array(e.length),p.fill(1)):p=r,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:p.length,numAddAxisAfterEllipsis:0,begin:e.slice(),end:t.slice(),strides:p.slice(),beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let N=0;N<h.dims;
54N++)c&&1<<N&o&&h.numAddAxisAfterEllipsis++,1<<N&i&&(c=!0);c||(h.ellipsisMask|=1<<h.dims,h.dims++);const d={dims:n.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};(function(N,T){T.beginMask=0,T.endMask=0,T.shrinkAxisMask=0;let $=0;T.beginValid=N.begin!=null,T.endValid=N.end!=null,T.begin=new Array(T.dims),T.end=new Array(T.dims),T.strides=new Array(T.dims),T.finalShapeGatherIndices=[],T.finalShapeGatherIndicesSparse=[],T.inputShapeGatherIndicesSparse=new Array(T.dims);for(let _=0;_<N.dims;_++)if(1<<_&N.ellipsisMask){const L=Math.min(T.dims-(N.dims-_)+1+N.numAddAxisAfterEllipsis,T.dims);for(;$<L;$++)T.begin[$]=0,T.end[$]=0,T.strides[$]=1,T.beginMask|=1<<$,T.endMask|=1<<$,T.finalShapeGatherIndices.push($),T.finalShapeGatherIndicesSparse.push(-1),T.inputShapeGatherIndicesSparse[$]=_}else if(1<<_&N.newAxisMask)T.finalShapeGatherIndices.push(oh),T.finalShapeGatherIndicesSparse.push(-1);else{if($===T.begin.length)throw Error(`Index out of range using input dim ${$}; input has only ${T.dims} dims, ${T.begin.length}.`);N.begin!=null&&(T.begin[$]=N.begin[_]),N.end!=null&&(T.end[$]=N.end[_]),T.strides[$]=N.strides[_],N.beginMask&1<<_&&(T.beginMask|=1<<$),N.endMask&1<<_&&(T.endMask|=1<<$),N.shrinkAxisMask&1<<_?(T.finalShapeGatherIndices.push(Am),T.finalShapeGatherIndicesSparse.push(-1),T.shrinkAxisMask|=1<<$):(T.finalShapeGatherIndices.push($),T.finalShapeGatherIndicesSparse.push(_)),T.inputShapeGatherIndicesSparse[$]=_,$++}})(h,d);let m=!0,g=!0,y=!0;const w=[],v=[];for(let N=0;N<n.length;++N){if(d.strides[N]===0)throw Error(`strides[${N}] must be non-zero`);const T=!!(d.shrinkAxisMask&1<<N),$=n[N];if($===-1){w.push(T?1:-1);continue}const _=[d.beginMask&1<<N,d.endMask&1<<N],L=[d.strides[N]>0?0:-1,d.strides[N]>0?$:$-1];if(T&&d.strides[N]<=0)throw Error("only stride 1 allowed on non-range indexing.");y=y&&d.strides[N]===1;const z=!!(d.beginMask&1<<N&&d.endMask&1<<N);if(d.beginValid&&d.endValid){if(T){const X=d.begin[N]<0?$+d.begin[N]:d.begin[N];if(d.begin[N]=X,d.end[N]=d.begin[N]+1,X<0||X>=$)throw Error(`slice index ${d.begin[N]} of dimension ${N} out of bounds.`)}else d.begin[N]=br(d.begin[N],0,d.strides[N],$,_,L),d.end[N]=br(d.end[N],1,d.strides[N],$,_,L);const U=d.strides[N]===1&&d.begin[N]===0&&d.end[N]===$;m=m&&U,g=g&&(N===0&&d.strides[N]===1||U)}else m=m&&d.strides[N]===1&&z,g=g&&(N===0&&d.strides[N]===1||z);let O,V=!1;if(d.beginValid&&d.endValid?(O=d.end[N]-d.begin[N],V=!0):T?(O=1,V=!0):z&&$>=0&&(O=d.strides[N]<0?-$:$,V=!0),V){let U;U=O===0||O<0!=d.strides[N]<0?0:Math.trunc(O/d.strides[N])+(O%d.strides[N]!==0?1:0),w.push(U)}else w.push(-1)}for(let N=0;N<d.finalShapeGatherIndices.length;++N){const T=d.finalShapeGatherIndices[N];T>=0?v.push(w[T]):T===oh&&v.push(1)}return{finalShapeSparse:v.filter((N,T)=>d.finalShapeGatherIndices[T]!==oh),finalShape:v,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:d.begin,end:d.end,strides:d.strides}}function br(n,e,t,r,s,a){if(s[e])return t>0?a[e]:a[e+1&1];{const i=n<0?r+n:n;return i<a[0]?a[0]:i>a[1]?a[1]:i}}const tr=.001,Qi=.1;function Ji(n,e,t){return t==null&&(t=ui()),Ru(n,e,(r,s)=>Fy(r,s,t))}function ui(){return J.backend.floatPrecision()===32?tr:Qi}function Ru(n,e,t){let r=!0;if((lr(n)||lr(e))&&(r=!1),lr(n)&&lr(e)&&(r=!0),r){const i=n.constructor.name,o=e.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(n)&&Array.isArray(e)){const i=ya(n),o=ya(e);if(!le(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}const s=lr(n)?n:Ba(n),a=lr(e)?e:Ba(e);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.
55Actual:   ${s}.
56Expected: ${a}.`);for(let i=0;i<a.length;++i){const o=s[i],l=a[i];if(!t(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
57Actual:   ${s}.
58Expected: ${a}.`)}typeof expect<"u"&&expect().nothing()}function Cd(n,e){n().then(()=>e.fail(),()=>e()),typeof expect<"u"&&expect().nothing()}function uT(n,e){const t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return Qn(n)||Qn(n[0])||Qn(e)||Qn(e[0])?Ru(n,t,(r,s)=>r==s):Ru(n,e,(r,s)=>Fy(r,s,0))}function lT(n,e,t){if(t==null&&(t=ui()),!Fy(n,e,t))throw new Error(`Numbers differ: actual === ${n}, expected === ${e}`);typeof expect<"u"&&expect().nothing()}function Fy(n,e,t){return!isFinite(n)&&!isFinite(e)||!(isNaN(n)||isNaN(e)||Math.abs(n-e)>t)}function cT(n,e,t){for(let r=0;r<n.length;r++)if(n[r]<e||n[r]>t)throw new Error(`Value out of range:${n[r]} low: ${e}, high: ${t}`)}function hT(n,e){const t=new Float32Array(n),r=new Float32Array(e);if(t.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${t.length}`);for(let s=0;s<r.length;s++)if(t[s]!==r[s])throw new Error(`Expected ArrayBuffer value at ${s} to be ${r[s]} but got ${t[s]} instead`)}function Zx(n){for(let e=0;e<n.length;e++){const t=n[e];Array.isArray(t)?Zx(t):n[e]=dn(t)}return n}function dT(n){const e=document.createElement("video");
58return"playsInline"in e&&(e.playsInline=!0),e.muted=!0,e.loop=!0,e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.preload="auto",e.appendChild(n),new Promise(t=>{e.addEventListener("loadeddata",r=>t(e)),e.load()})}async function pT(n){await n.play(),"requestVideoFrameCallback"in n&&await new Promise(e=>{n.requestVideoFrameCallback(e)})}const Qx="4.22.0";class Jx{static sgd(e){return new Ul(e)}static momentum(e,t,r=!1){return new rh(e,t,r)}static rmsprop(e,t=.9,r=0,s=null,a=!1){return new bd(e,t,r,s,a)}static adam(e=.001,t=.9,r=.999,s=null){return new yd(e,t,r,s)}static adadelta(e=.001,t=.95,r=null){return new aa(e,t,r)}static adamax(e=.002,t=.9,r=.999,s=null,a=0){return new nh(e,t,r,s,a)}static adagrad(e,t=.1){return new gd(e,t)}}const My=ee({acos_:function(n){const e={x:P(n,"x","acos")};return J.runKernel(Da,e)}}),Oy=ee({acosh_:function(n){const e={x:P(n,"x","acosh")};return J.runKernel(Js,e)}}),ew=ee({addN_:function(n){A(Array.isArray(n),()=>"The argument passed to tf.addN() must be a list of tensors"),A(n.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${n.length}`);const e=n.map((s,a)=>P(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(!le(s.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=e;return J.runKernel(yc,r)}}),Rm=ee({all_:function(n,e=null,t=!1){const r={x:P(n,"x","all","bool")},s={axis:e,keepDims:t};return J.runKernel(bc,r,s)}}),Hp=ee({any_:function(n,e=null,t=!1){const r={x:P(n,"x","any","bool")},s={axis:e,keepDims:t};return J.runKernel(xi,r,s)}}),uh=ee({argMax_:function(n,e=0){const t={x:P(n,"x","argMax")},r={axis:e};return J.runKernel(Zu,t,r)}}),Ly=ee({argMin_:function(n,e=0){const t={x:P(n,"x","argMin")},r={axis:e};return J.runKernel(wi,t,r)}}),zy=ee({asin_:function(n){const e={x:P(n,"x","asin")};return J.runKernel(pa,e)}}),Py=ee({asinh_:function(n){const e={x:P(n,"x","asinh")};return J.runKernel(go,e)}}),By=ee({atan_:function(n){const e={x:P(n,"x","atan")};return J.runKernel(Za,e)}}),Vy=ee({atan2_:function(n,e){let t=P(n,"a","atan2"),r=P(e,"b","atan2");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(Jo,s)}}),Uy=ee({atanh_:function(n){const e={x:P(n,"x","atanh")};return J.runKernel(vi,e)}});function jp(n,e,t,r,s="NHWC",a){return is(n,[...e,n[3]],t,a,r,null,null,Du(s))}function li(n,e,t,r,s,a,i="channelsLast"){const[o,l]=Kp(e);let p;if(i==="channelsLast")p=[o,l,n[3],n[3]];else{if(i!=="channelsFirst")throw new Error(`Unknown dataFormat ${i}`);p=[o,l,n[1],n[1]]}return is(n,p,t,r,s,a,!1,i)}function _u(n,e,t,r,s,a,i="NDHWC"){const[o,l,p]=Gy(e);let c,h;if(i==="NDHWC")h="channelsLast",c=[o,l,p,n[4],n[4]];else{if(i!=="NCDHW")throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,l,p,n[1],n[1]]}return Gl(n,c,t,r,s,!1,h,a)}function is(n,e,t,r,s,a,i=!1,o="channelsLast"){let[l,p,c,h]=[-1,-1,-1,-1];if(o==="channelsLast")[l,p,c,h]=n;else{if(o!=="channelsFirst")throw new Error(`Unknown dataFormat ${o}`);[l,h,p,c]=n}const[d,m,,g]=e,[y,w]=Kp(t),[v,N]=Kp(r),T=$d(d,v),$=$d(m,N),{padInfo:_,outHeight:L,outWidth:z}=function(U,X,ne,ae,Ie,me,we,$e,ze){let We,Je,nt;if(typeof U=="number"){We={top:U,bottom:U,left:U,right:U,type:U===0?"VALID":"NUMBER"};const lt=function(dt,yt,xt,Ct,Rt){Ct==null&&(Ct=Wy(dt,yt,xt));const tn=dt[1];return[qp((dt[0]-yt+2*Ct)/xt+1,Rt),qp((tn-yt+2*Ct)/xt+1,Rt)]}([X,ne],me,ae,U,$e);Je=lt[0],nt=lt[1]}else if(U==="same"){Je=Math.ceil(X/ae),nt=Math.ceil(ne/Ie);const lt=Math.max(0,(Je-1)*ae+me-X),dt=Math.max(0,(nt-1)*Ie+we-ne),yt=Math.floor(lt/2),xt=lt-yt,Ct=Math.floor(dt/2);We={top:yt,bottom:xt,left:Ct,right:dt-Ct,type:"SAME"}}else if(U==="valid")We={top:0,bottom:0,left:0,right:0,type:"VALID"},Je=Math.ceil((X-me+1)/ae),nt=Math.ceil((ne-we+1)/Ie);else{if(typeof U!="object")throw Error(`Unknown padding parameter: ${U}`);{const lt=ze==="channelsLast"?U[1][0]:U[2][0],dt=ze==="channelsLast"?U[1][1]:U[2][1],yt=ze==="channelsLast"?U[2][0]:U[3][0],xt=ze==="channelsLast"?U[2][1]:U[3][1];We={top:lt,bottom:dt,left:yt,right:xt,type:lt===0&&dt===0&&yt===0&&xt===0?"VALID":"EXPLICIT"},Je=qp((X-me+lt+dt)/ae+1,$e),nt=qp((ne-we+yt+xt)/Ie+1,$e)}}return{padInfo:We,outHeight:Je,outWidth:nt}}(s,p,c,y,w,T,$,a,o),O=i?g*h:g;let V;return o==="channelsFirst"?V=[l,O,L,z]:o==="channelsLast"&&(V=[l,L,z,O]),{batchSize:l,dataFormat:o,inHeight:p,inWidth:c,inChannels:h,outHeight:L,outWidth:z,outChannels:O,padInfo:_,strideHeight:y,strideWidth:w,filterHeight:d,filterWidth:m,effectiveFilterHeight:T,effectiveFilterWidth:$,dilationHeight:v,dilationWidth:N,inShape:n,outShape:V,filterShape:e}}function Gl(n,e,t,r,s,a=!1,i="channelsLast",o){let[l,p,c,h,d]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,p,c,h,d]=n;else{if(i!=="channelsFirst")throw new Error(`Unknown dataFormat ${i}`);[l,d,p,c,h]=n}const[m,g,y,,w]=e,[v,N,T]=Gy(t),[$,_,L]=Gy(r),z=$d(m,$),O=$d(g,_),V=$d(y,L),{padInfo:U,outDepth:X,outHeight:ne,outWidth:ae}=function(we,$e,ze,We,Je,nt,lt,dt,yt,xt,Ct){let Rt,tn,nn,pn;if(we==="valid"&&(we=0),typeof we=="number"){Rt={top:we,bottom:we,left:we,right:we,front:we,back:we,type:we===0?"VALID":"NUMBER"};const Xt=function(vn,kn,Ln,Nn,wn,Gn){wn==null&&(wn=Wy(vn,kn[0],Nn[0]));const hs=[0,0,0,1];for(let Pr=0;Pr<3;Pr++)vn[Pr]+2*wn>=kn[Pr]&&(hs[Pr]=qp((vn[Pr]-kn[Pr]+2*wn)/Nn[Pr]+1,Gn));return hs}([$e,ze,We,1],[dt,yt,xt],0,[Je,nt,lt],we,Ct);tn=Xt[0],nn=Xt[1],pn=Xt[2]}else{if(we!=="same")throw Error(`Unknown padding parameter: ${we}`);{tn=Math.ceil($e/Je),nn=Math.ceil(ze/nt),pn=Math.ceil(We/lt);const Xt=(tn-1)*Je+dt-$e,vn=(nn-1)*nt+yt-ze,kn=(pn-1)*lt+xt-We,Ln=Math.floor(Xt/2),Nn=Xt-Ln,wn=Math.floor(vn/2),Gn=vn-wn,hs=Math.floor(kn/2);Rt={top:wn,bottom:Gn,left:hs,right:kn-hs,front:Ln,back:Nn,type:"SAME"}}}return{padInfo:Rt,outDepth:tn,outHeight:nn,outWidth:pn}}(s,p,c,h,v,N,T,z,O,V,o),Ie=a?w*d:w;let me;return i==="channelsFirst"?me=[l,Ie,X,ne,ae]:i==="channelsLast"&&(me=[l,X,ne,ae,Ie]),{batchSize:l,dataFormat:i,inDepth:p,inHeight:c,inWidth:h,inChannels:d,outDepth:X,outHeight:ne,outWidth:ae,outChannels:Ie,padInfo:U,strideDepth:v,strideHeight:N,strideWidth:T,filterDepth:m,filterHeight:g,filterWidth:y,effectiveFilterDepth:z,effectiveFilterHeight:O,effectiveFilterWidth:V,dilationDepth:$,dilationHeight:_,dilationWidth:L,inShape:n,outShape:me,filterShape:e}}function Wy(n,e,t,r=1){const s=$d(e,r);return Math.floor((n[0]*(t-1)-t+s)/2)}function Kp(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function Gy(n){return typeof n=="number"?[n,n,n]:n}function $d(n,e){return e<=1?n:n+(n-1)*(e-1)}function qp(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 Hl(n){const[e,t,r]=Kp(n);return e===1&&t===1&&r===1}function bs(n,e){return Hl(n)||Hl(e)}function lh(n){return Kp(n).every(e=>e>0)}function Du(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function Ws(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")A(ue(e),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);else{if(typeof e!="object")throw Error(`Error in ${n}: Unknown padding parameter: ${e}`);e.forEach(r=>{r.forEach(s=>{A(ue(s),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${s}.`)})})}}}const he=ee({reshape_:function(n,e){const t={x:P(n,"x","reshape","string_or_numeric")},r={shape:e};return J.runKernel(_o,t,r)}}),Xp=ee({avgPool_:function(n,e,t,r,s){const a=P(n,"x","avgPool","float32");A(bs(t,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '1'`);let i=a,o=!1;a.rank===3&&(o=!0,i=he(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}
58.`),Ws("avgPool",r,s);const l={x:i},p={filterSize:e,strides:t,pad:r,dimRoundingMode:s};let c=J.runKernel(xc,l,p);return c=gt(c,a.dtype),o?he(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Hy=ee({avgPool3d_:function(n,e,t,r,s,a="NDHWC"){const i=P(n,"x","avgPool3d","float32");let o=i,l=!1;i.rank===4&&(l=!0,o=he(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),A(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),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}'`),Ws("avgPool3d",r,s);const p={x:o},c={filterSize:e,strides:t,pad:r,dimRoundingMode:s,dataFormat:a};let h=J.runKernel(Qu,p,c);return h=gt(h,o.dtype),l?he(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),Fr=ee({concat_:function(n,e=0){A(n.length>=1,()=>"Pass at least one tensor to concat");const t=Fl(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
59          with dtype ${a.dtype}. `)}),t.length===1)return va(t[0]);const r=t,s={axis:e};return J.runKernel(tu,r,s)}}),eo=ee({sigmoid_:function(n){const e={x:P(n,"x","sigmoid","float32")};return J.runKernel(du,e)}}),Tn=ee({slice_:function(n,e,t){const r=P(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 J.runKernel(Lc,s,a)}}),jl=ee({tanh_:function(n){const e={x:P(n,"x","tanh","float32")};return J.runKernel(wu,e)}}),tw=ee({basicLSTMCell_:function(n,e,t,r,s,a){const i=P(n,"forgetBias","basicLSTMCell"),o=P(e,"lstmKernel","basicLSTMCell"),l=P(t,"lstmBias","basicLSTMCell"),p=P(r,"data","basicLSTMCell"),c=P(s,"c","basicLSTMCell"),h=P(a,"h","basicLSTMCell"),d=Fr([p,h],1),m=Yt(d,o),g=Ue(m,l),y=g.shape[0],w=g.shape[1]/4,v=[y,w],N=Tn(g,[0,0],v),T=Tn(g,[0,w],v),$=Tn(g,[0,2*w],v),_=Tn(g,[0,3*w],v),L=Ue(se(eo(N),jl(T)),se(c,eo(Ue(i,$))));return[L,se(jl(L),eo(_))]}}),Yp=ee({batchToSpaceND_:function(n,e,t){const r=P(n,"x","batchToSpaceND"),s=e.reduce((o,l)=>o*l);A(r.rank>=1+e.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${e.length}`),A(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length  ${e.length}`),A(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},i={blockShape:e,crops:t};return J.runKernel(el,a,i)}}),Ad=ee({batchNorm_:function(n,e,t,r,s,a){a==null&&(a=.001);const i=P(n,"x","batchNorm"),o=P(e,"mean","batchNorm"),l=P(t,"variance","batchNorm");let p,c;s!=null&&(p=P(s,"scale","batchNorm")),r!=null&&(c=P(r,"offset","batchNorm")),A(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(c==null||o.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h={x:function(g){let y;return y=g.rank===0||g.rank===1?he(g,[1,1,1,g.size]):g.rank===2?he(g,[1,1,g.shape[0],g.shape[1]]):g.rank===3?he(g,[1,g.shape[0],g.shape[1],g.shape[2]]):g,y}(i),scale:p,offset:c,mean:o,variance:l},d={varianceEpsilon:a},m=J.runKernel(hl,h,d);return he(m,i.shape)}}),jy=ee({batchNorm2d_:function(n,e,t,r,s,a){const i=P(n,"x","batchNorm"),o=P(e,"mean","batchNorm"),l=P(t,"variance","batchNorm");let p,c;return s!=null&&(p=P(s,"scale","batchNorm")),r!=null&&(c=P(r,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),c!=null&&A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ad(i,o,l,c,p,a)}}),Ky=ee({batchNorm3d_:function(n,e,t,r,s,a){const i=P(n,"x","batchNorm"),o=P(e,"mean","batchNorm"),l=P(t,"variance","batchNorm");let p,c;return s!=null&&(p=P(s,"scale","batchNorm")),r!=null&&(c=P(r,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}
59.`),A(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),c!=null&&A(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ad(i,o,l,c,p,a)}}),qy=ee({batchNorm4d_:function(n,e,t,r,s,a){const i=P(n,"x","batchNorm"),o=P(e,"mean","batchNorm"),l=P(t,"variance","batchNorm");let p,c;return s!=null&&(p=P(s,"scale","batchNorm")),r!=null&&(c=P(r,"offset","batchNorm")),A(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),A(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),c!=null&&A(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ad(i,o,l,c,p,a)}}),Xy=ee({bincount_:function(n,e,t){const r=P(n,"x","bincount"),s=P(e,"weights","bincount");A(r.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),A(t>=0,()=>`size must be non-negative, but got ${t}.`),A(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},i={size:t};return J.runKernel(eu,a,i)}}),nw=ee({bitwiseAnd_:function(n,e){const t=P(n,"x","bitwiseAnd"),r=P(e,"y","bitwiseAnd");if(!le(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 J.runKernel(ki,s)}}),rw=ee({broadcastArgs_:function(n,e){const t=P(n,"s0","broadcastArgs","int32"),r=P(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 J.runKernel(vc,s)}}),ch=ee({broadcastTo_:function(n,e){let t=P(n,"broadcastTo","x");const r=t.shape;if(ts(e),e.length<t.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);if(e.length>t.rank){const l=t.shape.slice();for(;l.length<e.length;)l.unshift(1);t=he(t,l)}const s=t.shape,a=Array.from(e);for(let l=e.length-1;l>=0;l--)if(s[l]===e[l])a[l]=1;else if(t.shape[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${e}].`);if(a.map((l,p)=>l>1?p:-1).filter(l=>l>=0).length===0)return va(t);const i={x:t},o={reps:a};return J.runKernel(vu,i,o)}}),Yy=ee({ceil_:function(n){const e={x:P(n,"x","ceil","float32")};return J.runKernel(nl,e)}}),ia=ee({clipByValue_:function(n,e,t){const r=P(n,"x","clipByValue");if(A(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`),e===t)return $u(r.shape,e,r.dtype);const s={x:r},a={clipValueMin:e,clipValueMax:t};return J.runKernel(bo,s,a)}}),Zy=ee({concat1d_:function(n){return Fr(n,0)}}),Qy=ee({concat2d_:function(n,e){return Fr(n,e)}}),Jy=ee({concat3d_:function(n,e){return Fr(n,e)}}),e0=ee({concat4d_:function(n,e){return Fr(n,e)}}),Fu=ee({conv2d_:function(n,e,t,r,s="NHWC",a=[1,1],i){const o=P(n,"x","conv2d","float32"),l=P(e,"filter","conv2d","float32");let p=o,c=!1;o.rank===3&&(c=!0,p=he(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Ws("conv2d",r,i);const h=s==="NHWC"?p.shape[3]:p.shape[1];A(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),A(bs(t,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),A(lh(a),()=>"Error in conv2D: Dilated rates should be larger than 0."),A(lh(t),()=>"Error in conv2D: Strides should be larger than 0.");
59const d={x:p,filter:l},m={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},g=J.runKernel(ds,d,m);return c?he(g,[g.shape[1],g.shape[2],g.shape[3]]):g}}),_m=ee({conv1d_:function(n,e,t,r,s="NWC",a=1,i){const o=P(n,"x","conv1d"),l=P(e,"filter","conv1d");let p=o,c=!1;o.rank===2&&(c=!0,p=he(o,[1,o.shape[0],o.shape[1]])),A(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Ws("conv1d",r,i),A(p.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(bs(t,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${a}'`),A(lh(a),()=>"Error in conv1D: Dilated rates should be larger than 0."),A(lh(t),()=>"Error in conv1D: Stride should be larger than 0."),A(s==="NWC",()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);const h=he(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=he(p,[p.shape[0],1,p.shape[1],p.shape[2]]),m=Fu(d,h,[1,t],r,"NHWC",[1,a],i);return he(m,c?[m.shape[2],m.shape[3]]:[m.shape[0],m.shape[2],m.shape[3]])}}),t0=ee({conv2DBackpropInput_:function(n,e,t,r,s,a="NHWC",i){A(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let o=n,l=e,p=!1;e.rank===3&&(p=!0,l=he(e,[1,e.shape[0],e.shape[1],e.shape[2]]),o=[1,n[0],n[1],n[2]]),A(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);const c=a==="NHWC"?o[3]:o[1],h=a==="NHWC"?l.shape[3]:l.shape[1];A(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),A(h===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${t.shape[3]}.`),Ws("conv2dDerInput",s,i);const d={dy:l,filter:t},m={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:o},g=J.runKernel(sl,d,m);return p?he(g,[g.shape[1],g.shape[2],g.shape[3]]):g}}),Dm=ee({conv2dTranspose_:function(n,e,t,r,s,a){const i=P(n,"x","conv2dTranspose"),o=P(e,"filter","conv2dTranspose");return t0(t,i,o,r,s,"NHWC",a)}}),n0=ee({conv3d_:function(n,e,t,r,s="NDHWC",a=[1,1,1]){const i=P(n,"x","conv3d"),o=P(e,"filter","conv3d");let l=i,p=!1;i.rank===4&&(p=!0,l=he(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),A(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),A(bs(t,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),A(s==="NDHWC",()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`),A(lh(a),()=>"Error in conv3D: Dilated rates should be larger than 0."),A(lh(t),()=>"Error in conv3D: Strides should be larger than 0.");const c={x:l,filter:o},h={strides:t,pad:r,dataFormat:s,dilations:a},d=J.runKernel(kc,c,h);return p?he(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),sw=ee({conv3DBackpropInput_:function(n,e,t,r,s){A(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let a=n,i=e,o=!1;e.rank===4&&(o=!0,i=he(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],p=i.shape[4];A(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),A(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),A(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),A(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),A(p===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[4]}.`);const c={dy:i,filter:t},h={pad:s,strides:r,inputShape:a},d=J.runKernel(Nc,c,h);return o?he(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),r0=ee({conv3dTranspose_:function(n,e,t,r,s){const a=P(n,"x","conv3dTranspose"),i=P(e,"filter","conv3dTranspose");return sw(t,a,i,r,s)}}),Zp=ee({cos_:function(n){const e={x:P(n,"x","cos","float32")};return J.runKernel(xo,e)}}),Fm=ee({cosh_:function(n){const e={x:P(n,"x","cosh","float32")};return J.runKernel(Ii,e)}}),Qp=ee({cumprod_:function(n,e=0,t=!1,r=!1){const s={x:P(n,"x","cumprod")},a={axis:e,exclusive:t,reverse:r};return J.runKernel(jh,s,a)}}
59),Mm=ee({cumsum_:function(n,e=0,t=!1,r=!1){const s={x:P(n,"x","cumsum")},a={axis:e,exclusive:t,reverse:r};return J.runKernel(nu,s,a)}}),s0=ee({denseBincount_:function(n,e,t,r=!1){const s=P(n,"x","denseBincount"),a=P(e,"weights","denseBincount");A(s.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`),A(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),A(t>=0,()=>`size must be non-negative, but got ${t}.`),A(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 i={x:s,weights:a},o={size:t,binaryOutput:r};return J.runKernel(il,i,o)}}),a0=ee({depthToSpace_:function(n,e,t="NHWC"){const r=P(n,"x","depthToSpace","float32"),s=t==="NHWC"?r.shape[1]:r.shape[2],a=t==="NHWC"?r.shape[2]:r.shape[3],i=t==="NHWC"?r.shape[3]:r.shape[1];A(e>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${e}`),A(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
60    ${s} and ${e}  for depthToSpace with input shape
61    ${r.shape}`),A(a*e>=0,()=>`Negative dimension size caused by overflow when multiplying
62    ${a} and ${e} for depthToSpace with input shape
63        ${r.shape}`),A(i%(e*e)===0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${i} for depthToSpace with input shape ${r.shape}`);const o={x:r},l={blockSize:e,dataFormat:t};return J.runKernel(Ic,o,l)}}),Rd=ee({depthwiseConv2d_:function(n,e,t,r,s="NHWC",a=[1,1],i){const o=P(n,"x","depthwiseConv2d","float32"),l=P(e,"filter","depthwiseConv2d","float32");let p=o,c=!1;o.rank===3&&(c=!0,p=he(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const h=s==="NHWC"?p.shape[3]:p.shape[1];A(h===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`),Ws("depthwiseConv2d",r,i);const d={x:p,filter:l},m={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},g=J.runKernel(wo,d,m);return c?he(g,[g.shape[1],g.shape[2],g.shape[3]]):g}}),aw=ee({diag_:function(n){const e={x:P(n,"x","diag")};return J.runKernel(Tc,e)}}),i0=ee({dilation2d_:function(n,e,t,r,s=[1,1],a="NHWC"){const i=P(n,"x","dilation2d"),o=P(e,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),A(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=i,p=!1;i.rank===3&&(l=he(i,[1,i.shape[0],i.shape[1],i.shape[2]]),p=!0),A(l.shape[3]===o.shape[2],()=>`Error in dilation2d:  input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);const c={x:l,filter:o},h={strides:t,pad:r,dilations:s},d=J.runKernel(Ms,c,h);return p?he(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),Ia=ee({equal_:function(n,e){let t=P(n,"a","equal","string_or_numeric"),r=P(e,"b","equal","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(ol,s)}}),os=ee({where_:function(n,e,t){const r=P(e,"a","where"),s=P(t,"b","where"),a=P(n,"condition","where","bool"),i=Gt(Gt(a.shape,r.shape),s.shape),o={condition:ch(a,i),t:ch(r,i),e:ch(s,i)};return J.runKernel(Il,o)}}),o0=ee({divNoNan_:function(n,e){let t=P(n,"a","div"),r=P(e,"b","div");[t,r]=ar(t,r);const s=Lt(t,r),a=mn(s),i=Ia(r,a);return os(i,a,s)}}),u0=ee({dot_:function(n,e){const t=P(n,"t1","dot"),r=P(e,"t2","dot");A(!(t.rank!==1&&t.rank!==2||r.rank!==1&&r.rank!==2),()=>`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(A(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),t.rank===1&&r.rank===1){const i=he(t,[1,-1]),o=he(r,[-1,1]),l=Yt(i,o);return he(l,[])}if(t.rank===1&&r.rank===2){const i=he(t,[1,-1]),o=he(r,[r.shape[0],r.shape[1]]),l=Yt(i,o);return he(l,[l.size])}if(t.rank===2&&r.rank===1){const i=he(r,[-1,1]),o=Yt(t,i);return he(o,[o.size])}{const i=he(r,[r.shape[0],r.shape[1]]);return Yt(t,i)}}}),hh=ee({einsum_:function(n,...e){const t=e.map((s,a)=>P(s,`tensors${a}`,"einsum")),r={equation:n};return J.runKernel(Ec,t,r)}}),_d=ee({elu_:function(n){const e={x:P(n,"x","elu","float32")};return J.runKernel(fa,e)}}),iw=ee({ensureShape_:function(n,e){const t=P(n,"x","ensureShape","string_or_numeric");if(!Y(t.shape,e))throw new Error(`EnsureShape: Shape of tensor ${t.shape} is not compatible with expected shape ${e}`);return n}}),Om=ee({erf_:function(n){let e=P(n,"x","erf");A(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=gt(e,"float32"));const t={x:e};return J.runKernel(ru,t)}});function l0(n,e){for(let t=0;t<n.length;++t)if(n[n.length-t-1]!==e-1-t)return!1;return!0}function ow(n,e,t){const r=n.length+e.length,s=[];let a=0,i=0;for(let o=0;o<r;o++)t.indexOf(o)===-1?s.push(n[a++]):s.push(e[i++]);return s}function us(n,e){const t=[],r=n.length;for(let s=0;s<r;s++)e.indexOf(s)===-1&&t.push(n[s]);return[t,e.map(s=>n[s])]}function Mr(n,e){return ow(n,e.map(t=>1),e)}function xs(n,e,t){A(l0(e,t),()=>`${n} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function Ir(n,e){if(l0(n,e))return null;const t=[];for(let r=0;r<e;++r)n.indexOf(r)===-1&&t.push(r);
63return n.forEach(r=>t.push(r)),t}function Kl(n){return n.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function Or(n,e){const t=[];for(let r=e-n;r<e;++r)t.push(r);return t}const Va=ee({max_:function(n,e=null,t=!1){const r={x:P(n,"x","max")},s={reductionIndices:e,keepDims:t};return J.runKernel(iu,r,s)}}),Dd=ee({min_:function(n,e=null,t=!1){const r={x:P(n,"x","min")},s={axis:e,keepDims:t};return J.runKernel(ml,r,s)}}),Dt=ee({sum_:function(n,e=null,t=!1){let r=P(n,"x","sum");r.dtype==="bool"&&(r=gt(r,"int32"));const s={x:r},a={axis:e,keepDims:t};return J.runKernel(La,s,a)}});function uw(n,e,t=null){if(n.rank===0)return An(n);if(n.rank!==1&&t===null)return uw(he(n,[-1]),e,t);if(n.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return Dt(An(n),t);if(e===1/0)return Va(An(n),t);if(e===-1/0)return Dd(An(n),t);if(e==="euclidean"||e===2)return qn(Dt(Ar(An(n),Pt(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return Va(Dt(An(n),t[0]),t[1]-1);if(e===1/0)return Va(Dt(An(n),t[1]),t[0]);if(e===-1/0)return Dd(Dt(An(n),t[1]),t[0]);if(e==="fro"||e==="euclidean")return qn(Dt(Mn(n),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}const Fd=ee({norm_:function(n,e="euclidean",t=null,r=!1){const s=uw(n=P(n,"x","norm"),e,t);let a=s.shape;if(r){const i=Oe(t,n.shape);a=Mr(s.shape,i)}return he(s,a)}}),c0=ee({euclideanNorm_:function(n,e=null,t=!1){return Fd(n,"euclidean",e,t)}}),oa=ee({exp_:function(n){const e={x:P(n,"x","exp")};return J.runKernel(Os,e)}}),ws=ee({expandDims_:function(n,e=0){const t=P(n,"x","expandDims","string_or_numeric");A(e<=t.rank,()=>"Axis must be <= rank of the tensor");const r={input:t},s={dim:e};return J.runKernel(ul,r,s)}}),h0=ee({expm1_:function(n){const e={x:P(n,"x","expm1")};return J.runKernel(vo,e)}}),Ua=ee({tile_:function(n,e){const t=P(n,"x","tile","string_or_numeric");A(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 J.runKernel(vu,r,s)}}),Lm=ee({eye_:function(n,e,t,r="float32"){e==null&&(e=n);const s=ln([n,e],r),a=n<=e?n:e;for(let o=0;o<a;++o)s.set(1,o,o);const i=he(s.toTensor(),[n,e]);if(t==null)return i;if(t.length===1)return Ua(ws(i,0),[t[0],1,1]);if(t.length===2)return Ua(ws(ws(i,0),0),[t[0],t[1],1,1]);if(t.length===3)return Ua(ws(ws(ws(i,0),0),0),[t[0],t[1],t[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t.length}D.`)}}),Md=ee({floor_:function(n){const e={x:P(n,"x","floor","float32")};return J.runKernel(ko,e)}}),Od=ee({gather_:function(n,e,t=0,r=0){const s={x:P(n,"x","gather"),indices:P(e,"indices","gather","int32")},a={axis:t,batchDims:r};return J.runKernel(xn,s,a)}}),Gs=ee({greater_:function(n,e){let t=P(n,"a","greater","string_or_numeric"),r=P(e,"b","greater","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(ea,s)}}),Mu=ee({greaterEqual_:function(n,e){let t=P(n,"a","greaterEqual","string_or_numeric"),r=P(e,"b","greaterEqual","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(Ht,s)}}),d0=ee({isFinite_:function(n){const e={x:P(n,"x","isFinite")};return J.runKernel(Ci,e)}}),p0=ee({isInf_:function(n){const e={x:P(n,"x","isInf")};return J.runKernel(ps,e)}}),f0=ee({isNaN_:function(n){const e={x:P(n,"x","isNaN")};return J.runKernel(ns,e)}}),Jp=ee({leakyRelu_:function(n,e=.2){const t={x:P(n,"x","leakyRelu")},r={alpha:e};return J.runKernel(rr,t,r)}}),Ld=ee({less_:function(n,e){let t=P(n,"a","less","string_or_numeric"),r=P(e,"b","less","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(Ls,s)}}),ql=ee({lessEqual_:function(n,e){let t=P(n,"a","lessEqual","string_or_numeric"),r=P(e,"b","lessEqual","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel($i,s)}});function lw(n,e,t){if(t<=0)throw new Error("The number of values should be positive.");const r={start:n,stop:e,num:t};return J.runKernel(ta,{},r)}const m0=ee({localResponseNormalization_:function(n,e=5,t=1,r=1,s=.5){const a=P(n,"x","localResponseNormalization");A(a.rank===4||a.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
64               rank ${a.rank}.`),A(ue(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let i=a,o=!1;a.rank===3&&(o=!0,i=he(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},p={depthRadius:e,bias:t,alpha:r,beta:s},c=J.runKernel(au,l,p);return o?he(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Sa=ee({log_:function(n){const e={x:P(n,"x","log","float32")};return J.runKernel(Ft,e)}}),ef=ee({log1p_:function(n){const e={x:P(n,"x","log1p")};return J.runKernel(Ai,e)}}),dh=ee({softplus_:function(n){const e={x:P(n,"x","softplus")};return J.runKernel(pu,e)}}),g0=ee({logSigmoid_:function(n){const e=P(n,"x","logSigmoid");return Br(t=>({value:Vn(dh(Vn(t))),gradFunc:r=>se(r,eo(Vn(t)))}))(e)}}),zm=ee({logSoftmax_:function(n,e=-1){const t=P(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 Br((s,a)=>{const i=Va(s,e,!0),o=ot(s,i),l=ot(gt(o,"float32"),Sa(Dt(oa(o),e,!0)));return a([l]),{value:l,gradFunc:(p,c)=>{const[h]=c,d=oa(h);return ot(p,se(Dt(p,e,!0),d))}}})(t)}}),tf=ee({logSumExp_:function(n,e=null,t=!1){const r=P(n,"x","logSumExp"),s=Oe(e,r.shape),a=Va(r,s,!0),i=ot(r,a),o=oa(i),l=Dt(o,s),p=Sa(l),c=Ue(he(a,p.shape),p);if(t){const h=Mr(c.shape,s);return he(c,h)}return c}}),ci=ee({logicalAnd_:function(n,e){const t=P(n,"a","logicalAnd","bool"),r=P(e,"b","logicalAnd","bool");Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(Io,s)}}),nf=ee({logicalNot_:function(n){const e={x:P(n,"x","logicalNot","bool")};return J.runKernel(dl,e)}}),Pm=ee({logicalOr_:function(n,e){const t=P(n,"a","logicalOr","bool"),r=P(e,"b","logicalOr","bool");Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(su,s)}}),y0=ee({logicalXor_:function(n,e){const t=P(n,"a","logicalXor","bool"),r=P(e,"b","logicalXor","bool");return Gt(t.shape,r.shape),ci(Pm(n,e),nf(ci(n,e)))}}),cw=2147483648,Bm=ee({searchSorted_:function(n,e,t="left"){const r=P(n,"sortedSequence","searchSorted"),s=P(e,"values","searchSorted"),a=r.shape[r.shape.length-1],i=s.shape[s.shape.length-1],o=he(r,[-1,a]),l=he(s,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(j(l.shape)>=cw)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=cw)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const p={sortedSequence:o,values:l},c={side:t};return J.runKernel(cu,p,c)}});function hw(n,e){return Bm(n,e,"left")}const rf=ee({maxPool_:function(n,e,t,r,s){const a=P(n,"x","maxPool");let i=a,o=!1;a.rank===3&&(o=!0,i=he(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}
64.`),A(bs(t,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '1'`),Ws("maxPool",r,s);const l={x:i},p={filterSize:e,strides:t,pad:r,dimRoundingMode:s},c=J.runKernel(Ac,l,p);return o?he(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),b0=ee({maxPool3d_:function(n,e=[1,1,1],t,r,s,a="NDHWC"){const i=P(n,"x","maxPool3d");let o=i,l=!1;i.rank===4&&(l=!0,o=he(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),A(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),Ws("maxPool3d",r,s);const p={x:o},c={filterSize:e,strides:t,pad:r,dimRoundingMode:s,dataFormat:a},h=J.runKernel(Oa,p,c);return l?he(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),dw=ee({maxPoolWithArgmax_:function(n,e,t,r,s=!1){const a={x:P(n,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:r,includeBatchInIndex:s},o=J.runKernel(_c,a,i);return{result:o[0],indexes:o[1]}}}),Sr=ee({mean_:function(n,e=null,t=!1){const r={x:P(n,"x","mean")},s={axis:e,keepDims:t};return J.runKernel(fl,r,s)}});function Wr(n,e="float32"){if(ts(n),e==="complex64"){const r=Wr(n,"float32"),s=Wr(n,"float32");return Gi(r,s)}const t=Er(j(n),e);return J.makeTensor(t,n,e)}function ua(n,e="float32"){if(ts(n),e==="complex64"){const r=ua(n,"float32"),s=Wr(n,"float32");return Gi(r,s)}const t=Ku(j(n),e);return J.makeTensor(t,n,e)}function pw(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=P(n,"x","meshgrid",n instanceof Sn?n.dtype:"float32");if(e===void 0)return[r];let s=P(e,"y","meshgrid",e instanceof Sn?e.dtype:"float32");const a=j(r.shape),i=j(s.shape);return t==="xy"?(r=he(r,[1,-1]),s=he(s,[-1,1]),[Yt(ua([i,1],r.dtype),r),Yt(s,ua([1,a],s.dtype))]):(r=he(r,[-1,1]),s=he(s,[1,-1]),[Yt(r,ua([1,i],r.dtype)),Yt(ua([a,1],s.dtype),s)])}const Xl=ee({minimum_:function(n,e){let t=P(n,"a","minimum"),r=P(e,"b","minimum");[t,r]=ar(t,r),t.dtype==="bool"&&(t=gt(t,"int32"),r=gt(r,"int32")),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(Ri,s)}}),x0=ee({mirrorPad_:function(n,e,t){A(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);const r=P(n,"x","mirrorPad");if(r.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(e.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${e.length}.`);const s=t==="reflect"?1:0;for(let o=0;o<r.rank;o++)A(e[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(e[o][0]>=0&&e[o][0]<=r.shape[o]-s&&e[o][1]>=0&&e[o][1]<=r.shape[o]-s,()=>`Padding in dimension ${o} cannot be greater than or equal to ${r.shape[o]-s} or less than 0 for input of shape ${r.shape}`);const a={paddings:e,mode:t},i={x:r};return J.runKernel(_i,i,a)}}),w0=ee({mod_:function(n,e){let t=P(n,"a","mod"),r=P(e,"b","mod");[t,r]=ar(t,r);const s={a:t,b:r};return J.runKernel(Eo,s)}}),sf=ee({moments_:function(n,e=null,t=!1){const r=Oe(e,(n=P(n,"x","moments")).shape),s=Sr(n,r,t);let a=s.shape;t||(a=Mr(s.shape,r));const i=Mn(ot(gt(n,"float32"),he(s,a)));return{mean:s,variance:Sr(i,r,t)}}}),fw=ee({multiRNNCell_:function(n,e,t,r){const s=P(e,"data","multiRNNCell"),a=Fl(t,"c","multiRNNCell"),i=Fl(r,"h","multiRNNCell");let o=s;const l=[];for(let h=0;h<n.length;h++){const d=n[h](o,a[h],i[h]);l.push(d[0]),l.push(d[1]),o=d[1]}const p=[],c=[];for(let h=0;h<l.length;h+=2)p.push(l[h]),c.push(l[h+1]);return[p,c]}}),mw=ee({multinomial_:function(n,e,t,r=!1){const s=P(n,"logits","multinomial"),a=s.size,i=s.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);t=t||Math.random();const o={logits:i===1?he(s,[1,-1]):s},l={numSamples:e,seed:t,normalized:r},p=J.runKernel(Dc,o,l);return i===1?he(p,[p.size]):p}}),ph=ee({notEqual_:function(n,e){let t=P(n,"a","notEqual","string_or_numeric"),r=P(e,"b","notEqual","string_or_numeric");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel($o,s)}}),Ta=ee({onesLike_:function(n){const e={x:P(n,"x","onesLike")};return J.runKernel(gl,e)}}
64),gw=ee({outerProduct_:function(n,e){const t=P(n,"v1","outerProduct"),r=P(e,"v2","outerProduct");A(t.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${r.rank}.`);const s=he(t,[-1,1]),a=he(r,[1,-1]);return Yt(s,a)}}),Ou=ee({pad_:function(n,e,t=0){const r=P(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 J.runKernel(yl,a,s)}}),yw=ee({pad1d_:function(n,e,t=0){return A(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Ou(n,[e],t)}}),bw=ee({pad2d_:function(n,e,t=0){return A(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ou(n,e,t)}}),xw=ee({pad3d_:function(n,e,t=0){return A(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."),Ou(n,e,t)}}),ww=ee({pad4d_:function(n,e,t=0){return A(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."),Ou(n,e,t)}}),af=ee({spaceToBatchND_:function(n,e,t){const r=P(n,"x","spaceToBatchND");A(r.rank>=1+e.length,()=>`input rank ${r.rank} should be > than [blockShape] ${e.length}`),A(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),A(r.shape.reduce((i,o,l)=>l>0&&l<=e.length?i&&(o+t[l-1][0]+t[l-1][1])%e[l-1]===0:i,!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 J.runKernel(Tl,s,a)}}),v0=ee({pool_:function(n,e,t,r,s,a,i){s==null&&(s=[1,1]),a==null&&(a=1),r===0&&(r="valid");const o=P(n,"x","maxPool");let l=o,p=!1;o.rank===3&&(p=!0,l=he(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(bs(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);const c=li(l.shape,e,a,s,r),h=[c.dilationHeight,c.dilationWidth];let d;d=r==="same"?function($,_){const L=$.map((V,U)=>V+(V-1)*(_[U]-1)).map(V=>V-1),z=L.map(V=>Math.floor(V/2)),O=L.map((V,U)=>V-z[U]);return L.map((V,U)=>[z[U],O[U]])}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const m=h[0]===1&&h[1]===1,[g,y]=function($,_,L){const z=L.map(ne=>ne[0]),O=L.map(ne=>ne[1]),V=$.concat(z,O),U=_.map((ne,ae)=>(ne-V[ae]%ne)%ne),X=O.map((ne,ae)=>ne+U[ae]);return[_.map((ne,ae)=>[z[ae],X[ae]]),_.map((ne,ae)=>[0,U[ae]])]}([c.inHeight,c.inWidth],h,d),w=m?r:"valid",v=m?l:af(l,h,g),N=(t==="avg"?()=>Xp(v,e,a,w,i):()=>rf(v,e,a,w,i))(),T=m?N:Yp(N,h,y);return p?he(T,[T.shape[1],T.shape[2],T.shape[3]]):T}}),of=ee({prelu_:function(n,e){const t={x:P(n,"x","prelu"),alpha:P(e,"alpha","prelu")};return J.runKernel(ti,t)}}),k0=ee({prod_:function(n,e=null,t=!1){let r=P(n,"x","prod");r.dtype==="bool"&&(r=gt(r,"int32"));const s={x:r},a={axis:e,keepDims:t};return J.runKernel(Fi,s,a)}}),vw=ee({raggedGather_:function(n,e,t,r){const s={paramsNestedSplits:n.map((o,l)=>P(o,`tensors${l}`,"raggedGather","int32")),paramsDenseValues:P(e,"paramsDenseValues","raggedGather"),indices:P(t,"indices","raggedGather","int32")},a={outputRaggedRank:r},i=J.runKernel(uu,s,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),kw=ee({raggedRange_:function(n,e,t){const r=P(n,"starts","raggedRange"),s={starts:r,limits:P(e,"limits","raggedRange",r.dtype),deltas:P(t,"deltas","raggedRange",r.dtype)},a=J.runKernel(Ao,s);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}}),Nw=ee({raggedTensorToTensor_:function(n,e,t,r,s){const a=P(n,"shape","raggedTensorToTensor","int32"),i=P(e,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:P(t,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:r.map((p,c)=>P(p,`tensors${c}`,"raggedTensorToTensor","int32"))},l={rowPartitionTypes:s};return J.runKernel(Mi,o,l)}}),Iw=ee({rand_:function(n,e,t){ts(n);const r=j(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")throw new Error(`Unknown data type ${t}`);s=new Uint8Array(r)}for(let a=0;a<r;a++)s[a]=e();return J.makeTensor(s,n,t)}});var zd=Z(391);class N0{constructor(e,t,r,s,a){this.mean=e,this.stdDev=t,this.dtype=r,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const i=a||Math.random();this.random=zd.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){const s=this.nextVal;return this.nextVal=NaN,s}let e,t,r=!1;for(;!r;){let s,a,i;do s=2*this.random()-1,a=2*this.random()-1,i=s*s+a*a;while(i>=1||i===0);const o=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*a*o,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 fT{constructor(e,t,r,s){this.alpha=e,this.beta=1/t,this.dtype=r;const a=s||Math.random();this.randu=zd.alea(a.toString()),this.randn=new N0(0,1,r,!1,this.randu()),this.d=e<1?e+.6666666666666666:e-.3333333333333333,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,r,s,a,i;for(;;){do s=this.randn.nextValue(),i=1+this.c*s;while(i<=0);if(i*=i*i,e=s*s,t=1-.331*e*e,r=.5*e+this.d*(1-i+Math.log(i)),a=this.randu(),a<t||Math.log(a)<r)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class mT{constructor(e=0,t=1,r,s){if(this.canReturnFloat=()=>this.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=zd.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}
64nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Sw=ee({randomGamma_:function(n,e,t=1,r="float32",s){if(ts(n),t==null&&(t=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);const a=new fT(e,t,r,s),i=ln(n,r);for(let o=0;o<i.values.length;o++)i.values[o]=a.nextValue();return i.toTensor()}}),Vm=ee({randomNormal_:function(n,e=0,t=1,r,s){if(ts(n),r!=null&&r==="bool")throw new Error(`Unsupported data type ${r}`);const a=new N0(e,t,r,!1,s),i=ln(n,r);for(let o=0;o<i.values.length;o++)i.values[o]=a.nextValue();return i.toTensor()}}),Tw=ee({randomStandardNormal_:function(n,e,t){if(e!=null&&e==="bool")throw new Error(`Unsupported data type ${e}`);return Vm(n,0,1,e,t)}}),Yl=ee({randomUniform_:function(n,e=0,t=1,r="float32",s){ts(n);const a=ln(n,r),i=new mT(e,t,null,s);for(let o=0;o<a.values.length;o++)a.values[o]=i.nextValue();return a.toTensor()}}),Ew=ee({randomUniformInt_:function(n,e,t,r){return Yl(n,e,t,"int32",r)}});function fh(n,e,t=1,r="float32"){if(t===0)throw new Error("Cannot have a step of zero");const s={start:n,stop:e,step:t,dtype:r};return J.runKernel(Ts,{},s)}const I0=ee({reciprocal_:function(n){const e={x:P(n,"x","reciprocal")};return J.runKernel(Ro,e)}}),to=ee({relu_:function(n){const e={x:P(n,"x","relu")};return J.runKernel(Oi,e)}}),Um=ee({relu6_:function(n){const e={x:P(n,"x","relu6")};return J.runKernel(Do,e)}}),Wa=ee({reverse_:function(n,e){const t={x:P(n,"x","reverse")},r={dims:e};return J.runKernel(Nl,t,r)}}),Cw=ee({reverse1d_:function(n){const e=P(n,"x","reverse");return A(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),Wa(e,0)}}),$w=ee({reverse2d_:function(n,e){const t=P(n,"x","reverse");return A(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),Wa(t,e)}}),Aw=ee({reverse3d_:function(n,e){const t=P(n,"x","reverse");return A(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),Wa(t,e)}}),Rw=ee({reverse4d_:function(n,e){const t=P(n,"x","reverse");return A(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),Wa(t,e)}}),Wm=ee({round_:function(n){const e={x:P(n,"x","round")};return J.runKernel(Fo,e)}}),Gm=ee({rsqrt_:function(n){const e={x:P(n,"x","rsqrt","float32")};return J.runKernel(lu,e)}}),Hm=ee({selu_:function(n){const e={x:P(n,"x","selu")};return J.runKernel(Sl,e)}}),jm=ee({separableConv2d_:function(n,e,t,r,s,a=[1,1],i="NHWC"){const o=P(n,"x","separableConv2d"),l=P(e,"depthwiseFilter","separableConv2d"),p=P(t,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(o.rank===3&&(h=!0,c=he(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${p.shape[0]}.`),A(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const d=l.shape[2],m=l.shape[3];A(p.shape[2]===d*m,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*m}, but got ${p.shape[2]}.`);const g=Rd(c,l,r,s,i,a),y=Fu(g,p,1,"valid",i);return h?he(y,[y.shape[1],y.shape[2],y.shape[3]]):y}}),_w=async function(n,e){const t=P(n,"x","setdiff1d"),r=P(e,"y","setdiff1d");A(t.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${r.dtype}).`),A(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),A(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);const s=await t.data(),a=await r.data(),i=new Set(a);let o=0;for(let c=0;c<s.length;c++)i.has(s[c])||o++;const l=new kr([o],t.dtype),p=new kr([o],"int32");for(let c=0,h=0;c<s.length;c++)i.has(s[c])||(l.values[h]=s[c],p.values[h]=c,h++);return[l.toTensor(),p.toTensor()]},S0=ee({sign_:function(n){const e={x:P(n,"x","sign")};return J.runKernel(hu,e)}}),Km=ee({sin_:function(n){const e={x:P(n,"x","sin","float32")};return J.runKernel(zi,e)}}),qm=ee({sinh_:function(n){const e={x:P(n,"x","sinh")};return J.runKernel(Mo,e)}}
64),uf=ee({slice1d_:function(n,e,t){const r=P(n,"x","slice1d");return A(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),Tn(r,[e],[t])}}),Xm=ee({slice2d_:function(n,e,t){const r=P(n,"x","slice2d");return A(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),Tn(r,e,t)}}),lf=ee({slice3d_:function(n,e,t){const r=P(n,"x","slice3d");return A(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),Tn(r,e,t)}}),Pd=ee({slice4d_:function(n,e,t){const r=P(n,"x","slice4d");return A(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),Tn(r,e,t)}}),cf=ee({softmax_:function(n,e=-1){const t=P(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 J.runKernel(mu,r,s)}}),hf=ee({fft_:function(n){A(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const e={input:n};return J.runKernel(ll,e)}}),Bd=ee({ifft_:function(n){A(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const e={input:n};return J.runKernel(ei,e)}}),Ym=ee({irfft_:function(n){const e=n.shape[n.shape.length-1],t=n.size/e;let r;if(e<=2){const s=he(n,[t,e]);r=Bd(s)}else{const s=[t,2*(e-1)],a=he(Au(n),[t,e]),i=he(Ho(n),[t,e]),o=Wa(Tn(a,[0,1],[t,e-2]),1),l=se(Wa(Tn(i,[0,1],[t,e-2]),1),Pt(-1)),p=Fr([a,o],1),c=Fr([i,l],1),h=he(Gi(p,c),[s[0],s[1]]);r=Bd(h)}if(r=Au(r),n.rank===3&&n.shape[0]!==0){const s=r,a=n.shape[0];r=he(r,[a,r.shape[0]/a,r.shape[1]]),s.dispose()}return r}}),la=ee({split_:function(n,e,t=0){const r={x:P(n,"x","split")},s={numOrSizeSplits:e,axis:t};return J.runKernel(El,r,s)}}),df=ee({rfft_:function(n,e){A(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&&e<t){const g=n.shape.map(w=>0),y=n.shape.map(w=>w);y[n.shape.length-1]=e,s=Tn(n,g,y),t=e}else if(e!=null&&e>t){const g=n.shape.map(y=>y);g[n.shape.length-1]=e-t,s=Fr([n,Wr(g)],n.shape.length-1),t=e}else s=n;const a=mn(s),i=he(Gi(s,a),[r,t]),o=hf(i),l=Math.floor(t/2)+1,p=Au(o),c=Ho(o),h=la(p,[l,t-l],p.shape.length-1),d=la(c,[l,t-l],c.shape.length-1),m=s.shape.slice();return m[s.shape.length-1]=l,he(Gi(h[0],d[0]),m)}}),Zm=ee({squaredDifference_:function(n,e){let t=P(n,"a","squaredDifference"),r=P(e,"b","squaredDifference");[t,r]=ar(t,r),Gt(t.shape,r.shape);const s={a:t,b:r};return J.runKernel(bu,s,{})}}),Zl=ee({squeeze_:function(n,e){const t=P(n,"x","squeeze","string_or_numeric");return he(t,je(t.shape,e).newShape)}}),Hs=ee({stack_:function(n,e=0){const t=Fl(n,"tensors","stack","string_or_numeric");A(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&A(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");const r=t,s={axis:e};return J.runKernel(Mc,r,s)}}),mh=ee({step_:function(n,e=0){const t={x:P(n,"x","step")},r={alpha:e};return J.runKernel(ra,t,r)}}),T0=ee({stridedSlice_:function(n,e,t,r,s=0,a=0,i=0,o=0,l=0){const p={x:P(n,"x","stridedSlice","string_or_numeric")},c={begin:e,end:t,strides:r,beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return J.runKernel(Pi,p,c)}}),E0=ee({tan_:function(n){const e={x:P(n,"x","tan","float32")};return J.runKernel(xu,e)}});function vs(n,e){Ve(n);const t=ya(n,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Hi(n,null,t,e)}function Ql(n,e,t){if(Ve(n),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=ya(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 Hi(n,e,r,t)}function Dw(n,e,t){if(Ve(n),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=ya(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 Hi(n,e,r,t)}function Fw(n,e,t){if(Ve(n),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=ya(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 Hi(n,e,r,t)}function Mw(n,e,t){if(Ve(n),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=ya(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 Hi(n,e=e||r,r,t)}const Ow=ee({tensorScatterUpdate_:function(n,e,t){const r=P(n,"tensor","tensorScatterupdate"),s=P(e,"
64indices","tensorScatterupdate","int32"),a=P(t,"updates","tensorScatterupdate");if(Vs(a,s,r.shape),r.dtype!==a.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${r.dtype} and ${a.dtype}.`);const i={tensor:r,indices:s,updates:a};return J.runKernel(Li,i,{})}}),C0=ee({topk_:function(n,e=1,t=!0){const r=P(n,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const s=r.shape[r.shape.length-1];if(e<0)throw new Error(`'k' passed to topk() must be >= 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},i={k:e,sorted:t},[o,l]=J.runKernel(Pc,a,i);return{values:o,indices:l}}}),Qm=ee({truncatedNormal_:function(n,e=0,t=1,r,s){if(ts(n),r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");const a=new N0(e,t,r,!0,s),i=ln(n,r);for(let o=0;o<i.values.length;o++)i.values[o]=a.nextValue();return i.toTensor()}}),$0=ee({unique_:function(n,e=0){const t=P(n,"x","unique","string_or_numeric");A(t.rank>0,()=>"The input tensor must be at least 1D");const r={x:t},s={axis:e},[a,i]=J.runKernel(Vc,r,s);return{values:a,indices:i}}}),Jm=ee({unsortedSegmentSum_:function(n,e,t){const r=P(n,"x","unsortedSegmentSum"),s=P(e,"segmentIds","unsortedSegmentSum","int32");A(ue(t),()=>"numSegments must be of dtype int");const a={x:r,segmentIds:s},i={numSegments:t};return J.runKernel(mr,a,i)}}),Ga=ee({unstack_:function(n,e=0){const t=P(n,"x","unstack","string_or_numeric");A(e>=-t.shape.length&&e<t.shape.length,()=>`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);const r={value:t},s={axis:e};return J.runKernel(na,r,s)}});function Lw(n,e){return Bm(n,e,"right")}function A0(n,e=!0,t,r){return J.makeVariable(n,e,t,r)}function eg(n,e){const t=[];for(let a=0;a<e.length;a++)e[a]&&t.push(a);const r=ln(n,"int32"),s=ln([t.length,n.length],"int32");for(let a=0;a<t.length;a++){const i=r.indexToLoc(t[a]),o=a*n.length;s.values.set(i,o)}return s.toTensor()}const R0=async function(n){const e=P(n,"condition","whereAsync","bool"),t=await e.data(),r=eg(e.shape,t);return n!==e&&e.dispose(),r},zw=async function(n,e,t){const r=P(n,"tensor","boolMask"),s=P(e,"mask","boolMask","bool"),a=t??0,i=s.rank,o=r.shape;A(i>0,()=>"mask cannot be scalar"),ge(o.slice(a,a+i),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let y=a;y<a+i;y++)l*=o[y];const p=o.slice(0,a).concat([l],o.slice(a+i)),c=he(r,p),h=he(s,[-1]),d=await R0(h),m=Zl(d,[1]),g=Od(c,m,a);return n!==r&&r.dispose(),e!==s&&s.dispose(),m.dispose(),c.dispose(),h.dispose(),d.dispose(),g},Pw=ee({movingAverage_:function(n,e,t,r,s=!0){const a=P(n,"v","movingAverage"),i=P(e,"x","movingAverage"),o=P(t,"decay","movingAverage");am(a,i),A(le(a.shape,i.shape),()=>"Shape mismatch in v and x");const l=Pt(1),p=ot(l,o);let c=se(ot(i,a),p);if(s){A(r!=null,()=>"When using zeroDebias: true, step is required.");const h=P(r,"step","movingAverage");c=Lt(c,ot(l,Ar(o,h)))}return Ue(a,c)}}),Bw=ee({scatterND_:function(n,e,t){ts(t);const r=P(n,"indices","scatterND","int32"),s=P(e,"updates","scatterND");Vs(s,r,t);const a={indices:r,updates:s},i={shape:t};return J.runKernel(Oc,a,i)}}),Vw=ee({sparseToDense_:function(n,e,t,r=0){ts(t);const s=P(n,"sparseIndices","sparseToDense","int32"),a=P(e,"sparseValues","sparseToDense","string_or_numeric"),i=P(r,"defaultValue","sparseToDense",a.dtype);(function(p,c,h,d){if(p.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${p.dtype}.`);if(p.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${p.shape}.`);const m=p.rank>0?p.shape[0]:1,g=p.rank>1?p.shape[1]:1;if(h.length!==g)throw new Error(`outputShape has incorrect number of elements:, ${h.length}, should be: ${g}.`);const y=c.size;if(c.rank!==0&&(c.rank!==1||y!==m))throw new Error(`sparseValues has incorrect shape ${c.shape}, should be [] or [${m}]`);if(c.dtype!==d.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")})(s,a,t,i);const o={sparseIndices:s,sparseValues:a,defaultValue:i},l={outputShape:t};return J.runKernel(yu,o,l)}}),Uw=ee({gatherND_:function(n,e){const t=P(e,"indices","gatherND","int32"),r={params:P(n,"x","gatherND","string_or_numeric"),indices:t};
64return J.runKernel($c,r)}}),_0=ee({dropout_:function(n,e,t,r){const s=P(n,"x","dropout");if(A(s.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`),A(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return n instanceof Sn?s.clone():s;const a=function(l,p){if(p==null)return l.shape.slice();if(le(l.shape,p))return p;if(l.shape.length===p.length){const c=[];for(let h=0;h<l.shape.length;h++)p[h]==null&&l.shape[h]!=null?c.push(l.shape[h]):c.push(p[h]);return c}return p}(s,t),i=1-e,o=Lt(Md(Ue(Yl(a,0,1,"float32",r),i)),i);return se(s,o)}});function D0(n){return Math.floor(Math.pow(2,Math.ceil(Math.log(n)/Math.log(2))))}function tg(n,e,t){const r=1-n%2,s=new Float32Array(n);for(let a=0;a<n;++a){const i=2*Math.PI*a/(n+r-1);s[a]=e-t*Math.cos(i)}return vs(s,"float32")}const Ww=async function(n,e,t=1){const r=P(n,"predictions","inTopK"),s=P(e,"targets","inTopK");A(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),A(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}`),ge(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];A(t>0&&t<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${t}`);const i=await r.data(),o=await s.data(),[l,p]=[i.length/a,a],c=_t("bool",l);for(let h=0;h<l;h++){const d=h*p,m=i.subarray(d,d+p),g=[];for(let y=0;y<m.length;y++)g.push({value:m[y],index:y});g.sort((y,w)=>w.value-y.value),c[h]=0;for(let y=0;y<t;y++)if(g[y].index===o[h]){c[h]=1;break}}return n!==r&&r.dispose(),e!==s&&s.dispose(),Bs(c,s.shape,"bool")},F0=ee({conv2DBackpropFilter_:function(n,e,t,r,s,a="NHWC",i){let o=n;n.rank===3&&(o=he(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=he(e,[1,e.shape[0],e.shape[1],e.shape[2]])),A(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);const p=a==="NHWC"?o.shape[3]:o.shape[1],c=a==="NHWC"?l.shape[3]:l.shape[1];A(p===t[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${t[2]}.`),A(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),Ws("conv2dDerFilter",s,i);const h={x:o,dy:l},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:t};return J.runKernel(Gh,h,d)}});function ng(n,e,t){if(t==null||t==="linear")return n;if(t==="relu")return se(n,mh(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function rg(n,e){let t=e;const r=er(n.shape,e.shape);return r.length>0&&(t=Dt(t,r)),he(t,n.shape)}function sg(n,e,t,r){if(e==="linear")return n;if(e==="relu")return to(n);if(e==="elu")return _d(n);if(e==="relu6")return Um(n);if(e==="prelu")return of(n,t);if(e==="leakyrelu")return Jp(n,r);if(e==="sigmoid")return eo(n);throw new Error(`Unknown fused activation ${e}.`)}const ag=(n,e)=>!(n>0)||e==="linear",Gw=ee({fusedConv2d_:function({x:n,filter:e,strides:t,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:p,leakyreluAlpha:c}){if(l=l||"linear",ag(J.state.gradientDepth,l)===!1){A(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 L=Fu(n,e,t,r,s,a,i);return o!=null&&(L=Ue(L,o)),sg(L,l,p,c)}const h=P(n,"x","conv2d","float32"),d=P(e,"filter","conv2d","float32");let m=h,g=!1;h.rank===3&&(g=!0,m=he(h,[1,h.shape[0],h.shape[1],h.shape[2]])),A(m.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${m.rank}.`),A(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),Ws("fused conv2d",r,i);const y=s==="NHWC"?m.shape[3]:m.shape[1];A(d.shape[2]===y,()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${d.shape[2]}.`),A(bs(t,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);const w=is(m.shape,d.shape,t,a,r,i);let v,N;if(o!=null&&(v=P(o,"bias","fused conv2d"),[v]=ar(v,h),s==="NHWC"?Gt(w.outShape,v.shape):(A(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}.`),A(v.shape.length===0||v.shape[0]===w.outChannels||v.shape[0]===1,()=>`Error in fused conv2d: bias shape (${v.shape}) is not compatible with the number of output channels (${w.outChannels})`))),p!=null){const L=p.shape;if(A(L.length<=1||L.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-${L.length}.`),L.length===1)A(L[0]===1||L[0]===w.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${L}) is not compatible with the number of output channels (${w.outChannels}).`);else if(L.length===3)try{Gt(L,w.outShape)}catch{const O=`Error in fused conv2d: PReLU activation weights (${L}) is not compatible with the output shape of the conv2d (${w.outShape}).`;throw Error(O)}N=P(p,"prelu weights","fused conv2d")}const T=(L,z)=>{A(s==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`);const[O,V,U,X]=z,ne=ng(L,U,l);
64A(Hl(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);const ae=[t0(V.shape,ne,O,t,r),F0(V,ne,O.shape,t,r)];if(X!=null){const Ie=rg(X,ne);ae.push(Ie)}return ae},$={x:m,filter:d,bias:v,preluActivationWeights:N},_={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return o==null?Br((z,O,V)=>{let U=J.runKernel(Lo,$,_);return V([O,z,U]),g&&(U=he(U,[U.shape[1],U.shape[2],U.shape[3]])),{value:U,gradFunc:T}})(m,d):Br((z,O,V,U)=>{let X=J.runKernel(Lo,$,_);return U([O,z,X,V]),g&&(X=he(X,[X.shape[1],X.shape[2],X.shape[3]])),{value:X,gradFunc:T}})(m,d,v)}}),Hw=ee({depthwiseConv2dNativeBackpropFilter_:function(n,e,t,r,s,a=[1,1],i){let o=n;n.rank===3&&(o=he(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=he(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const p={x:o,dy:l},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,filterShape:t};return J.runKernel(Sc,p,c)}}),jw=ee({depthwiseConv2dNativeBackpropInput_:function(n,e,t,r,s,a=[1,1],i){let o=e,l=!1;e.rank===3&&(l=!0,o=he(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const p={dy:o,filter:t},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,inputShape:n},h=J.runKernel(Fa,p,c);return l?he(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),gT=ee({fusedDepthwiseConv2d_:function({x:n,filter:e,strides:t,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:p,leakyreluAlpha:c}){if(ag(J.state.gradientDepth,l)===!1){let _=Rd(n,e,t,r,s,a,i);return o!=null&&(_=Ue(_,o)),sg(_,l,p,c)}const h=P(n,"x","depthwiseConv2d","float32"),d=P(e,"filter","depthwiseConv2d","float32");let m=h,g=!1;h.rank===3&&(g=!0,m=he(h,[1,h.shape[0],h.shape[1],h.shape[2]])),A(m.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`),A(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),A(m.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${m.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),a==null&&(a=[1,1]),A(bs(t,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),Ws("fused depthwiseConv2d",r,i);const y=is(m.shape,d.shape,t,a,r,i,!0);let w,v;o!=null&&(w=P(o,"bias","fused conv2d"),[w]=ar(w,h),Gt(y.outShape,w.shape)),p!=null&&(v=P(p,"prelu weights","fused depthwiseConv2d"));const N=(_,L)=>{A(Hl(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[z,O,V,U]=L,X=ng(_,V,l),ne=jw(O.shape,X,z,t,r,a,i),ae=Hw(O,X,z.shape,t,r,a,i);return U!=null?[ne,ae,rg(w,X)]:[ne,ae]},T={x:m,filter:d,bias:w,preluActivationWeights:v},$={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return o==null?Br((L,z,O)=>{let V=J.runKernel(ni,T,$);return O([z,L,V]),g&&(V=he(V,[V.shape[1],V.shape[2],V.shape[3]])),{value:V,gradFunc:N}})(m,d):Br((L,z,O,V)=>{let U=J.runKernel(ni,T,$);return V([z,L,U,O]),g&&(U=he(U,[U.shape[1],U.shape[2],U.shape[3]])),{value:U,gradFunc:N}})(m,d,w)}}),M0=ee({fusedMatMul_:function({a:n,b:e,transposeA:t=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(ag(J.state.gradientDepth,a)===!1){let U=Yt(n,e,t,r);return s!=null&&(U=Ue(U,s)),sg(U,a,i,o)}let l=P(n,"a","fused matMul"),p=P(e,"b","fused matMul");[l,p]=ar(l,p);const c=t?l.shape[l.rank-2]:l.shape[l.rank-1],h=r?p.shape[p.rank-1]:p.shape[p.rank-2],d=t?l.shape[l.rank-1]:l.shape[l.rank-2],m=r?p.shape[p.rank-2]:p.shape[p.rank-1],g=l.shape.slice(0,-2),y=p.shape.slice(0,-2),w=j(g),v=j(y);A(c===h,()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${p.shape} and transposeA=${t} and transposeB=${r} must match.`);const N=Gt(l.shape.slice(0,-2),p.shape.slice(0,-2)).concat([d,m]),T=he(l,t?[w,c,d]:[w,d,c]),$=he(p,r?[v,m,h]:[v,h,m]);let _,L;s!=null&&(_=P(s,"bias","fused matMul"),[_]=ar(_,l),Gt(N,_.shape)),i!=null&&(L=P(i,"prelu weights","fused matMul"));const z=(U,X)=>{const[ne,ae,Ie,me]=X,we=ng(he(U,Ie.shape),Ie,a);let $e,ze;return t||r?!t&&r?($e=Yt(we,ae,!1,!1),ze=Yt(we,ne,!0,!1)):t&&!r?($e=Yt(ae,we,!1,!0),ze=Yt(ne,we,!1,!1)):($e=Yt(ae,we,!0,!0),ze=Yt(we,ne,!0,!0)):($e=Yt(we,ae,!1,!0),ze=Yt(ne,we,!0,!1)),s!=null?[$e,ze,rg(me,we)
64]:[$e,ze]},O={a:T,b:$,bias:_,preluActivationWeights:L},V={transposeA:t,transposeB:r,activation:a,leakyreluAlpha:o};return s==null?Br((X,ne,ae)=>{const Ie=J.runKernel(Jn,O,V);return ae([X,ne,Ie]),{value:he(Ie,N),gradFunc:z}})(T,$):Br((X,ne,ae,Ie)=>{const me=J.runKernel(Jn,O,V);return Ie([X,ne,me,ae]),{value:he(me,N),gradFunc:z}})(T,$,_)}}),yT=ee({hammingWindow_:function(n){return tg(n,.54,.46)}}),Kw=ee({hannWindow_:function(n){return tg(n,.5,.5)}}),qw=ee({frame_:function(n,e,t,r=!1,s=0){let a=0;const i=[];for(;a+e<=n.size;)i.push(Tn(n,a,e)),a+=t;if(r)for(;a<n.size;){const o=a+e-n.size,l=Fr([Tn(n,a,e-o),$u([o],s)]);i.push(l),a+=t}return i.length===0?Ql([],[0,e]):he(Fr(i),[i.length,e])}}),bT=ee({stft_:function(n,e,t,r,s=Kw){r==null&&(r=D0(e));const a=qw(n,e,t),i=se(a,s(e));return df(i,r)}}),xT=ee({cropAndResize_:function(n,e,t,r,s="bilinear",a=0){const i=P(n,"image","cropAndResize"),o=P(e,"boxes","cropAndResize","float32"),l=P(t,"boxInd","cropAndResize","int32"),p=o.shape[0];A(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${o.shape}
64.`),A(l.rank===1&&l.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${o.shape}.`),A(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),A(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),A(s==="bilinear"||s==="nearest",()=>`method must be bilinear or nearest, but was ${s}`);const c={image:i,boxes:o,boxInd:l},h={method:s,extrapolationValue:a,cropSize:r};return J.runKernel(al,c,h)}}),wT=ee({flipLeftRight_:function(n){const e=P(n,"image","flipLeftRight","float32");A(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);const t={image:e};return J.runKernel(Cc,t,{})}}),vT=ee({grayscaleToRGB_:function(n){const e=P(n,"image","grayscaleToRGB"),t=e.rank-1,r=e.shape[t];A(e.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`),A(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)}}),kT=ee({rgbToGrayscale_:function(n){const e=P(n,"image","RGBToGrayscale"),t=e.rank-1,r=e.shape[t];A(e.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${e.rank}.`),A(r===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const s=e.dtype,a=gt(e,"float32"),i=vs([.2989,.587,.114]);let o;switch(e.rank){case 2:o=hh("ij,j->i",a,i);break;case 3:o=hh("ijk,k->ij",a,i);break;case 4:o=hh("ijkl,l->ijk",a,i);break;case 5:o=hh("ijklm,m->ijkl",a,i);break;case 6:o=hh("ijklmn,n->ijklm",a,i);break;default:throw new Error("Not a valid tensor rank.")}return o=ws(o,-1),gt(o,s)}}),NT=ee({rotateWithOffset_:function(n,e,t=0,r=.5){const s=P(n,"image","rotateWithOffset","float32");A(s.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);const a={image:s},i={radians:e,fillValue:t,center:r};return J.runKernel(Xh,a,i)}});function Vd(n,e,t,r,s,a){r==null&&(r=.5),s==null&&(s=Number.NEGATIVE_INFINITY),a==null&&(a=0);const i=n.shape[0];return t=Math.min(t,i),A(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),A(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),A(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),A(e.rank===1,()=>"scores must be a 1D tensor"),A(e.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${e.shape[0]}`),A(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:t,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const IT=ee({nonMaxSuppression_:function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY){const a=P(n,"boxes","nonMaxSuppression","float32"),i=P(e,"scores","nonMaxSuppression","float32"),o=Vd(a,i,t,r,s),l={maxOutputSize:t=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:s=o.scoreThreshold};return J.runKernel(zs,{boxes:a,scores:i},l)}});function ST(n,e,t){const r=function(a,i,o){return function(l,p,c){let h=0,d=l.length,m=0,g=!1;for(;h<d;){m=h+(d-h>>>1);const y=c(p,l[m]);y>0?h=m+1:(d=m,g=!y)}return g?h:-h-1}(a,i,o||TT)}(n,e,t),s=r<0?-(r+1):r;n.splice(s,0,e)}function TT(n,e){return n>e?1:n<e?-1:0}function ig(n,e,t,r,s){return O0(n,e,t,r,s,0)}function og(n,e,t,r,s,a){return O0(n,e,t,r,s,0,!1,a,!0)}function ug(n,e,t,r,s,a){return O0(n,e,t,r,s,a,!0)}function O0(n,e,t,r,s,a,i=!1,o=!1,l=!1){const p=[];for(let w=0;w<e.length;w++)e[w]>s&&p.push({score:e[w],boxIndex:w,suppressBeginIndex:0});p.sort(Xw);const c=a>0?-.5/a:0,h=[],d=[];for(;h.length<t&&p.length>0;){const w=p.pop(),{score:v,boxIndex:N,suppressBeginIndex:T}=w;if(v<s)break;let $=!1;for(let _=h.length-1;_>=T;--_){const L=ET(n,N,h[_]);if(L>=r){$=!0;break}if(w.score=w.score*CT(r,c,L),w.score<=s)break}w.suppressBeginIndex=h.length,$||(w.score===v?(h.push(N),d.push(w.score)):w.score>s&&ST(p,w,Xw))}const m=h.length,g=t-m;o&&g>0&&(h.push(...new Array(g).fill(0)),d.push(...new Array(g).fill(0)));const y={selectedIndices:h};return i&&(y.selectedScores=d),l&&(y.validOutputs=m),y}function ET(n,e,t){const r=n.subarray(4*e,4*e+4),s=n.subarray(4*t,4*t+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),o=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),p=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),d=Math.max(s[1],s[3]),m=(o-a)*(l-i),g=(h-p)*(d-c);if(m<=0||g<=0)return 0;const y=Math.max(a,p),w=Math.max(i,c),v=Math.min(o,h),N=Math.min(l,d),T=Math.max(v-y,0)*Math.max(N-w,0);return T/(m+g-T)}function CT(n,e,t){const r=Math.exp(e*t*t);return t<=n?r:0}function Xw(n,e){return n.score-e.score||n.score===e.score&&e.boxIndex-n.boxIndex}const $T=ee({nonMaxSuppressionWithScore_:function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=P(n,"boxes","nonMaxSuppression"),o=P(e,"scores","nonMaxSuppression"),l=Vd(i,o,t,r,s,a),p={boxes:i,scores:o},c={maxOutputSize:t=l.maxOutputSize,iouThreshold:r=l.iouThreshold,scoreThreshold:s=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},h=J.runKernel(Fc,p,c);return{selectedIndices:h[0],selectedScores:h[1]}}}),AT=ee({nonMaxSuppressionPadded_:function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=P(n,"boxes","nonMaxSuppression"),o=P(e,"scores","nonMaxSuppression"),l=Vd(i,o,t,r,s,null),p={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=J.runKernel(Mt,p,c);return{selectedIndices:h[0],validOutputs:h[1]}}}),Yw=ee({resizeBilinear_:function(n,e,t=!1,r=!1){const s=P(n,"images","resizeBilinear");A(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}
64.`),A(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),A(r===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;s.rank===3&&(i=!0,a=he(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const o={images:a},l={alignCorners:t,halfPixelCenters:r,size:e},p=J.runKernel(vl,o,l);return i?he(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),Zw=ee({resizeNearestNeighbor_:function(n,e,t=!1,r=!1){const s=P(n,"images","resizeNearestNeighbor");A(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),A(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),A(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(r===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;s.rank===3&&(i=!0,a=he(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const o={images:a},l={alignCorners:t,halfPixelCenters:r,size:e},p=J.runKernel(Es,o,l);return i?he(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),RT=ee({threshold_:function(n,e="binary",t=!1,r=.5){const s=P(n,"image","threshold"),a=s.shape[0]*s.shape[1];let i,o,l,p,c=se(vs([r]),255);if(A(s.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`),A(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]}.`),A(s.dtype==="int32"||s.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),A(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),s.shape[2]===3){[i,o,l]=la(s,[1,1,1],-1);const d=se(i,.2989),m=se(o,.587),g=se(l,.114);p=Ue(Ue(d,m),g)}else p=n;e==="otsu"&&(c=function(d,m){let g,y,w,v,N,T,$=vs([-1]),_=vs([0]),L=vs([0]);for(let z=0;z<d.size-1;z++){g=Tn(d,0,z+1),y=Tn(d,z+1),N=Lt(Dt(g),m),T=Lt(Dt(y),m);const O=Dt(se(g,fh(0,g.size)));w=Lt(O,Dt(g));const V=$u(y.shape,g.size),U=Ue(fh(0,y.size),V),X=se(y,U);v=Lt(Dt(X),Dt(y));const ne=ot(w,v),ae=ot(w,v),Ie=se(N,T);L=se(se(Ie,ne),ae);const me=Gs(L,_);_=os(me,L,_),$=os(me,vs([z]),$)}return $}(Xy(gt(Wm(p),"int32"),Bs([]),256),a));const h=t?ql(p,c):Gs(p,c);return gt(se(h,255),"int32")}}),_T=ee({transform_:function(n,e,t="nearest",r="constant",s=0,a){const i=P(n,"image","transform","float32"),o=P(e,"transforms","transform","float32");A(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),A(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);const l={image:i,transforms:o},p={interpolation:t,fillMode:r,fillValue:s,outputShape:a};return J.runKernel(Bc,l,p)}}),DT=ee({bandPart_:function(n,e,t){const r=P(n,"a","bandPart");A(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const s=r.shape,[a,i]=r.shape.slice(-2);let o,l;typeof e=="number"?(A(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),A(e<=a,()=>`bandPart(): numLower (${e}) must not be greater than the number of rows (${a}).`),o=P(e<0?a:e,"numLower","bandPart")):(A(e.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),o=os(Ld(e,0),a,Xl(e,a))),typeof t=="number"?(A(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`),A(t<=i,()=>`bandPart(): numUpper (${t}) must not be greater than the number of columns (${i}).`),l=P(t<0?i:t,"numUpper","bandPart")):(A(t.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=os(Ld(t,0),i,Xl(t,i)));const p=he(fh(0,a,1,"int32"),[-1,1]),c=fh(0,i,1,"int32"),h=ot(p,c),d=ci(ql(h,o),Mu(h,Vn(l))),m=Wr([a,i],r.dtype);return he(Hs(Ga(he(r,[-1,a,i])).map(g=>os(d,g,m))),s)}}),FT=ee({gramSchmidt_:function(n){let e;if(Array.isArray(n)){e=!1,A(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<n.length;++a)A(n[a].shape[0]===s,()=>
64`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[a].shape[0]} vs. ${s})`)}else e=!0,n=la(n,n.shape[0],0).map(s=>Zl(s,[0]));A(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<n.length;++s)t.push(J.tidy(()=>{let a=r[s];if(s>0)for(let i=0;i<s;++i){const o=se(Dt(se(t[i],a)),t[i]);a=ot(a,o)}return Lt(a,Fd(a,"euclidean"))}));return e?Hs(t,0):t}});function Qw(n,e=!1){return J.tidy(()=>{A(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=Lm(t),a=va(n);const i=Ql([[1]],[1,1]);let o=va(i);const l=t>=r?r:t;for(let p=0;p<l;++p){const c=a,h=o,d=s;[o,a,s]=J.tidy(()=>{const m=Tn(a,[p,p],[t-p,1]),g=Fd(m),y=Tn(a,[p,p],[1,1]),w=os(Gs(y,0),Ql([[-1]]),Ql([[1]])),v=ot(y,se(w,g)),N=Lt(m,v);o=N.shape[0]===1?va(i):Fr([i,Tn(N,[1,0],[N.shape[0]-1,N.shape[1]])],0);const T=Vn(Lt(Yt(w,v),g)),$=Tn(a,[p,0],[t-p,r]),_=se(T,o),L=Qt(o);if(p===0)a=ot($,Yt(_,Yt(L,$)));else{const V=ot($,Yt(_,Yt(L,$)));a=Fr([Tn(a,[0,0],[p,r]),V],0)}const z=Qt(_),O=Tn(s,[0,p],[t,s.shape[1]-p]);if(p===0)s=ot(O,Yt(Yt(O,o),z));else{const V=ot(O,Yt(Yt(O,o),z));s=Fr([Tn(s,[0,0],[t,p]),V],1)}return[o,a,s]}),on([c,h,d])}return!e&&t>r&&(s=Tn(s,[0,0],[t,r]),a=Tn(a,[0,0],[r,r])),[s,a]})}const MT=ee({qr_:function(n,e=!1){if(A(n.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return Qw(n,e);{const t=n.shape.slice(0,n.shape.length-2).reduce((i,o)=>i*o),r=Ga(he(n,[t,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),s=[],a=[];return r.forEach(i=>{const[o,l]=Qw(i,e);s.push(o),a.push(l)}),[he(Hs(s,0),n.shape),he(Hs(a,0),n.shape)]}}});var js;(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"})(js||(js={}));const Lu=ee({computeWeightedLoss_:function(n,e,t=js.SUM_BY_NONZERO_WEIGHTS){const r=P(n,"losses","computeWeightedLoss");let s=null;e!=null&&(s=P(e,"weights","computeWeightedLoss"));const a=s==null?r:se(r,s);if(t===js.NONE)return a;if(t===js.SUM)return Dt(a);if(t===js.MEAN){if(s==null)return Sr(a);{const i=r.size/s.size,o=Lt(Dt(a),Dt(s));return i>1?Lt(o,Pt(i)):o}}if(t===js.SUM_BY_NONZERO_WEIGHTS){if(s==null)return Lt(Dt(a),Pt(r.size));{const i=se(s,ua(r.shape)),o=gt(Dt(ph(i,Pt(0))),"float32");return Lt(Dt(a),o)}}throw Error(`Unknown reduction: ${t}`)}}),OT=ee({absoluteDifference_:function(n,e,t,r=js.SUM_BY_NONZERO_WEIGHTS){const s=P(n,"labels","absoluteDifference"),a=P(e,"predictions","absoluteDifference");let i=null;t!=null&&(i=P(t,"weights","absoluteDifference")),ge(s.shape,a.shape,"Error in absoluteDifference: ");const o=An(ot(s,a));return Lu(o,i,r)}}),LT=ee({cosineDistance_:function(n,e,t,r,s=js.SUM_BY_NONZERO_WEIGHTS){const a=P(n,"labels","cosineDistance"),i=P(e,"predictions","cosineDistance");let o=null;r!=null&&(o=P(r,"weights","cosineDistance")),ge(a.shape,i.shape,"Error in cosineDistance: ");const l=Pt(1),p=ot(l,Dt(se(a,i),t,!0));return Lu(p,o,s)}}),zT=ee({hingeLoss_:function(n,e,t,r=js.SUM_BY_NONZERO_WEIGHTS){let s=P(n,"labels","hingeLoss");const a=P(e,"predictions","hingeLoss");let i=null;t!=null&&(i=P(t,"weights","hingeLoss")),ge(s.shape,a.shape,"Error in hingeLoss: ");const o=Pt(1);s=ot(se(Pt(2),s),o);const l=to(ot(o,se(s,a)));return Lu(l,i,r)}}),PT=ee({huberLoss_:function(n,e,t,r=1,s=js.SUM_BY_NONZERO_WEIGHTS){const a=P(n,"labels","huberLoss"),i=P(e,"predictions","huberLoss");let o=null;t!=null&&(o=P(t,"weights","huberLoss")),ge(a.shape,i.shape,"Error in huberLoss: ");const l=Pt(r),p=An(ot(i,a)),c=Xl(p,l),h=ot(p,c),d=Ue(se(Pt(.5),Mn(c)),se(l,h));return Lu(d,o,s)}}),BT=ee({logLoss_:function(n,e,t,r=1e-7,s=js.SUM_BY_NONZERO_WEIGHTS){const a=P(n,"labels","logLoss"),i=P(e,"predictions","logLoss");let o=null;t!=null&&(o=P(t,"weights","logLoss")),ge(a.shape,i.shape,"Error in logLoss: ");const l=Pt(1),p=Pt(r),c=Vn(se(a,Sa(Ue(i,p)))),h=se(ot(l,a),Sa(Ue(ot(l,i),p))),d=ot(c,h);return Lu(d,o,s)}}),VT=ee({meanSquaredError_:function(n,e,t,r=js.SUM_BY_NONZERO_WEIGHTS){const s=P(n,"labels","meanSquaredError"),a=P(e,"predictions","meanSquaredError");let i=null;t!=null&&(i=P(t,"weights","meanSquaredError")),ge(s.shape,a.shape,"Error in meanSquaredError: ");const o=Zm(s,a);return Lu(o,i,r)}}),UT=ee({sigmoidCrossEntropy_:function(n,e,t,r=0,s=js.SUM_BY_NONZERO_WEIGHTS){let a=P(n,"multiClassLabels","sigmoidCrossEntropy");const i=P(e,"logits","sigmoidCrossEntropy");let o=null;if(t!=null&&(o=P(t,"weights","sigmoidCrossEntropy")),ge(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){const p=Pt(r),c=Pt(1),h=Pt(.5);a=Ue(se(a,ot(c,p)),se(h,p))}const l=function(p,c){const h=P(p,"labels","sigmoidCrossEntropyWithLogits"),d=P(c,"logits","sigmoidCrossEntropyWithLogits");ge(h.shape,d.shape,"Error in sigmoidCrossEntropyWithLogits: ");const m=to(d),g=se(d,h),y=ef(oa(Vn(An(d))));return Ue(ot(m,g),y)}(a,i);return Lu(l,o,s)}}),WT=ee({softmaxCrossEntropy_:function(n,e,t,r=0,s=js.SUM_BY_NONZERO_WEIGHTS){let a=P(n,"onehotLabels","softmaxCrossEntropy");const i=P(e,"logits","softmaxCrossEntropy");let o=null;if(t!=null&&(o=P(t,"weights","softmaxCrossEntropy")),ge(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){const p=Pt(r),c=Pt(1),h=Pt(a.shape[1]);a=Ue(se(a,ot(c,p)),Lt(p,h))}const l=function(p,c,h=-1){if(h===-1&&(h=c.rank-1),h!==c.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${c.rank} and dim was ${h}`);return Br((m,g,y)=>{const w=tf(g,[h],!0),v=ot(gt(g,"float32"),w);y([m,v]);const N=Vn(se(v,m));return{value:Dt(N,[h]),gradFunc:(T,$)=>{const[_,L]=$,z=Mr(T.shape,[h]);return[se(he(T,z),ot(gt(_,"float32"),oa(L))),se(he(T,z),ot(oa(L),gt(_,"float32")))]}}})(p,c)}(a,i);return Lu(l,o,s)}}),GT=ee({sparseFillEmptyRows_:function(n,e,t,r){const s=P(n,"indices","sparseFillEmptyRows","int32"),a=P(e,"values","sparseFillEmptyRows"),i=P(t,"denseShape","sparseFillEmptyRows","int32"),o=P(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(s.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
65        ${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const l={indices:s,values:a,denseShape:i,defaultValue:o},p=J.runKernel(Cl,l);return{outputIndices:p[0],outputValues:p[1],emptyRowIndicator:p[2],reverseIndexMap:p[3]}}}),HT=ee({sparseReshape_:function(n,e,t){const r=P(n,"inputIndices","sparseReshape","int32"),s=P(e,"
65inputShape","sparseReshape","int32"),a=P(t,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
66        ${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 i={inputIndices:r,inputShape:s,newShape:a},o=J.runKernel($l,i);return{outputIndices:o[0],outputShape:o[1]}}}),jT=ee({sparseSegmentMean_:function(n,e,t){const r=P(n,"data","sparseSegmentMean"),s=P(e,"indices","sparseSegmentMean","int32"),a=P(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
67          ${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
68          ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return J.runKernel(qh,i)}}),KT=ee({sparseSegmentSum_:function(n,e,t){const r=P(n,"data","sparseSegmentSum"),s=P(e,"indices","sparseSegmentSum","int32"),a=P(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
69         ${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
70         ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return J.runKernel(gu,i)}}),qT=ee({stringNGrams_:function(n,e,t,r,s,a,i,o){const l=P(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 p=P(e,"dataSplits","stringNGrams");if(p.dtype!=="int32")throw new Error("Data splits must be of datatype int32");const c={separator:t,nGramWidths:r,leftPad:s,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:p},d=J.runKernel(rs,h,c);return{nGrams:d[0],nGramsSplits:d[1]}}}),XT=ee({stringSplit_:function(n,e,t=!0){const r=P(n,"input","stringSplit","string"),s=P(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},i={input:r,delimiter:s},o=J.runKernel(Bi,i,a);return{indices:o[0],values:o[1],shape:o[2]}}}),YT=ee({stringToHashBucketFast_:function(n,e){const t=P(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 J.runKernel(ss,s,r)}}),ZT=ee({staticRegexReplace_:function(n,e,t,r=!0){const s=P(n,"input","staticRegexReplace","string"),a={pattern:e,rewrite:t,replaceGlobal:r};return J.runKernel(Al,{x:s},a)}}),Jw={fft:hf,ifft:Bd,rfft:df,irfft:Ym},e2={hammingWindow:yT,hannWindow:Kw,frame:qw,stft:bT},hi={flipLeftRight:wT,grayscaleToRGB:vT,resizeNearestNeighbor:Zw,resizeBilinear:Yw,rgbToGrayscale:kT,rotateWithOffset:NT,cropAndResize:xT,nonMaxSuppression:IT,nonMaxSuppressionAsync:async function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY){const a=P(n,"boxes","nonMaxSuppressionAsync"),i=P(e,"scores","nonMaxSuppressionAsync"),o=Vd(a,i,t,r,s);t=o.maxOutputSize,r=o.iouThreshold,s=o.scoreThreshold;const l=await Promise.all([a.data(),i.data()]),p=l[0],c=l[1],{selectedIndices:h}=ig(p,c,t,r,s);return a!==n&&a.dispose(),i!==e&&i.dispose(),vs(h,"int32")},nonMaxSuppressionWithScore:$T,nonMaxSuppressionWithScoreAsync:async function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=P(n,"boxes","nonMaxSuppressionAsync"),o=P(e,"scores","nonMaxSuppressionAsync"),l=Vd(i,o,t,r,s,a);t=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;const p=await Promise.all([i.data(),o.data()]),c=p[0],h=p[1],{selectedIndices:d,selectedScores:m}=ug(c,h,t,r,s,a);return i!==n&&i.dispose(),o!==e&&o.dispose(),{selectedIndices:vs(d,"int32"),selectedScores:vs(m)}},nonMaxSuppressionPadded:AT,nonMaxSuppressionPaddedAsync:async function(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=P(n,"boxes","nonMaxSuppressionAsync"),o=P(e,"scores","nonMaxSuppressionAsync"),l=Vd(i,o,t,r,s,null),p=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,m]=await Promise.all([i.data(),o.data()]),{selectedIndices:g,validOutputs:y}
70=og(d,m,p,c,h,a);return i!==n&&i.dispose(),o!==e&&o.dispose(),{selectedIndices:vs(g,"int32"),validOutputs:Pt(y,"int32")}},threshold:RT,transform:_T},L0={bandPart:DT,gramSchmidt:FT,qr:MT},t2={absoluteDifference:OT,computeWeightedLoss:Lu,cosineDistance:LT,hingeLoss:zT,huberLoss:PT,logLoss:BT,meanSquaredError:VT,sigmoidCrossEntropy:UT,softmaxCrossEntropy:WT},n2={sparseFillEmptyRows:GT,sparseReshape:HT,sparseSegmentMean:jT,sparseSegmentSum:KT},r2={stringNGrams:qT,stringSplit:XT,stringToHashBucketFast:YT,staticRegexReplace:ZT},gh=Jx,QT=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function z0(){return new Promise(n=>QT(()=>n()))}function P0(n,e){const t=n[0].length;n.forEach((s,a)=>{A(s.length===t,()=>`Error in concat${t}D: rank of tensors[${a}] must be the same as the rank of the rest (${t})`)}),A(e>=0&&e<t,()=>`Error in concat${t}D: axis must be between 0 and ${t-1}.`);const r=n[0];n.forEach((s,a)=>{for(let i=0;i<t;i++)A(i===e||s[i]===r[i],()=>`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 jo(n,e){const t=n[0].slice();for(let r=1;r<n.length;r++)t[e]+=n[r][e];return t}var no;function s2(n,e,t){let r=new Array;if(t==null&&e==null)return r;if(e==null)for(;r.length<n+t.length;)r.push(-1);else r=e.slice();if(t==null)return r;if(n+t.length!==r.length)throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.rank = ${n+t.length}, but shape.rank = ${r.length}`);for(let s=1;s<t.length;++s){const a=t[s],i=r[r.length-t.length+s],o=r[i];if(a>=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.shape[${s+n}] = ${a} but shape[${s+n}] = ${o}`)}else r[i]=a}return r}function a2(n){const e={FIRST_DIM_SIZE:no.FIRST_DIM_SIZE,VALUE_ROWIDS:no.VALUE_ROWIDS,ROW_LENGTHS:no.ROW_LENGTHS,ROW_SPLITS:no.ROW_SPLITS,ROW_LIMITS:no.ROW_LIMITS,ROW_STARTS:no.ROW_STARTS},t=[];for(const r of n){if(!(r in e))break;t.push(e[r])}return t}function i2(n){return n.length===0?0:n[0]===no.FIRST_DIM_SIZE?n.length-1:n.length}function o2(n,e){if(n==null||e==null)return;const t=n.length,r=e.length;if(t>=r)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${e}, are incompatible: defaultValue.rank = ${t} must be less than ragged tensor input flatValues.rank = ${r})`);for(let s=0;s<Math.min(t,r-1);++s){const a=n[s],i=e[s+1];if(a>=0&&i>=0&&a!==1&&a!==i)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${e} are incompatible: defaultValue.shape[${s-n.length}] = ${a} but ragged tensor input.flatValues.shape[${s-n.length}] = ${i}`)}}(function(n){n[n.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",n[n.VALUE_ROWIDS=1]="VALUE_ROWIDS",n[n.ROW_LENGTHS=2]="ROW_LENGTHS",n[n.ROW_SPLITS=3]="ROW_SPLITS",n[n.ROW_LIMITS=4]="ROW_LIMITS",n[n.ROW_STARTS=5]="ROW_STARTS"})(no||(no={}));const B0=30;function lg(n){return n<=B0?n:bt(n,Math.floor(Math.sqrt(n)))}function V0(n,e,t){return[t*(typeof n=="number"?n:n[0]),e*(typeof n=="number"?n:n[1])]}function pf(n,e,t,r=!0){let s=[];if(r)s=s.concat(e.slice(0)),s.push(n[0]/t),s=s.concat(n.slice(1));else{s=s.concat(n[0]);const a=e.length;for(let i=0;i<a;++i)s=s.concat([n[i+1]/e[i],e[i]]);s=s.concat(n.slice(a+1))}return s}function ff(n,e,t=!0){const r=[];if(t){r.push(e);for(let s=e+1;s<n;++s)s<=2*e?(r.push(s),r.push(s-(e+1))):r.push(s)}else{const s=[],a=[];for(let i=1;i<n;++i)i>=2*e+1||i%2==1?a.push(i):s.push(i);r.push(...s),r.push(0),r.push(...a)}return r}function mf(n,e,t,r=!0){const s=[];r?s.push(n[0]/t):s.push(n[0]*t);for(let a=1;a<n.length;++a)a<=e.length?r?s.push(e[a-1]*n[a]):s.push(n[a]/e[a-1]):s.push(n[a]);return s}function U0(n,e){const t=[0];for(let r=0;r<e;++r)t.push(n[r][0]);return t}function W0(n,e,t){const r=n.slice(0,1);for(let s=0;s<t;++s)r.push(n[s+1]-e[s][0]-e[s][1]);return r}const cg=1.7580993408473768,hg=1.0507009873554805,G0=.3275911,H0=.254829592,j0=-.284496736,K0=1.421413741,q0=-1.453152027,X0=1.061405429;function zu(n,e){if(n.length!==e.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${n.length}, imag: ${e.length}.`);const t=new Float32Array(2*n.length);for(let r=0;r<t.length;r+=2)t[r]=n[r/2],t[r+1]=e[r/2];return t}function u2(n){const e=new Float32Array(n.length/2),t=new Float32Array(n.length/2);for(let r=0;r<n.length;r+=2)e[r/2]=n[r],t[r/2]=n[r+1];return{real:e,imag:t}}function l2(n){const e=Math.ceil(n.length/4),t=new Float32Array(e),r=new Float32Array(e);for(let s=0;s<n.length;s+=4)t[Math.floor(s/4)]=n[s],r[Math.floor(s/4)]=n[s+1];return{real:t,imag:r}}function c2(n){const e=Math.floor(n.length/4),t=new Float32Array(e),r=new Float32Array(e);for(let s=2;s<n.length;s+=4)t[Math.floor(s/4)]=n[s],r[Math.floor(s/4)]=n[s+1];return{real:t,imag:r}}function Y0(n,e){return{real:n[2*e],imag:n[2*e+1]}}function h2(n,e,t,r){n[2*r]=e,n[2*r+1]=t}function d2(n,e){const t=new Float32Array(n/2),r=new Float32Array(n/2);for(let s=0;s<Math.ceil(n/2);s++){const a=(e?2:-2)*Math.PI*(s/n);t[s]=Math.cos(a),r[s]=Math.sin(a)}return{real:t,imag:r}}function p2(n,e,t){const r=(t?2:-2)*Math.PI*(n/e);return{real:Math.cos(r),imag:Math.sin(r)}}const Z0="->",JT=/->/g,f2=",",m2="...";function Q0(n,e){const t=((n=n.replace(/\s/g,"")).length-n.replace(JT,"").length)/Z0.length;if(t<1)throw new Error("Equations without an arrow are not supported.");
vendor: 5,361 bytes, lines 70-73
70if(t>1)throw new Error(`Equation must contain exactly one arrow ("${Z0}").`);const[r,s]=n.split(Z0);A(r.indexOf(m2)===-1,()=>`The ellipsis notation ("${m2}") is not supported yet.`);const a=r.split(f2),i=a.length;if(e!==i)throw new Error(`Expected ${i} input tensors, received ${e}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let h=0;h<s.length;++h){const d=s[h];if(!a.some(m=>m.indexOf(d)!==-1))throw new Error(`Output subscripts contain the label ${d} not present in the input subscripts.`);o.indexOf(d)===-1&&o.push(d)}for(let h=0;h<r.length;++h){const d=r[h];o.indexOf(d)===-1&&d!==f2&&o.push(d)}const l=new Array(a.length);for(let h=0;h<i;++h){if(new Set(a[h].split("")).size!==a[h].length)throw new Error(`Found duplicate axes in input component ${a[h]}. Support for duplicate axes in input is not implemented yet.`);l[h]=[];for(let d=0;d<a[h].length;++d)l[h].push(o.indexOf(a[h][d]))}const p=o.length,c=[];for(let h=s.length;h<p;++h)c.push(h);return{allDims:o,summedDims:c,idDims:l}}function J0(n,e){let t=new Array(n);t.fill(-1);for(let s=0;s<e.length;++s)t[e[s]]=s;const r=[];for(let s=0;s<n;++s)t[s]===-1&&r.push(s);return t=t.filter(s=>s!==-1),{permutationIndices:t,expandDims:r}}function e1(n,e,t){const r=new Array(n);for(let s=0;s<t.length;++s){const a=t[s].shape;for(let i=0;i<e[s].length;++i)r[e[s][i]]===void 0?r[e[s][i]]=a[i]:A(r[e[s][i]]===a[i],()=>`Expected dimension ${r[e[s][i]]} at axis ${i} of input shaped ${JSON.stringify(a)}, but got dimension ${a[i]}`)}}function t1(n,e){const t=n,r=[];let s=0;n.length===0&&t.push(-1),s=n.length+1;for(let i=0;i<s;++i)r.push([]);const a=[];for(let i=0;i<t.length;++i){const o=e3(e,t[i]);for(const l of o)a.indexOf(l)===-1&&(r[i].push(l),a.push(l))}return{path:t,steps:r}}function n1(n){return n.every((e,t)=>e===t)}function e3(n,e){const t=[];for(let r=0;r<n.length;++r)n[r].length!==0&&n[r].indexOf(e)===-1&&e!==-1||t.push(r);return t}function r1(n,e,t=0){let r=[];if(typeof e=="number")A(n.shape[t]%e===0,()=>"Number of splits must evenly divide the axis."),r=new Array(e).fill(n.shape[t]/e);else{const s=e.reduce((i,o)=>(o===-1&&(i+=1),i),0);A(s<=1,()=>"There should be only one negative value in split array.");const a=e.indexOf(-1);if(a!==-1){const i=e.reduce((o,l)=>l>0?o+l:o);e[a]=n.shape[t]-i}A(n.shape[t]===e.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),r=e}return r}function g2(n){return`Received SparseTensor with denseShape[0] = 0 but
71  indices.shape[0] = ${n}`}function y2(n,e){return`indices(${n}, 0) is invalid: ${e} < 0`}function b2(n,e,t){return`indices(${n}, 0) is invalid: ${e} >= ${t}`}function x2(n,e){return`only one output dimension may be -1, not both ${n} and ${e}`}function w2(n,e){return`size ${n} must be non-negative, not ${e}`}function t3(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function v2(n,e){return`Input to reshape is a SparseTensor with ${j(n)}
72  dense values, but the requested shape requires a multiple of ${j(e)}. inputShape=${n} outputShape= ${e}`}function k2(n,e){return`Input to reshape is a tensor with ${j(n)} dense values, but the requested shape has ${j(e)}. inputShape=${n} outputShape=${e}`}function n3(){return"segment ids must be >= 0"}function N2(){return"segment ids are not increasing"}function I2(n,e){return`Segment id ${n} out of range [0, ${e}), possibly because segmentIds input is not sorted.`}function S2(n,e,t){return`Bad: indices[${n}] == ${e} out of range [0, ${t})`}function T2(n,e){let t,r=!1;for(n<=B0?(t=n,r=!0):t=bt(n,Math.floor(Math.sqrt(n)));!r;)t>e||t===n?r=!0:t=bt(n,t+1);return t}function E2(n,e,t){const r=[],s=n.length;for(let a=0;a<s;a++)a!==e?r.push(n[a]):r.push(t);return r}function s1(n,e,t,r){const s=e.shape.length,a=n.shape.length;if(r!==0&&(r<-s||r>s))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) (
73    ${a}).`);if(t<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${t}).`);for(let h=0;h<r;++h)if(n.shape[h]!==e.shape[h])throw new Error(`x.shape[${h}]: ${n.shape[h]} should be equal to indices.shape[${h}]: ${e.shape[h]}.`);const i=n.shape[t],o=[];let l=1,p=1,c=1;for(let h=0;h<r;++h)o.push(n.shape[h]),l*=n.shape[h];for(let h=r;h<t;h++)o.push(n.shape[h]),p*=n.shape[h];for(let h=r;h<s;h++)o.push(e.shape[h]);for(let h=t+1;h<a;h++)o.push(n.shape[h]),c*=n.shape[h];return{batchSize:l,sliceSize:c,outerSize:p,dimSize:i,outputShape:o}}function Pu(n){try{return n.map(e=>gr(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function C2(n){return n.map(e=>dn(e))}(function(){for(const n of Lp)st(n)})();const $2={kernelName:Yu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,mh(gt(t,"float32"),-1))}}},r3={kernelName:Da,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const r=Mn(gt(t,"float32")),s=qn(ot(Pt(1),r));return Vn(Lt(n,s))}}}},s3={kernelName:Js,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const r=qn(ot(Mn(gt(t,"float32")),1));return Lt(n,r)}}}},a3={kernelName:bi,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{let a=n;const i=er(t.shape,s);return i.length>
730&&(a=Dt(a,i)),he(a,t.shape)},b:()=>{let a=n;const i=er(r.shape,s);return i.length>0&&(a=Dt(a,i)),he(a,r.shape)}}}},i3={kernelName:yc,saveAllInputs:!0,gradFunc:(n,e)=>{const t={};return e.forEach((r,s)=>{t[s]=()=>n.clone()}),t}},o3={kernelName:Zu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>mn(t)}}},u3={kernelName:wi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>mn(t)}}},l3={kernelName:pa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,qn(ot(Pt(1),Mn(gt(t,"float32")))))}}},c3={kernelName:go,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const r=qn(Ue(Pt(1),Mn(gt(t,"float32"))));return Lt(n,r)}}}},h3={kernelName:Jo,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{const a=Ue(Mn(t),Mn(r));let i=se(n,Lt(r,a));const o=er(t.shape,s);return o.length>0&&(i=Dt(i,o)),he(i,t.shape)},b:()=>{const a=Ue(Mn(t),Mn(r));let i=Vn(se(n,Lt(t,a)));const o=er(r.shape,s);return o.length>0&&(i=Dt(i,o)),he(i,r.shape)}}}},d3={kernelName:Za,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,Ue(Mn(gt(t,"float32")),1))}}},p3={kernelName:vi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,ot(Pt(1),Mn(gt(t,"float32"))))}}},f3=ee({avgPool3dGrad_:function(n,e,t,r,s,a){const i=P(n,"dy","avgPool3dGrad"),o=P(e,"input","avgPool3dGrad");let l=i,p=o,c=!1;o.rank===4&&(c=!0,l=he(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=he(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(p.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),Ws("avgPool3dGrad",s,a);const h={dy:l,input:p},d={filterSize:t,strides:r,pad:s,dimRoundingMode:a},m=J.runKernel(Ju,h,d);return c?he(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}}),m3={kernelName:Qu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:o}=t;return{x:()=>f3(n,r,s,a,i,o)}}},g3=ee({avgPoolGrad_:function(n,e,t,r,s){const a=P(n,"dy","avgPoolGrad"),i=P(e,"input","avgPoolGrad");A(i.rank===a.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`);let o=i,l=a,p=!1;i.rank===3&&(p=!0,o=he(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=he(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),A(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);const c={dy:l,input:o},h={filterSize:t,strides:r,pad:s},d=J.runKernel(wc,c,h);return p?he(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),y3={kernelName:xc,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>g3(n,r,s,a,i)}}},b3={kernelName:yo,inputsToSave:["a","b"],gradFunc:(n,e,t)=>{const[r,s]=e,{transposeA:a,transposeB:i}=t;return a||i?!a&&i?{a:()=>Yt(n,s,!1,!1),b:()=>Yt(n,r,!0,!1)}:a&&!i?{a:()=>Yt(s,n,!1,!0),b:()=>Yt(r,n,!1,!1)}:{a:()=>Yt(s,n,!0,!0),b:()=>Yt(n,r,!0,!0)}:{a:()=>Yt(n,s,!1,!0),b:()=>Yt(r,n,!0,!1)}}},x3={kernelName:el,gradFunc:(n,e,t)=>{const{blockShape:r,crops:s}=t;return{x:()=>af(n,r,s)}}},w3={kernelName:Ni,gradFunc:(n,e,t)=>{const r=t,s=r.inputShape,a=r.shape,i=Array.from(a);for(let l=s.length-1;l>=0;l--)if(s[l]===a[l])i[l]=1;else if(s[l]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);const o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>Dt(n,o,!0)}}},v3={kernelName:tl,gradFunc:n=>({x:()=>n.clone()})},k3={kernelName:nl,gradFunc:n=>({x:()=>mn(n)})},N3={kernelName:bo,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{clipValueMin:s,clipValueMax:a}=t;return{x:()=>os(ci(Mu(r,s),ql(r,a)),n,mn(n))}}},I3={kernelName:rl,inputsToSave:["x"],gradFunc:$2.gradFunc},S3={kernelName:tu,saveAllInputs:!0,gradFunc:(n,e,t)=>{const r=e.map(o=>o.shape),{axis:s}=t,a=Oe(s,e[0].shape)[0],i=r.map(o=>o[a]);return la(n,i,a).map(o=>()=>o)}},T3={kernelName:ds,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[r,s]=e,{dilations:a,strides:i,pad:o,dataFormat:l}=t;return A(Hl(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>
vendor: 5,574 bytes, line 73
73t0(r.shape,n,s,i,o,l),filter:()=>F0(r,n,s.shape,i,o,l)}}},E3={kernelName:sl,inputsToSave:["dy","filter"],gradFunc:(n,e,t)=>{const[r,s]=e,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=t;return{dy:()=>Fu(n,s,a,i,o,1,l),filter:()=>F0(n,r,s.shape,a,i,o,l)}}},C3=ee({conv3DBackpropFilter_:function(n,e,t,r,s){let a=n;n.rank===4&&(a=he(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let i=e;i.rank===4&&(i=he(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),A(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),A(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),A(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),A(a.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${t[3]}.`),A(i.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${t[4]}).`);const o={x:a,dy:i},l={strides:r,pad:s,filterShape:t};return J.runKernel(Hh,o,l)}}),$3={kernelName:kc,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:r,strides:s,pad:a}=t;A(Hl(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const[i,o]=e;return{x:()=>sw(i.shape,n,o,s,a),filter:()=>C3(i,n,o.shape,s,a)}}},A3={kernelName:xo,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(Vn(Km(gt(t,"float32"))),n)}}},R3={kernelName:Ii,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(qm(gt(t,"float32")),n)}}},_3={kernelName:nu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{axis:s,exclusive:a,reverse:i}=t;return{x:()=>{const o=Ir([s],r.rank);let l=Mm(n,s,a,!i);return o!=null&&(l=Qt(l,o)),l}}}},D3={kernelName:wo,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:r,strides:s,pad:a,dimRoundingMode:i}=t,o=r??[1,1];A(Hl(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[l,p]=e;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),A(l.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),A(bs(s,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${s} and dilations '${o}'.`),Ws("depthwiseConv2d",a,i),{x:()=>jw(l.shape,n,p,s,a,o,i),filter:()=>Hw(l,n,p.shape,s,a,o,i)}}},F3={kernelName:Ms,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[r,s]=e,a={x:r,filter:s,dy:n},i={x:r,filter:s,dy:n};return{x:()=>J.runKernel(On,a,t),filter:()=>J.runKernel(jn,i,t)}}},M3={kernelName:fa,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e,r={dy:n,y:t};return{x:()=>J.runKernel(Qa,r)}}},O3={kernelName:ru,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,r=se(oa(Vn(Mn(t))),2/Math.sqrt(Math.PI));return{x:()=>se(n,r)}}},L3={kernelName:Os,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,t)}}},z3={kernelName:ul,inputsToSave:["input"],gradFunc:(n,e)=>{const[t]=e;return{input:()=>he(n,t.shape)}}},P3={kernelName:vo,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,oa(t))}}},B3={kernelName:ko,gradFunc:n=>({x:()=>mn(n)})},V3={kernelName:No,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{const a=Lt(n,gt(r,"float32")),i=er(t.shape,s);return i.length>0?he(Dt(a,i),t.shape):a},b:()=>{let a=se(n,gt(t,"float32"));const i=er(r.shape,s);i.length>0&&(a=he(Dt(a,i),r.shape));const o=Mn(r);return Vn(Lt(a,gt(o,"float32")))}}}},U3={kernelName:hl,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,e,t)=>{const{varianceEpsilon:r}=t,[s,a,i,o]=e,l=o??Pt(1),p=er(a.shape,s.shape),c=[];if(a.rank===1){for(let y=0;y<s.shape.length-1;++y)c.push(s.shape[y]);c.push(1)}const h=ot(s,a),d=se(n,l),m=Gm(Ue(i,Pt(r))),g=se(se(se(m,m),m),Pt(-.5));return{x:()=>a.rank===1?he(se(se(n,Ua(he(m,[1,1,1,a.shape[0]]),c)),l),s.shape):he(se(se(n,m),l),s.shape),mean:()=>{let y=se(se(m,Pt(-1)),d);return a.rank===1&&(y=Dt(y,p)),he(y,a.shape)},variance:()=>{let y=se(se(g,h),d);return a.rank===1&&(y=Dt(y,p)),he(y,a.shape)},scale:()=>{const y=se(h,m);let w=se(n,y);return a.rank===1&&(w=Dt(w,p)),he(w,a.shape)},offset:()=>{let y=n;return a.rank===1&&(y=Dt(y,p)),he(y,a.shape)}}}},W3={kernelName:xn,inputsToSave:["x","indices"],gradFunc:(n,e,t)=>{const[r,s]=e,{axis:a,batchDims:i}=t,o=Oe(a,r.shape)[0],l=(p,c,h)=>()=>{const d=p.shape,m=c.size,g=d.slice(0,o),y=g.length,w=d.slice(a,d.length).slice(1),v=w.length,N=A2(0,y),T=A2(y+1,y+1+v),$=R2([g,[m],w]),_=he(h,$),L=he(c,[m]),z=R2([[y],N,T]),O=Qt(_,z);let V=Jm(O,L,p.shape[o]);const U=Kl(z);return V=Qt(V,U),V};if(i===1){const p=r.shape[0],c=r.split(p,0);return{x:()=>Hs(c.map((d,m)=>l(d,s.slice(m,1),n.slice(m,1))())).reshape(r.shape),indices:()=>s}}return{x:l(r,s,n),indices:()=>s}}};function A2(n,e){const t=[];for(let r=n;r<e;++r)t.push(r);return t}function R2(n){const e=[];for(let t=0;t<n.length;++t)for(let r=0;r<n[t].length;++r)e.push(n[t][r]);return e}const G3={kernelName:Ht,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e;return{a:()=>mn(t),b:()=>mn(r)}}},H3={kernelName:Ja,gradFunc:n=>({x:()=>gt(n,"float32")})},j3={kernelName:Ci,gradFunc:n=>({x:()=>mn(n)})},K3={kernelName:ps,gradFunc:n=>({x:()=>mn(n)})},q3={kernelName:ns,gradFunc:n=>({x:()=>mn(n)})}
vendor: 4,351 bytes, line 73
73,X3={kernelName:rr,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{alpha:s}=t,a=Gs(r,0);return{x:()=>os(a,n,se(n,s))}}},Y3={kernelName:Ai,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,Ue(t,1))}}},Z3={kernelName:Ft,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,gt(t,"float32"))}}},Q3={kernelName:Kh,inputsToSave:[],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[r]=e,{axis:s}=t;return{logits:()=>{const a=oa(r);return ot(n,se(Dt(n,s,!0),a))}}}},J3=ee({localResponseNormalizationBackprop_:function(n,e,t,r=5,s=1,a=1,i=.5){const o={x:n,y:e,dy:t},l={depthRadius:r,bias:s,alpha:a,beta:i};return J.runKernel(Ma,o,l)}}),eE={kernelName:au,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[r,s]=e,{depthRadius:a,bias:i,alpha:o,beta:l}=t;return{x:()=>J3(r,s,n,a,i,o,l)}}};function _2(n,e,t,r){return e.rank<t.rank&&(e=he(e,Mr(e.shape,r))),n.rank<t.rank&&(n=he(n,Mr(n.shape,r))),{x:()=>se(n,gt(Ia(t,e),n.dtype))}}const D2={kernelName:iu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const r=t,{reductionIndices:s}=r,a=e[0],i=_2(n,e[1],a,Oe(s,a.shape));return{x:()=>i.x()}}},tE={kernelName:To,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e;return{a:()=>se(n,gt(Mu(t,r),"float32")),b:()=>se(n,gt(Ld(t,r),"float32"))}}},nE=ee({maxPool3dGrad_:function(n,e,t,r,s,a,i){const o=P(n,"dy","maxPool3dGrad"),l=P(e,"input","maxPool3dGrad"),p=P(t,"output","maxPool3dGrad");let c=o,h=l,d=p,m=!1;l.rank===4&&(m=!0,c=he(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=he(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=he(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]])),A(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),A(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),Ws("maxPool3dGrad",a,i);const g={dy:c,input:h,output:d},y={filterSize:r,strides:s,pad:a,dimRoundingMode:i},w=J.runKernel(Rc,g,y);return m?he(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}}),rE={kernelName:Oa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[r,s]=e,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=t;return{x:()=>nE(n,r,s,a,i,o,l)}}},sE=ee({maxPoolGrad_:function(n,e,t,r,s,a,i){const o=P(n,"dy","maxPoolGrad"),l=P(e,"input","maxPoolGrad"),p=P(t,"output","maxPoolGrad");A(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),A(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Ws("maxPoolGrad",a,i);const c={dy:o,input:l,output:p},h={filterSize:r,strides:s,pad:a,dimRoundingMode:i};return J.runKernel(pl,c,h)}}),aE={kernelName:Ac,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[r,s]=e,{filterSize:a,strides:i,pad:o}=t;return{x:()=>sE(n,r,s,a,i,o)}}},iE={kernelName:_i,inputsToSave:["x"],gradFunc:(n,e,t)=>{const r=e[0],{paddings:s}=t,a=s.map(i=>i[0]);return{x:()=>Tn(n,a,r.shape)}}},F2={kernelName:yl,inputsToSave:["x"],gradFunc:(n,e,t)=>{const r=e[0],{paddings:s}=t,a=s.map(i=>i[0]);return{x:()=>Tn(n,a,r.shape)}}},oE={kernelName:bl,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,e)=>{const[t,r,s]=e,a=t,i=r,o=Gt(a.shape,i.shape);return{a:()=>{const l=gt(i,"float32");let p=se(n,se(l,Ar(a,ot(l,Pt(1)))));const c=er(a.shape,o);return c.length>0&&(p=Dt(p,c)),he(p,a.shape)},b:()=>{const l=Gs(a,0),p=os(l,Sa(a),mn(a));let c=se(n,se(s,p));const h=er(i.shape,o);return h.length>0&&(c=Dt(c,h)),he(c,i.shape)}}}},uE={kernelName:Sl,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const r=Gs(t,Pt(0)),s=Pt(cg),a=Pt(hg),i=se(n,a),o=se(se(n,s),oa(gt(t,"float32")));return os(r,i,o)}}}},M2={kernelName:Tl,gradFunc:(n,e,t)=>{const{blockShape:r,paddings:s}=t;return{x:()=>Yp(n,r,s)}}},O2={kernelName:El,gradFunc:(n,e,t)=>{const{axis:r}=t;return{x:()=>Fr(n,r)}}},lE=[$2,r3,s3,a3,i3,o3,u3,l3,c3,h3,d3,p3,m3,y3,b3,x3,w3,v3,k3,N3,I3,S3,E3,T3,$3,A3,R3,_3,D3,F3,{kernelName:Ti,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{const a=Lt(n,gt(r,"float32")),i=er(t.shape,s);return i.length>0?he(Dt(a,i),t.shape):a},b:()=>{let a=se(n,gt(t,"float32"));const i=er(r.shape,s);i.length>0&&(a=he(Dt(a,i),r.shape));const o=Mn(r);
73return Vn(Lt(a,gt(o,"float32")))}}}},M3,O3,L3,z3,P3,V3,B3,U3,W3,G3,H3,j3,K3,q3,X3,Y3,Z3,Q3,eE,D2,D2,tE,rE,aE,{kernelName:fl,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{axis:s}=t,a=Oe(s,r.shape),i=j(us(r.shape,a)[1]);return{x:()=>{const o=r.shape.slice();a.forEach(p=>{o[p]=1});const l=he(n,o);return Lt(se(l,ua(r.shape,"float32")),i)}}}},{kernelName:ml,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const r=t,{axis:s}=r,[a,i]=e,o=_2(n,i,a,Oe(s,a.shape));return{x:()=>o.x()}}},{kernelName:Ri,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e;return{a:()=>se(n,gt(ql(t,r),"float32")),b:()=>se(n,gt(Gs(t,r),"float32"))}}},iE,{kernelName:Eo,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{const a=er(t.shape,s);return a.length>0?he(Dt(n,a),t.shape):n},b:()=>{const a=se(n,Vn(Md(Lt(t,r)))),i=er(r.shape,s);return i.length>0?he(Dt(a,i),r.shape):a}}}},{kernelName:Di,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{const a=se(n,gt(r,"float32")),i=er(t.shape,s);return i.length>0?he(Dt(a,i),t.shape):a},b:()=>{const a=se(n,gt(t,"float32")),i=er(r.shape,s);return i.length>0?he(Dt(a,i),r.shape):a}}}},{kernelName:Co,gradFunc:n=>({x:()=>Vn(n)})},{kernelName:ou,inputsToSave:["indices"],gradFunc:(n,e)=>{const t=e[0];return{indices:()=>Wr(t.shape,"float32")}}},{kernelName:gl,gradFunc:n=>({x:()=>mn(n)})},{kernelName:Mc,saveAllInputs:!0,gradFunc:(n,e,t)=>{const{axis:r}=t;return Ga(n,r).map(s=>()=>s)}},F2,F2,oE,{kernelName:ti,inputsToSave:["x","alpha"],gradFunc:(n,e)=>{const[t,r]=e,s=Gs(t,0);return{x:()=>os(s,n,se(n,r)),alpha:()=>{let a=os(s,mn(n),se(n,t));const i=er(r.shape,n.shape);return i.length>0&&(a=Dt(a,i)),he(a,r.shape)}}}},{kernelName:Fi,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{axis:s}=t;let a=[];return a=s==null?r.shape.map((i,o)=>o):typeof s=="number"?[s]:s,{x:()=>function(i,o,l){const p=i.shape.length,c=p-l.length,h=Ir(l,p);let d=i;h!=null&&(d=Qt(i,h));const m=d.shape.slice(),g=m.splice(p-l.length,l.length).reduce((w,v)=>w*v,1);m.push(g);let y=function(w,v,N){const T=w.shape.slice();T[N]=1;const $=he(v,T),_=Qp(w,N,!0,!1),L=Qp(w,N,!0,!0),z=se(_,L);return se($,z)}(d.reshape(m),o,c);if(y=y.reshape(d.shape),h!=null){const w=Kl(h);y=Qt(y,w)}return y}(r,n,a)}}},{kernelName:Ro,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,Vn(Mn(t)))}}},{kernelName:Do,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,r=se(ql(t,6),mh(t));return{x:()=>se(n,gt(r,"float32"))}}},{kernelName:Oi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,gt(mh(t),"float32"))}}},{kernelName:_o,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>he(n,t.shape)}}},{kernelName:vl,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[r]=e,s={dy:n,images:r};return{images:()=>J.runKernel(kl,s,t)}}},{kernelName:Es,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[r]=e,s={dy:n,images:r};return{images:()=>J.runKernel(wl,s,t)}}},{kernelName:Nl,gradFunc:(n,e,t)=>{const{dims:r}=t,s=Oe(r,n.shape);return{x:()=>Wa(n,s)}}},{kernelName:Fo,gradFunc:n=>({x:()=>mn(n)})},{kernelName:lu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Vn(Lt(n,se(Ar(t,1.5),2)))}}},{kernelName:Il,inputsToSave:["condition"],gradFunc:(n,e)=>{const[t]=e;return{condition:()=>gt(mn(t),"float32"),t:()=>se(n,gt(t,n.dtype)),e:()=>se(n,gt(nf(t),n.dtype))}}},uE,{kernelName:du,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,se(t,ot(Pt(1),t)))}}},{kernelName:hu,gradFunc:n=>({x:()=>mn(n)})},{kernelName:zi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(Zp(gt(t,"float32")),n)}}},{kernelName:Mo,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(Fm(gt(t,"float32")),n)}}},{kernelName:Lc,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{begin:s,size:a}=t,i=r.shape,[o,l]=rn(r,s,a),p=[];for(let c=0;c<n.rank;c++)p.push([o[c],i[c]-o[c]-l[c]]);return{x:()=>Ou(n,p)}}},{kernelName:mu,outputsToSave:[!0],gradFunc:(n,e,t)=>{const[r]=e,{dim:s}=t,a=se(n,r);return{logits:()=>ot(a,se(Dt(a,[s],!0),r))}}},{kernelName:pu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,eo(t))}}},M2,M2,O2,O2,{kernelName:fu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,se(qn(gt(t,"float32")),2))}}},{kernelName:bu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Pt(2);return{a:()=>se(n,se(s,ot(t,r))),b:()=>se(n,se(s,ot(r,t)))}}},{kernelName:zc,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,se(gt(t,"float32"),2))}}},{kernelName:ra,gradFunc:n=>({x:()=>mn(n)})},{kernelName:Rl,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,r]=e,s=Gt(t.shape,r.shape);return{a:()=>{let a=n;const i=er(t.shape,s);return i.length>
vendor: 12,798 bytes, line 73
730&&(a=Dt(a,i)),he(a,t.shape)},b:()=>{let a=n;const i=er(r.shape,s);return i.length>0&&(a=Dt(a,i)),he(Vn(a),r.shape)}}}},{kernelName:La,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,s=r.shape.slice(),{axis:a}=t;Oe(a,r.shape).forEach(l=>{s[l]=1});const i=he(n,s),o=se(i,ua(r.shape,"float32"));return{x:()=>o}}},{kernelName:xu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Lt(n,Mn(Zp(t)))}}},{kernelName:wu,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(ot(Pt(1),Mn(t)),n)}}},{kernelName:vu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[r]=e,{reps:s}=t;return{x:()=>{let a=mn(r);if(r.rank===1)for(let i=0;i<s[0];++i)a=Ue(a,Tn(n,[i*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(let i=0;i<s[0];++i)for(let o=0;o<s[1];++o)a=Ue(a,Tn(n,[i*r.shape[0],o*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(let i=0;i<s[0];++i)for(let o=0;o<s[1];++o)for(let l=0;l<s[2];++l)a=Ue(a,Tn(n,[i*r.shape[0],o*r.shape[1],l*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(r.rank!==4)throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);for(let i=0;i<s[0];++i)for(let o=0;o<s[1];++o)for(let l=0;l<s[2];++l)for(let p=0;p<s[3];++p)a=Ue(a,Tn(n,[i*r.shape[0],o*r.shape[1],l*r.shape[2],p*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return a}}}},{kernelName:Oo,gradFunc:(n,e,t)=>{const r=t,{perm:s}=r,a=Kl(s);return{x:()=>Qt(n,a)}}},{kernelName:na,gradFunc:(n,e,t)=>{const r=t,{axis:s}=r;return{value:()=>Hs(n,s)}}},{kernelName:mr,inputsToSave:["segmentIds"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>function(r,s){const a=Nr(s,mn(s)),i=Od(r,a);let o=Mu(s,Pt(0,"int32"));const l=i.rank-o.rank;for(let c=0;c<l;++c)o=ws(o,c+1);o=ci(o,ua(i.shape,"bool"));const p=mn(i);return os(o,i,p)}(n,t)}}},{kernelName:ku,gradFunc:n=>({x:()=>mn(n)})}];for(const n of lE)em(n);_e().prototype.abs=function(){return this.throwIfDisposed(),An(this)},_e().prototype.acos=function(){return this.throwIfDisposed(),My(this)},_e().prototype.acosh=function(){return this.throwIfDisposed(),Oy(this)},_e().prototype.add=function(n){return this.throwIfDisposed(),Ue(this,n)},_e().prototype.all=function(n,e){return this.throwIfDisposed(),Rm(this,n,e)},_e().prototype.any=function(n,e){return this.throwIfDisposed(),Hp(this,n,e)},_e().prototype.argMax=function(n){return this.throwIfDisposed(),uh(this,n)},_e().prototype.argMin=function(n){return this.throwIfDisposed(),Ly(this,n)},_e().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),he(this,[])},_e().prototype.asType=function(n){return this.throwIfDisposed(),gt(this,n)},_e().prototype.as1D=function(){return this.throwIfDisposed(),he(this,[this.size])},_e().prototype.as2D=function(n,e){return this.throwIfDisposed(),he(this,[n,e])},_e().prototype.as3D=function(n,e,t){return this.throwIfDisposed(),he(this,[n,e,t])},_e().prototype.as4D=function(n,e,t,r){return this.throwIfDisposed(),he(this,[n,e,t,r])},_e().prototype.as5D=function(n,e,t,r,s){return this.throwIfDisposed(),he(this,[n,e,t,r,s])},_e().prototype.asin=function(){return this.throwIfDisposed(),zy(this)},_e().prototype.asinh=function(){return this.throwIfDisposed(),Py(this)},_e().prototype.atan=function(){return this.throwIfDisposed(),By(this)},_e().prototype.atan2=function(n){return this.throwIfDisposed(),Vy(this,n)},_e().prototype.atanh=function(){return this.throwIfDisposed(),Uy(this)},_e().prototype.avgPool=function(n,e,t,r){return this.throwIfDisposed(),Xp(this,n,e,t,r)},_e().prototype.batchToSpaceND=function(n,e){return this.throwIfDisposed(),Yp(this,n,e)},_e().prototype.batchNorm=function(n,e,t,r,s){return this.throwIfDisposed(),Ad(this,n,e,t,r,s)},_e().prototype.broadcastTo=function(n){return this.throwIfDisposed(),ch(this,n)},_e().prototype.cast=function(n){return this.throwIfDisposed(),gt(this,n)},_e().prototype.ceil=function(){return this.throwIfDisposed(),Yy(this)},_e().prototype.clipByValue=function(n,e){return this.throwIfDisposed(),ia(this,n,e)},_e().prototype.concat=function(n,e){return this.throwIfDisposed(),n instanceof Sn&&(n=[n]),Fr([this,...n],e)},_e().prototype.conv1d=function(n,e,t,r,s,a){return this.throwIfDisposed(),_m(this,n,e,t,r,s,a)},_e().prototype.conv2dTranspose=function(n,e,t,r,s){return this.throwIfDisposed(),Dm(this,n,e,t,r,s)},_e().prototype.conv2d=function(n,e,t,r,s,a){return this.throwIfDisposed(),Fu(this,n,e,t,r,s,a)},_e().prototype.cos=function(){return this.throwIfDisposed(),Zp(this)},_e().prototype.cosh=function(){return this.throwIfDisposed(),Fm(this)},_e().prototype.cumprod=function(n,e,t){return this.throwIfDisposed(),Qp(this,n,e,t)},_e().prototype.cumsum=function(n,e,t){return this.throwIfDisposed(),Mm(this,n,e,t)},_e().prototype.depthToSpace=function(n,e){return this.throwIfDisposed(),a0(this,n,e)},_e().prototype.depthwiseConv2d=function(n,e,t,r,s,a){return this.throwIfDisposed(),Rd(this,n,e,t,r,s,a)},_e().prototype.dilation2d=function(n,e,t,r,s){return this.throwIfDisposed(),i0(this,n,e,t,r,s)},_e().prototype.divNoNan=function(n){return this.throwIfDisposed(),o0(this,n)},_e().prototype.div=function(n){return this.throwIfDisposed(),Lt(this,n)},_e().prototype.dot=function(n){return this.throwIfDisposed(),u0(this,n)},_e().prototype.elu=function(){return this.throwIfDisposed(),_d(this)},_e().prototype.equal=function(n){return this.throwIfDisposed(),Ia(this,n)},_e().prototype.erf=function(){return this.throwIfDisposed(),Om(this)},_e().prototype.euclideanNorm=function(n,e){return this.throwIfDisposed(),c0(this,n,e)},_e().prototype.exp=function(){return this.throwIfDisposed(),oa(this)},_e().prototype.expandDims=function(n){return this.throwIfDisposed(),ws(this,n)},_e().prototype.expm1=function(){return this.throwIfDisposed(),h0(this)},_e().prototype.fft=function(){return this.throwIfDisposed(),hf(this)},_e().prototype.flatten=function(){return this.throwIfDisposed(),he(this,[this.size])},_e().prototype.floor=function(){return this.throwIfDisposed(),Md(this)},_e().prototype.floorDiv=function(n){return this.throwIfDisposed(),Jc(this,n)},_e().prototype.gather=function(n,e,t){return this.throwIfDisposed(),Od(this,n,e,t)},_e().prototype.greaterEqual=function(n){return this.throwIfDisposed(),Mu(this,n)},_e().prototype.greater=function(n){return this.throwIfDisposed(),Gs(this,n)},_e().prototype.ifft=function(){return this.throwIfDisposed(),Bd(this)},_e().prototype.irfft=function(){return this.throwIfDisposed(),Ym(this)},_e().prototype.isFinite=function(){return this.throwIfDisposed(),d0(this)},_e().prototype.isInf=function(){return this.throwIfDisposed(),p0(this)},_e().prototype.isNaN=function(){return this.throwIfDisposed(),f0(this)},_e().prototype.leakyRelu=function(n){return this.throwIfDisposed(),Jp(this,n)},_e().prototype.lessEqual=function(n){return this.throwIfDisposed(),ql(this,n)},_e().prototype.less=function(n){return this.throwIfDisposed(),Ld(this,n)},_e().prototype.localResponseNormalization=function(n,e,t,r){return this.throwIfDisposed(),m0(this,n,e,t,r)},_e().prototype.logSigmoid=function(){return this.throwIfDisposed(),g0(this)},_e().prototype.logSoftmax=function(n){return this.throwIfDisposed(),zm(this,n)},_e().prototype.logSumExp=function(n,e){return this.throwIfDisposed(),tf(this,n,e)},_e().prototype.log=function(){return this.throwIfDisposed(),Sa(this)},_e().prototype.log1p=function(){return this.throwIfDisposed(),ef(this)},_e().prototype.logicalAnd=function(n){return this.throwIfDisposed(),ci(this,n)},_e().prototype.logicalNot=function(){return this.throwIfDisposed(),nf(this)},_e().prototype.logicalOr=function(n){return this.throwIfDisposed(),Pm(this,n)},_e().prototype.logicalXor=function(n){return this.throwIfDisposed(),y0(this,n)},_e().prototype.matMul=function(n,e,t){return this.throwIfDisposed(),Yt(this,n,e,t)},_e().prototype.maxPool=function(n,e,t,r){return this.throwIfDisposed(),rf(this,n,e,t,r)},_e().prototype.max=function(n,e){return this.throwIfDisposed(),Va(this,n,e)},_e().prototype.maximum=function(n){return this.throwIfDisposed(),Nr(this,n)},_e().prototype.mean=function(n,e){return this.throwIfDisposed(),Sr(this,n,e)},_e().prototype.min=function(n,e){return this.throwIfDisposed(),Dd(this,n,e)},_e().prototype.minimum=function(n){return this.throwIfDisposed(),Xl(this,n)},_e().prototype.mirrorPad=function(n,e){return this.throwIfDisposed(),x0(this,n,e)},_e().prototype.mod=function(n){return this.throwIfDisposed(),w0(this,n)},_e().prototype.mul=function(n){return this.throwIfDisposed(),se(this,n)},_e().prototype.neg=function(){return this.throwIfDisposed(),Vn(this)},_e().prototype.norm=function(n,e,t){return this.throwIfDisposed(),Fd(this,n,e,t)},_e().prototype.notEqual=function(n){return this.throwIfDisposed(),ph(this,n)},_e().prototype.oneHot=function(n,e=1,t=0){return this.throwIfDisposed(),Ur(this,n,e,t)},_e().prototype.onesLike=function(){return this.throwIfDisposed(),Ta(this)},_e().prototype.pad=function(n,e){return this.throwIfDisposed(),Ou(this,n,e)},_e().prototype.pool=function(n,e,t,r,s,a){return this.throwIfDisposed(),v0(this,n,e,t,r,s,a)},_e().prototype.pow=function(n){return this.throwIfDisposed(),Ar(this,n)},_e().prototype.prelu=function(n){return this.throwIfDisposed(),of(this,n)},_e().prototype.prod=function(n,e){return this.throwIfDisposed(),k0(this,n,e)},_e().prototype.reciprocal=function(){return this.throwIfDisposed(),I0(this)},_e().prototype.relu=function(){return this.throwIfDisposed(),to(this)},_e().prototype.relu6=function(){return this.throwIfDisposed(),Um(this)},_e().prototype.reshapeAs=function(n){return this.throwIfDisposed(),he(this,n.shape)},_e().prototype.reshape=function(n){return this.throwIfDisposed(),he(this,n)},_e().prototype.resizeBilinear=function(n,e,t){return this.throwIfDisposed(),Yw(this,n,e,t)},_e().prototype.resizeNearestNeighbor=function(n,e,t){return this.throwIfDisposed(),Zw(this,n,e,t)},_e().prototype.reverse=function(n){return this.throwIfDisposed(),Wa(this,n)},_e().prototype.rfft=function(){return this.throwIfDisposed(),df(this)},_e().prototype.round=function(){return this.throwIfDisposed(),Wm(this)},_e().prototype.rsqrt=function(){return this.throwIfDisposed(),Gm(this)},_e().prototype.selu=function(){return this.throwIfDisposed(),Hm(this)},_e().prototype.separableConv2d=function(n,e,t,r,s,a){return this.throwIfDisposed(),jm(this,n,e,t,r,s,a)},_e().prototype.sigmoid=function(){return this.throwIfDisposed(),eo(this)},_e().prototype.sign=function(){return this.throwIfDisposed(),S0(this)},_e().prototype.sin=function(){return this.throwIfDisposed(),Km(this)},_e().prototype.sinh=function(){return this.throwIfDisposed(),qm(this)},_e().prototype.slice=function(n,e){return this.throwIfDisposed(),Tn(this,n,e)},_e().prototype.softmax=function(n){return this.throwIfDisposed(),cf(this,n)},_e().prototype.softplus=function(){return this.throwIfDisposed(),dh(this)},_e().prototype.spaceToBatchND=function(n,e){return this.throwIfDisposed(),af(this,n,e)},_e().prototype.split=function(n,e){return this.throwIfDisposed(),la(this,n,e)},_e().prototype.sqrt=function(){return this.throwIfDisposed(),qn(this)},_e().prototype.square=function(){return this.throwIfDisposed(),Mn(this)},_e().prototype.squaredDifference=function(n){return this.throwIfDisposed(),Zm(this,n)},_e().prototype.squeeze=function(n){return this.throwIfDisposed(),Zl(this,n)},_e().prototype.stack=function(n,e){this.throwIfDisposed();const t=n instanceof Sn?[this,n]:[this,...n];return Hs(t,e)},_e().prototype.step=function(n){return this.throwIfDisposed(),mh(this,n)},_e().prototype.stridedSlice=function(n,e,t,r,s,a,i,o){return this.throwIfDisposed(),T0(this,n,e,t,r,s,a,i,o)},_e().prototype.sub=function(n){return this.throwIfDisposed(),ot(this,n)},_e().prototype.sum=function(n,e){return this.throwIfDisposed(),Dt(this,n,e)},_e().prototype.tan=function(){return this.throwIfDisposed(),E0(this)},_e().prototype.tanh=function(){return this.throwIfDisposed(),jl(this)},_e().prototype.tile=function(n){return this.throwIfDisposed(),Ua(this,n)},_e().prototype.toBool=function(){return this.throwIfDisposed(),gt(this,"bool")},_e().prototype.toFloat=function(){return this.throwIfDisposed(),gt(this,"float32")},_e().prototype.toInt=function(){return this.throwIfDisposed(),gt(this,"int32")},_e().prototype.topk=function(n,e){return this.throwIfDisposed(),C0(this,n,e)},_e().prototype.transpose=function(n){return this.throwIfDisposed(),Qt(this,n)},_e().prototype.unique=function(n){return this.throwIfDisposed(),$0(this,n)},_e().prototype.unsortedSegmentSum=function(n,e){return this.throwIfDisposed(),Jm(this,n,e)},_e().prototype.unstack=function(n){return this.throwIfDisposed(),Ga(this,n)},_e().prototype.where=function(n,e){return this.throwIfDisposed(),os(n,this,e)},_e().prototype.zerosLike=function(){return this.throwIfDisposed(),mn(this)};
73class Ko extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ko.prototype)}}class di extends Error{constructor(e){super(e),Object.setPrototypeOf(this,di.prototype)}}class ce extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ce.prototype)}}class gn extends Error{constructor(e){super(e),Object.setPrototypeOf(this,gn.prototype)}}class a1 extends Error{constructor(e){super(e),Object.setPrototypeOf(this,a1.prototype)}}class L2{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const r=this.cache.keys().next().value;this.cache.delete(r)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const r=this.cache.keys().next().value;this.cache.delete(r)}this.maxEntries=e}}function yh(n,e){if(Array.isArray(n)){let t=[];for(let r=0;r<e;r++)t=t.concat(n);return t}{const t=new Array(e);return t.fill(n),t}}function qo(n,e){if(!n)throw new a1(e)}function z2(n,e){let t=0;for(const r of n)r===e&&t++;return t}function ca(n){return n.length===1?n[0]:n}function Un(n){return Array.isArray(n)?n:[n]}function Bu(n){const e=n.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return e[0]!=="_"?e:"private"+e}function bh(n){return n.length<=1||n.indexOf("_")===-1?n:n.replace(/[_]+(\w|$)/g,(e,t)=>t.toUpperCase())}let pi={};function i1(n){if(n==null)return null;const e={};return e.className=n.getClassName(),e.config=n.getConfig(),e}function o1(n){if(n!=null&&typeof n=="object")if(Array.isArray(n))n.forEach(e=>o1(e));else{const e=Object.keys(n);for(const t of e){const r=n[t];r!=null&&typeof r=="object"&&(Array.isArray(r)||r.type!=="ndarray"||typeof r.value!="number"?o1(r):n[t]=r.value)}}}function gf(n,e={},t={},r="object",s=!1){if(typeof n=="string"){const a=n;let i;if(a in t)i=t[a];else if(a in pi)i=pi[a];else if(i=e[a],i==null)throw new ce(`Unknown ${r}: ${n}. This may be due to one of the following reasons:
741. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
752. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}{const a=n;if(a.className==null||a.config==null)throw new ce(`${r}: Improper config format: ${JSON.stringify(a)}.
76'className' and 'config' must set.`);const i=a.className;let o,l;if(i in t?[o,l]=t[i]:i in pi?[o,l]=pi.className:i in e&&([o,l]=e[i]),o==null)throw new ce(`Unknown ${r}: ${i}. This may be due to one of the following reasons:
771. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
782. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const p={};for(const d of Object.keys(pi))p[d]=pi[d];for(const d of Object.keys(t))p[d]=t[d];a.config.customObjects=p;const c=Object.assign({},pi);for(const d of Object.keys(t))pi[d]=t[d];o1(a.config);const h=l(o,a.config,t,s);return pi=Object.assign({},c),h}{const p=Object.assign({},pi);for(const h of Object.keys(t))pi[h]=t[h];const c=new o(a.config);return pi=Object.assign({},p),c}}}function dg(n,e){return-1*function(t,r){return t<r?-1:t>r?1:0}(n,e)}function Jl(n){if(n==null)return n;const e=[];for(const t of n)e.indexOf(t)===-1&&e.push(t);return e}function cE(n){if(n==null)throw new ce(`Invalid value in obj: ${JSON.stringify(n)}`);for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}function xh(n,e,t){if(t!=null&&n.indexOf(t)<0)throw new ce(`${t} is not a valid ${e}.  Valid values are ${n} or null/undefined.`)}function u1(n,e,t=0,r=1/0){return qo(t>=0),qo(r>=t),Array.isArray(n)&&n.length>=t&&n.length<=r&&n.every(s=>typeof s===e)}function ls(n,e){Array.isArray(n)?(A(n.length>0,()=>`${e}
78 is unexpectedly an empty array.`),n.forEach((t,r)=>ls(t,`element ${r+1} of ${e}`))):A(Number.isInteger(n)&&n>0,()=>`Expected ${e} to be a positive integer, but got ${P2(n)}.`)}function P2(n){return n===null?"null":Array.isArray(n)?"["+n.map(e=>P2(e)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function B2(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}let hE=0;function V2(){return hE++}const pg={};function fg(n=""){return n in pg||(pg[n]=0),pg[n]+=1,n+pg[n].toString()}const dE=["channelsFirst","channelsLast"],pE=["nearest","bilinear"],fE=["valid","same","causal"],mE=["max","avg"],gE=["sum","mul","concat","ave"],Ud=new Map;function Lr(n){xh(dE,"DataFormat",n)}function Ha(n){xh(fE,"PaddingMode",n)}function U2(n){xh(mE,"PoolMode",n)}const yf=[];function wh(n,e){yf.push(n);try{const t=e();return yf.pop(),t}catch(t){throw yf.pop(),t}}function W2(n){if(!H2(n))throw new Error("Not a valid tensor name: '"+n+"'");return(yf.length===0?"":yf.join("/")+"/")+n}function G2(n){if(!H2(n))throw new Error("Not a valid tensor name: '"+n+"'");Ud.has(n)||Ud.set(n,0);const e=Ud.get(n);if(Ud.set(n,Ud.get(n)+1),e>0){const t=`${n}_${e}`;return Ud.set(t,1),t}return n}const yE=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function H2(n){return!!n.match(yE)}function bE(n){return n===parseInt(n.toString(),10)}function ec(n,e,t){e==null&&(e=0),t==null&&(t=n.length);let r=1;for(let s=e;s<t;++s)r*=n[s];return r}function Wd(n){if(n.length===0)return Number.NaN;let e=Number.POSITIVE_INFINITY;for(let t=0;t<n.length;t++){const r=n[t];r<e&&(e=r)}return e}function tc(n){if(n.length===0)return Number.NaN;let e=Number.NEGATIVE_INFINITY;for(let t=0;t<n.length;t++){const r=n[t];r>e&&(e=r)}return e}function ro(n,e){if(e<n)throw new ce(`end (${e}) < begin (${n}) is forbidden.`);const t=[];for(let r=n;r<e;++r)t.push(r);return t}let l1;function Xr(){return l1==null&&(l1=ad().epsilon()),l1}function Vu(n,e){return gt(n,e)}function bf(n,e=-1){const t=n.shape.slice();return e<0&&(e=t.length+e+1),t.splice(e,0,1),he(n,t)}function vh(n,e,t){return be(()=>{switch(n.rank){case 1:return uf(n,e,t);case 2:return Xm(n,[e,0],[t,n.shape[1]]);case 3:return lf(n,[e,0,0],[t,n.shape[1],n.shape[2]]);case 4:return Pd(n,[e,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3]]);case 5:return Tn(n,[e,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return Tn(n,[e,0,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new ce(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function c1(n,e,t){return be(()=>{switch(n.rank){case 1:return uf(n,e,t);case 2:return Xm(n,[0,e],[n.shape[0],t]);case 3:return lf(n,[0,0,e],[n.shape[0],n.shape[1],t]);case 4:return Pd(n,[0,0,0,e],[n.shape[0],n.shape[1],n.shape[2],t]);default:throw new ce(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function mg(n,e,t,r){return be(()=>{switch(n.rank){case 1:return uf(n,e,t);case 2:switch(r){case 1:return vh(n,e,t);case 2:return c1(n,e,t);default:throw new ce(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return vh(n,e,t);case 2:return lf(n,[0,e,0],[n.shape[0],t,n.shape[2]]);case 3:return c1(n,e,t);default:throw new ce(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return vh(n,e,t);case 2:return Pd(n,[0,e,0,0],[n.shape[0],t,n.shape[2],n.shape[3]]);case 3:return Pd(n,[0,0,e,0],[n.shape[0],n.shape[1],t,n.shape[3]]);case 4:return c1(n,e,t);default:throw new ce(`The axis is not within the rank of the tensor ${r}`)}default:throw new ce(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function h1(n,e=-1){let t;return e<0&&(t=n[0].rank,e=t!==0?t:0),e===n[0].rank&&(e=-1),Fr(n,e)}function j2(n,e){switch(n.rank){case 1:return Zy([n,e]);case 2:return Qy([n,e],0);case 3:return Jy([n,e],0);case 4:return e0([n,e],0);default:throw new ce(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function d1(n,e){if(Array.isArray(e)||(e=[e]),n.rank!==e.length)throw new ce(`The length of input n (${e.length}) does not match the number of dimensions in input x (${n.rank})`);return Ua(n,e)}function gg(n,e=0,t=1,r,s){return Vm(n,e,t,r,s)}function Uu(n,e,t,r){if(n.rank<2||e.rank<2)throw new gn(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${e.shape}`);if(e.rank>=3&&n.shape.slice(-1)[0]!==e.shape.slice(-2)[0])throw new gn(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and  y shape = ${e.shape}`);if(n.rank===2&&e.rank===2)return M0({a:n,b:e,transposeA:!1,transposeB:!1,bias:r?p1(n.rank,r,"channelsLast"):null,activation:t});{const s=n.shape.slice(),a=s.pop();n=he(n,[-1,a]);const i=e.shape.slice(),o=i.pop(),l=i.pop(),p=[...i,o],c=Array.from({length:e.rank},(d,m)=>m===0?e.rank-2:m<=e.rank-2?m-1:m);e=he(Qt(e,c),[l,-1]);const h=[...s,...p];return he(M0({a:n,b:e,transposeA:!1,transposeB:!1,bias:r?p1(n.rank,r,"channelsLast"):null,activation:t}),h)}}function K2(n,e,t){return be(()=>(e=Array.isArray(e)?vs(e,"int32"):gt(e,"int32"),Od(n,e,t)))}function xf(n){return se(n,n)}function p1(n,e,t){const r=e.shape;if(e.rank!==1&&e.rank!==n)throw new ce(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${n}`);if(n===5){if(t==="channelsFirst")return r.length===1?he(e,[1,r[0],1,1,1]):he(e,[1,r[3],r[0],r[1],r[2]]);if(t==="channelsLast")return r.length===1?he(e,[1,1,1,1,r[0]]):he(e,[1].concat(r))}else if(n===4){if(t==="channelsFirst")return r.length===1?he(e,[1,r[0],1,1]):he(e,[1,r[2],r[0],r[1]]);if(t==="channelsLast")return r.length===1?he(e,[1,1,1,r[0]]):he(e,[1].concat(r))}else if(n===3){if(t==="channelsFirst")return r.length===1?he(e,[1,r[0],1]):he(e,[1,r[1],r[0]]);if(t==="channelsLast")return r.length===1?he(e,[1,1,r[0]]):he(e,[1].concat(r))}else if(n<3)return e;throw new ce(`Unsupported input rank by biasAdd: ${e.rank}`)}function so(n,e,t){return be(()=>(t==null&&(t="channelsLast"),Lr(t),Ue(n,p1(n.rank,e,t))))}function q2(n,e,t,r){return be(()=>_0(n,e,t,r))}function wf(n,e,t=!1){return t?n():e()}const xE=["fanIn","fanOut","fanAvg"],wE=["normal","uniform","truncatedNormal"];class fi extends ii{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class f1 extends fi{apply(e,t){return Wr(e,t)}}f1.className="Zeros",st(f1);class yg extends fi{apply(e,t){return ua(e,t)}}yg.className="Ones",st(yg);class m1 extends fi{constructor(e){if(super(),typeof e!="object")throw new ce(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new ce(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return be(()=>se(Pt(this.value),ua(e,t)))}getConfig(){return{value:this.value}}}m1.className="Constant",st(m1);class g1 extends fi{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Yl(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}g1.className="RandomUniform",st(g1);class y1 extends fi{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if((t=t||"float32")!=="float32"&&t!=="int32")throw new gn(`randomNormal does not support dType ${t}.`);return gg(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}y1.className="RandomNormal",st(y1);class b1 extends fi{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if((t=t||"float32")!=="float32"&&t!=="int32")throw new gn(`truncatedNormal does not support dType ${t}.`);return Qm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}
78b1.className="TruncatedNormal",st(b1);class x1 extends fi{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return be(()=>{if(e.length!==2||e[0]!==e[1])throw new ce("Identity matrix initializer can only be used for 2D square matrices.");return se(this.gain,Lm(e[0]))})}getConfig(){return{gain:this.gain}}}x1.className="Identity",st(x1);class ha extends fi{constructor(e){if(super(),e.scale<0)throw new ce(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,t=this.mode,xh(xE,"FanMode",t),this.distribution=e.distribution==null?"normal":e.distribution,function(r){xh(wE,"Distribution",r)}(this.distribution),this.seed=e.seed}apply(e,t){const r=function(o,l="channelsLast"){let p,c;if(Lr(l),o.length===2)p=o[0],c=o[1];else if([3,4,5].indexOf(o.length)!==-1){if(l==="channelsFirst"){const h=ec(o,2);p=o[1]*h,c=o[0]*h}else if(l==="channelsLast"){const h=ec(o,0,o.length-2);p=o[o.length-2]*h,c=o[o.length-1]*h}}else{const h=ec(o);p=Math.sqrt(h),c=Math.sqrt(h)}return[p,c]}(e),s=r[0],a=r[1];let i=this.scale;if(this.mode==="fanIn"?i/=Math.max(1,s):this.mode==="fanOut"?i/=Math.max(1,a):i/=Math.max(1,(s+a)/2),this.distribution==="normal"){const o=Math.sqrt(i);if((t=t||"float32")!=="float32"&&t!=="int32")throw new gn(`${this.getClassName()} does not support dType ${t}.`);return Qm(e,0,o,t,this.seed)}{const o=Math.sqrt(3*i);return Yl(e,-o,o,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ha.className="VarianceScaling",st(ha);class bg extends ha{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ha.className}}bg.className="GlorotUniform",st(bg);class xg extends ha{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ha.className}}xg.className="GlorotNormal",st(xg);class wg extends ha{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ha.className}}wg.className="HeNormal",st(wg);class vg extends ha{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ha.className}}vg.className="HeUniform",st(vg);class kg extends ha{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ha.className}}kg.className="LeCunNormal",st(kg);class Ng extends ha{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ha.className}}Ng.className="LeCunUniform",st(Ng);class w1 extends fi{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return be(()=>{if(e.length<2)throw new gn("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);const r=j(e.slice(0,-1)),s=e[e.length-1],a=r*s;a>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${a}) elements: Slowness may result.`);const i=gg([Math.max(s,r),Math.min(s,r)],0,1,t,this.seed),o=L0.qr(i,!1);let l=o[0];const p=o[1].flatten().stridedSlice([0],[Math.min(s,r)*Math.min(s,r)],[Math.min(s,r)+1]);return l=se(l,p.sign()),r<s&&(l=l.transpose()),se(Pt(this.gain),l.reshape(e))})}getConfig(){return{gain:this.gain,seed:this.seed}}}w1.className="Orthogonal",st(w1);const X2={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Y2(n,e={}){return gf(n,as.getMap().classNameMap,e,"initializer")}function Tr(n){return i1(n)}function xr(n){if(typeof n=="string"){const e=n in X2?X2[n]:n;if(e==="GlorotNormal")return new xg;if(e==="GlorotUniform")return new bg;if(e==="HeNormal")return new wg;if(e==="HeUniform")return new vg;if(e==="LeCunNormal")return new kg;if(e==="LeCunUniform")return new Ng;
vendor: 4,621 bytes, line 78
78{const t={};return t.className=e,t.config={},Y2(t)}}return n instanceof fi?n:Y2(n)}function v1(n){return Array.isArray(n)&&Array.isArray(n[0])}function Ig(n){return n.length===0?[]:Array.isArray(n[0])?n:[n]}function sn(n){let e;if(Array.isArray(n)){if(n.length!==1)throw new ce(`Expected Tensor length to be 1; got ${n.length}`);e=n[0]}else e=n;return e}function Rn(n){if(Array.isArray(n)&&Array.isArray(n[0])){if(n.length===1)return n[0];throw new ce(`Expected exactly 1 Shape; got ${n.length}`)}return n}function Sg(n){let e=0;for(const t of n)t.shape.length===0?e+=1:e+=t.shape.reduce((r,s)=>r*s);return e}const Z2="Variable";class Q2{constructor(e,t="float32",r=Z2,s=!0,a=null){this.dtype=t??"float32",this.shape=e.shape,this.id=V2(),r=r??Z2,this.originalName=W2(r),this.name=G2(this.originalName),this.trainable_=s,this.constraint=a,this.val=A0(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(t,r){if(t.shape.toString()!==r.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(r.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function k1(n){return n.map(e=>e.read())}function N1(n){n.forEach(e=>{e[0].write(e[1])})}class Gr{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class ao{constructor(e,t,r,s,a,i,o){this.dtype=e,this.shape=t,this.sourceLayer=r,this.inputs=s,this.callArgs=a,this.outputTensorIndex=o,this.id=V2(),i!=null&&(this.originalName=W2(i),this.name=G2(this.originalName)),this.rank=t.length}}let vE=0;class Tg{constructor(e,t){this.callArgs=t,this.id=vE++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const r of e.inboundLayers)r?.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let kE=0;class bn extends ii{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=kE++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const r=this.getClassName();t=Bu(r)+"_"+fg(r)}if(this.name=t,this.trainable_=e.trainable==null||e.trainable,e.inputShape!=null||e.batchInputShape!=null){let r;if(e.batchInputShape!=null)r=e.batchInputShape;else if(e.inputShape!=null){let a=null;e.batchSize!=null&&(a=e.batchSize),r=[a].concat(e.inputShape)}this.batchInputShape=r;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new di(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new ce(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return ca(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return ca(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ko(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Ko(`Layer ${this.name} is not connected, no input to return.`);return ca(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Ko(`Layer ${this.name} has no inbound nodes.`);
78if(this.inboundNodes.length>1)throw new Ko(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return ca(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=Un(e);if(this.inputSpec==null||this.inputSpec.length===0)return;const r=Un(this.inputSpec);if(t.length!==r.length)throw new ce(`Layer ${this.name} expects ${r.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let s=0;s<t.length;s++){const a=t[s],i=r[s];if(i==null)continue;const o=a.rank;if(i.ndim!=null&&o!==i.ndim)throw new ce(`Input ${s} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${o}`);if(i.maxNDim!=null&&o>i.maxNDim)throw new ce(`Input ${s} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${o}`);if(i.minNDim!=null&&o<i.minNDim)throw new ce(`Input ${s} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${o}.`);if(i.dtype!=null&&a.dtype!==i.dtype)throw new ce(`Input ${s} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${a.dtype}.`);if(i.axes){const l=a.shape;for(const p in i.axes){const c=Number(p),h=i.axes[p],d=c>=0?l[c]:l[l.length+c];if(h!=null&&[h,null].indexOf(d)===-1)throw new ce(`Input ${s} is incompatible with layer ${this.name}: expected axis ${c} of input shape to have value ${h} but got shape ${l}.`)}}if(i.shape!=null)for(let l=0;l<i.shape.length;++l){const p=i.shape[l],c=a.shape[l];if(p!=null&&c!=null&&p!==c)throw new ce(`Input ${s} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${a.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const r=Un(e),s=function(i){let o=!0;for(const l of Un(i))if(!(l instanceof ao)){o=!1;break}return o}(e),a=function(i){let o=!0;for(const l of Un(i))if(l instanceof ao){o=!1;break}return o}(e);if(s===a)throw new ce("Arguments to apply() must be all SymbolicTensors or all Tensors");return wh(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const i=[];for(const o of Un(e))i.push(o.shape);this.build(ca(i)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let i=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,i);const o=Un(i),l=[];for(let p of o)r.indexOf(p)!==-1&&(p=p.clone()),l.push(p);if(i=ca(l),this.activityRegularizer!=null)throw new gn("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const i=function(c){c=Un(c);const h=[];for(const d of c)h.push(d.shape);return ca(h)}(e),o=this.computeOutputShape(i);let l;const p="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?i[0]:i),l=o!=null&&o.length>0&&Array.isArray(o[0])?o.map((c,h)=>new ao(p,c,this,Un(e),t,this.name,h)):new ao(p,o,this,Un(e),t,this.name),this.addInboundNode(e,l,null,null,i,o,t),this._refCount++,this.activityRegularizer!=null)throw new gn("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return l}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((r,s)=>{r!=null&&e[s]!=null&&e[s]!==r&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}
vendor: 4,760 bytes, line 78
78get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Ko(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const r=JSON.stringify(t.outputShapes);e.indexOf(r)===-1&&e.push(r)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}throw new Ko(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new di(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Sg(this.weights)}build(e){this.built=!0}getWeights(e=!1){return k1(e?this.trainableWeights:this.weights)}setWeights(e){be(()=>{const t=this.weights;if(t.length!==e.length)throw new ce(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;const r=[],s=k1(t);for(let a=0;a<s.length;++a){const i=s[a],o=t[a],l=e[a];if(!le(i.shape,l.shape))throw new ce(`Layer weight shape ${i.shape} not compatible with provided weight shape ${l.shape}`);r.push([o,l])}N1(r)})}addWeight(e,t,r,s,a,i,o,l){if(this._addedWeightNames.indexOf(e)!==-1)throw new ce(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),r==null&&(r="float32"),this.fastWeightInitDuringBuild&&(s=l!=null?l():xr("zeros"));const p=s.apply(t,r),c=new Q2(p,r,e,i,o);return p.dispose(),a!=null&&this.addLoss(()=>a.apply(c.read())),i==null&&(i=!0),i?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Un(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach(r=>{if(r!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)})}return null}return t}setMaskMetadata(e,t,r){if(!this.supportsMasking)return;const s=this.computeMask(e,r),a=Un(t),i=Un(s);if(a.length!==i.length)throw new Error(`${this.name} outputs ${a.length} tensors but ${a.length} masks for those tensors`);for(let o=0;o<a.length;o++)a[o].kerasMask=i[o]}addInboundNode(e,t,r,s,a,i,o=null){const l=Un(e);t=Un(t),r=Un(r),s=Un(s),a=Ig(a),i=Ig(i);const p=[],c=[],h=[];for(const d of l)p.push(d.sourceLayer),c.push(d.nodeIndex),h.push(d.tensorIndex);new Tg({outboundLayer:this,inboundLayers:p,nodeIndices:c,tensorIndices:h,inputTensors:l,outputTensors:t,inputMasks:r,outputMasks:s,inputShapes:a,outputShapes:i},o);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}getConfig(){const e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function J2(n,e,t){if((e==null||t!=null&&t>0)&&(e=n.sourceLayer,t=n.nodeIndex),e.inboundNodes.length===0)return[n];{const r=e.inboundNodes[t];if(r.inboundLayers.length===0)return r.inputTensors;{const s=[];for(let a=0;a<r.inboundLayers.length;a++){const i=J2(r.inputTensors[a],r.inboundLayers[a],r.nodeIndices[a]);for(const o of i)s.indexOf(o)===-1&&s.push(o)}return s}}}class Gd extends bn{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:fg("input").toString()}),e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new ce("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new ce("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}
78else if(e.batchSize!=null)throw new ce("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const r=e.dtype||"float32";this.batchInputShape=t,this.dtype=r,this.inputSpec=[{shape:t}];const s=new ao(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new Tg({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new ce(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}function ev(n){if(n.batchShape==null&&n.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(n.batchShape!=null&&n.shape!=null)throw new ce("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let e=n.batchShape;n.shape!=null&&e==null&&(e=[null].concat(n.shape));let t=n.dtype;return t==null&&(t="float32"),new Gd({batchInputShape:e,name:n.name,dtype:t,sparse:n.sparse}).inboundNodes[0].outputTensors[0]}Gd.className="InputLayer",st(Gd);class nc{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof nc)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,r){if(this.id2Value[e.id]!=null)throw new ce(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(s,a){if(s.dtype==null||s.dtype===a.dtype)return a;try{return gt(a,s.dtype)}catch{throw new ce(`The dtype of the feed (${a.dtype}) can not be cast to the dtype of the key '${s.name}' (${s.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,r!=null&&(this.id2Mask[e.id]=r),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof ao){if(this.id2Value[e.id]==null)throw new ce(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(t==null)throw new ce(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ao){if(this.id2Value[e.id]==null)throw new ce(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(t==null)throw new ce(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&on(this.id2Mask)}}const Eg=new L2,Cg=new L2;function vf(n,e,t,r){const s=t!=null&&t.training,a=Array.isArray(n),i=a?n:[n],o=i.map(g=>g.name),l=[],p=e.names();for(const g of o)p.indexOf(g)!==-1?l.push(e.getValue(g)):l.push(null);const c=o.join(",")+"|"+e.names().sort().join(",");let h,d=Eg.get(c);if(d==null){const g=function(y,w){A(y!=null&&y.length>0,()=>"Expected at least one fetch, got none");let v=[],N={};if(y.length===1){const T=tv(y[0],w);v=T.sorted,N=T.recipientMap}else{const T=new Set;for(const $ of y){const{sorted:_,recipientMap:L}=tv($,w);for(const z of _)T.has(z.name)||(v.push(z),T.add(z.name));for(const z in L)N[z]==null&&(N[z]=new Set),L[z].forEach(O=>N[z].add(O))}}return{sorted:v,recipientCounts:NE(N)}}(i,e);d=g.sorted,h=g.recipientCounts,Eg.put(c,d),Cg.put(c,h)}h={},s||Object.assign(h,Cg.get(c));const m=new nc(e);for(let g=0;g<d.length;++g){const y=d[g],w=y.sourceLayer;if(w instanceof Gd)continue;const v=[],N=[],T=[];let $=!1;for(const V of y.inputs){const U=m.getValue(V),X=m.getMask(V);v.push(U),N.push(X),X!=null&&($=!0),s||(h[V.name]--,h[V.name]!==0||e.hasKey(V)||o.indexOf(V.name)!==-1||U.isDisposed||V.sourceLayer.stateful===!0||T.push(U))}$&&((t=t||{}).mask=N[0]);const _=Un(w.apply(v,t));let L=null;w.supportsMasking&&(L=w.computeMask(v,N));const z=IE(y),O=Array.isArray(z)?z:[z];for(let V=0;V<O.length;++V){m.hasKey(O[V])||m.add(O[V],_[V],Array.isArray(L)?L[0]:L);const U=o.indexOf(O[V].name);U!==-1&&(l[U]=_[V])}s||on(T)}return m.disposeMasks(),a?l:l[0]}function NE(n){const e={};for(const t in n)e[t]=n[t].size;return e}function tv(n,e){const t=new Set,r=[],s={};for(const o of e.names())t.add(o);const a=[],i=[];for(a.push(n);a.length>0;){const o=a[a.length-1];if(t.has(o.name)){a.pop();continue}const l=i[i.length-1]===a.length-1;if(o.inputs.length===0||l)a.pop(),r.push(o),t.add(o.name),l&&i.pop();else{i.push(a.length-1);for(const p of o.inputs)s[p.name]==null&&(s[p.name]=new Set),s[p.name].add(o.name),t.has(p.name)||a.push(p)}}return{sorted:r,recipientMap:s}}function IE(n){let e;if(n.sourceLayer.inboundNodes.length===1)e=n.sourceLayer.output;else{let t=null;for(let r=0;r<n.sourceLayer.inboundNodes.length;++r)for(const s of n.sourceLayer.inboundNodes[r].outputTensors)if(s.id===n.id){t=r;break}e=n.sourceLayer.getOutputAt(t)}return e}function I1(n,e){return be(()=>qn(Dt(se(n,n),e,!0)))}xe().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,function(n){Eg?.setMaxEntries(n),Cg?.setMaxEntries(n)});class kf extends ii{getConfig(){return{}}}class S1 extends kf{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return be(()=>{const t=I1(e,this.axis),r=ia(t,0,this.maxValue);return se(e,Lt(r,Ue(Xr(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}S1.className="MaxNorm",st(S1);class T1 extends kf{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return be(()=>
78Lt(e,Ue(Xr(),I1(e,this.axis))))}getConfig(){return{axis:this.axis}}}T1.className="UnitNorm",st(T1);class E1 extends kf{apply(e){return to(e)}}E1.className="NonNeg",st(E1);class C1 extends kf{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return be(()=>{const t=I1(e,this.axis),r=Ue(se(this.rate,ia(t,this.minValue,this.maxValue)),se(1-this.rate,t));return se(e,Lt(r,Ue(Xr(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}C1.className="MinMaxNorm",st(C1);const nv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Yr(n){return i1(n)}function rv(n,e={}){return gf(n,as.getMap().classNameMap,e,"constraint")}function Zr(n){return n==null?null:typeof n=="string"?rv({className:n in nv?nv[n]:n,config:{}}):n instanceof kf?n:rv(n)}function SE(n){return new S1(n)}function TE(n){return new T1(n)}function EE(){return new E1}function CE(n){return new C1(n)}function $E(){return new f1}function AE(){return new yg}function RE(n){return new m1(n)}function _E(n){return new g1(n)}function DE(n){return new y1(n)}function FE(n){return new b1(n)}function ME(n){return new x1(n)}function OE(n){return new ha(n)}function LE(n){return new bg(n)}function zE(n){return new xg(n)}function PE(n){return new wg(n)}function BE(n){return new vg(n)}function VE(n){return new kg(n)}function UE(n){return new Ng(n)}function WE(n){return new w1(n)}async function rc(n){if(n==null)return;const e=[],t=[],r=[];for(const s in n){const a=n[s];if(typeof a!="number"){const i=a;e.push(i.data()),t.push(s),r.push(i)}}if(e.length>0){const s=await Promise.all(e);for(let a=0;a<s.length;++a)n[t[a]]=s[a][0];on(r)}}function sv(n){if(n!=null)for(const e in n){const t=n[e];typeof t!="number"&&t.dispose()}}var av;(function(n){n[n.SILENT=0]="SILENT",n[n.VERBOSE=1]="VERBOSE"})(av||(av={}));class Hd{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class iv{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(const r of this.callbacks)await r.onEpochBegin(e,t)}
vendor: 1,228 bytes, line 78
78async onEpochEnd(e,t){t==null&&(t={});for(const r of this.callbacks)await r.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(const r of this.callbacks)await r.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(const r of this.callbacks)await r.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class GE extends Hd{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});const r=t.size==null?0:t.size;this.seen+=r;for(const s in t){const a=t[s];if(typeof a=="number")this.totals.hasOwnProperty(s)||(this.totals[s]=0),this.totals[s]=this.totals[s]+a*r;else{let i;s in this.totals?i=this.totals[s]:this.totals[s]=0;const o=be(()=>Ue(this.totals[s],se(a,r)));this.totals[s]=o,i?.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const r of this.params.metrics)this.totals[r]!=null&&(typeof this.totals[r]=="number"?t[r]=this.totals[r]/this.seen:be(()=>{const s=se(Lt(1,this.seen),this.totals[r]);t[r]=s,this.totals[r].dispose(),_r(t[r])}))}}class ov extends Hd{async onTrainBegin(e){this.epoch=[],this.history={}}
78async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const r in t)this.history[r]==null&&(this.history[r]=[]),this.history[r].push(t[r])}async syncData(){const e=[],t=[],r=[];for(const a in this.history){const i=this.history[a];for(let o=0;o<i.length;++o)if(typeof i[o]!="number"){const l=i[o];e.push(l.data()),t.push(a),r.push(o)}}const s=await Promise.all(e);for(let a=0;a<s.length;++a)this.history[t[a]][r[a]].dispose(),this.history[t[a]][r[a]]=s[a][0]}}class uv extends Hd{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||z0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=125),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");ft(this.yieldEvery)&&(this.maybeWait=function(r,s,a){let i,o=a!=null?a():Fn();return(...l)=>{const p=a!=null?a():Fn();return p-o<s||(o=p,i=r(...l)),i}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,r){const s=[];this.yield!=null&&(await rc(r),s.push(this.yield(e,t,r))),s.push(this.nextFrameFunc()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await rc(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const r=[];this.epochEnd!=null&&(await rc(t),r.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&r.push(this.nextFrameFunc()),await Promise.all(r)}async onBatchBegin(e,t){this.batchBegin!=null&&(await rc(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const r=[];this.batchEnd!=null&&(await rc(t),r.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?r.push(this.nextFrameFunc()):ft(this.yieldEvery)&&r.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(r)}async onTrainBegin(e){this.trainBegin!=null&&(await rc(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await rc(e),await this.trainEnd(e))}}function lv(n,e){return n==null&&(n={}),n instanceof Hd?[n]:Array.isArray(n)&&n[0]instanceof Hd?n:Un(n).map(t=>new uv(t,e))}class ja{constructor(){}static registerCallbackConstructor(e,t){A(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),ja.checkForDuplicate(t),ja.constructors[e]==null&&(ja.constructors[e]=[]),ja.constructors[e].push(t)}static checkForDuplicate(e){for(const t in ja.constructors)ja.constructors[+t].forEach(r=>{if(r===e)throw new ce("Duplicate callback constructor.")})}static clear(){ja.constructors={}}static createCallbacks(e){const t=[];for(const r in ja.constructors){const s=+r;e>=s&&t.push(...ja.constructors[s])}return t.map(r=>new r)}}function cv(n,e,t,r,s,a,i,o,l){const p=new ov,c=[new GE,...ja.createCallbacks(e)];n!=null&&c.push(...n),c.push(p);const h=new iv(c);return h.setParams({epochs:t,initialEpoch:r,samples:s,steps:a,batchSize:i,verbose:e,doValidation:o,metrics:l}),{callbackList:h,history:p}}function io(n,e={},t=!1){return gf(n,as.getMap().classNameMap,e,"layer",t)}function $g(n,e){return be(()=>{n.dtype!=="float32"&&(n=gt(n,"float32"));const t=Dt(xf(n),e,!0),r=$u(t.shape,Xr()),s=qn(Nr(t,r));return Lt(n,s)})}function kh(n,e){return be(()=>Sr(xf(ot(e,n)),-1))}function Ag(n,e){return be(()=>Sr(An(ot(e,n)),-1))}function jd(n,e){return be(()=>{const t=ot(n,e),r=ia(An(n),Xr(),Number.MAX_VALUE),s=An(Lt(t,r));return se(100,Sr(s,-1))})}function Nf(n,e,t=!1){return be(()=>{if(t)e=cf(e);else{const r=Dt(e,e.shape.length-1,!0);e=Lt(e,r)}return e=ia(e,Xr(),1-Xr()),Vn(Dt(se(gt(n,"float32"),Sa(e)),e.shape.length-1))})}function Rg(n,e,t=!1){return be(()=>{const r=gt(Md(function(a){const i=[ec(a.shape)];return he(a,i)}(n)),"int32"),s=(e=ia(e,Xr(),1-Xr())).shape;return Nf(he(Ur(r,s[s.length-1]),s),e,t)})}function _g(n,e){return be(()=>{let t;return t=ia(e,Xr(),1-Xr()),t=Sa(Lt(t,ot(1,t))),Sr(function(r,s){if(!le(r.shape,s.shape))throw new ce(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(s.shape)}`);return be(()=>{const a=to(s),i=Vn(An(s));return Ue(ot(a,se(s,r)),ef(oa(i)))})}(n,t),-1)})}function $1(n,e){return be(()=>{const t=$g(n,-1),r=$g(e,-1),s=se(t,r);return Vn(Dt(s,-1))})}ja.constructors={};const Dg={meanSquaredError:kh,meanAbsoluteError:Ag,meanAbsolutePercentageError:jd,meanSquaredLogarithmicError:function(n,e){return be(()=>{const t=ia(e,Xr(),Number.MAX_VALUE),r=Sa(Ue(1,t)),s=ia(n,Xr(),Number.MAX_VALUE),a=Sa(Ue(1,s));return Sr(xf(ot(r,a)),-1)})},squaredHinge:function(n,e){return be(()=>{const t=Nr(0,ot(1,se(n,e)));return Sr(xf(t),-1)})},hinge:function(n,e){return be(()=>{const t=Nr(0,ot(1,se(n,e)));return Sr(t,-1)})},categoricalHinge:function(n,e){return be(()=>{const t=Dt(se(n,e),-1),r=Va(se(ot(1,n),e),-1);return Nr(0,Ue(1,ot(r,t)))})},logcosh:function(n,e){return be(()=>{const t=Math.log(2),r=ot(e,n),s=ot(Ue(r,dh(se(-2,r))),t);return Sr(s,-1)})},categoricalCrossentropy:Nf,sparseCategoricalCrossentropy:Rg,binaryCrossentropy:_g,kullbackLeiblerDivergence:function(n,e){return be(()=>{const t=ia(n,Xr(),1),r=ia(e,Xr(),1);return Dt(se(n,Sa(Lt(t,r))),-1)})},poisson:function(n,e){return be(()=>{const t=Sa(Ue(Xr(),e));return Sr(ot(e,se(n,t)),-1)})},cosineProximity:$1};function A1(n){if(typeof n=="string"){if(n in Dg)return Dg[n];let e=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new ce(e)}return n}function R1(n,e){return be(()=>{const t=se(.5,Ta(e)),r=Vu(Gs(e,t),n.dtype);return Sr(Ia(n,r),-1)})}function _1(n,e){return be(()=>Vu(Ia(uh(n,-1),uh(e,-1)),"float32"))}function hv(n,e){return be(()=>gt(Dt(ci(Ia(n,1),Ia(e,1))),"float32"))}function dv(n,e){return be(()=>{const t=hv(n,e),r=function(a,i){return be(()=>gt(Dt(ci(Ia(a,0),Ia(i,1))),"float32"))}(n,e),s=Ue(t,r);return gt(os(Gs(s,0),Lt(t,s),0),"float32")})}function pv(n,e){return _g(n,e)}function fv(n,e){return n.rank===e.rank&&(n=Zl(n,[n.rank-1])),(e=uh(e,-1)).dtype!==n.dtype&&(e=gt(e,n.dtype)),gt(Ia(n,e),"float32")}const D1=Nf,mv=Rg,Fg={binaryAccuracy:R1,categoricalAccuracy:_1,precision:dv,categoricalCrossentropy:D1,sparseCategoricalCrossentropy:mv,mse:kh,MSE:kh,mae:Ag,MA
78E:Ag,mape:jd,MAPE:jd,cosine:$1};function HE(n){if(typeof n=="string"&&n in Fg)return Fg[n];if(typeof n!="string"&&n!=null)return n;throw new ce(`Unknown metric ${n}`)}function Mg(n){if(qo(n!==null,`Unknown LossOrMetricFn ${n}`),typeof n=="string")return n;{let e;for(const t of Object.keys(Dg))if(Dg[t]===n){e=t;break}if(e!==void 0)return e;for(const t of Object.keys(Fg))if(Fg[t]===n){e=t;break}return e!==void 0?e:n.name}}function gv(n,e,t=!1){if(n==null||typeof n!="object"||Object.getPrototypeOf(n)!==Object.prototype||!F1(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(t){const r=JSON.stringify(n);r.length>1048576&&console.warn(`User-defined metadata of model "${e}" is too large in size (length=${r.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function F1(n){if(n===null)return!0;if(typeof n=="object"){if(Object.getPrototypeOf(n)===Object.prototype){const e=Object.keys(n);for(const t of e)if(typeof t!="string"||!F1(n[t]))return!1;return!0}if(Array.isArray(n)){for(const e of n)if(!F1(e))return!1;return!0}return!1}{const e=typeof n;return e==="string"||e==="number"||e==="boolean"}}function Og(n,e,t=console.log){let r="";for(let s=0;s<n.length;++s)s>0&&(r=r.slice(0,r.length-1)+" "),r+=n[s],r=r.slice(0,e[s]),r+=" ".repeat(e[s]-r.length);t(r)}function jE(n,e,t){let r,s;try{s=n.inboundNodes.map(a=>JSON.stringify(a.inputShapes)).join(",")}catch{s="multiple"}try{r=JSON.stringify(n.outputShape)}catch{r="multiple"}Og([`${n.name} (${n.getClassName()})`,s,r,n.countParams().toString()],e,t)}function KE(n,e,t,r){let s,a;try{a=n.inboundNodes.map(c=>JSON.stringify(c.inputShapes)).join(",")}catch{a="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}const i=[];for(const c of n.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(c)===-1))for(let h=0;h<c.inboundLayers.length;++h){const d=c.inboundLayers[h].name,m=c.nodeIndices[h],g=c.tensorIndices[h];i.push(`${d}[${m}][${g}]`)}const o=n.name,l=n.getClassName(),p=i.length===0?"":i[0];Og([`${o} (${l})`,a,s,n.countParams().toString(),p],e,r);for(let c=1;c<i.length;++c)Og(["","","","",i[c]],e,r)}function yv(n,e,t){return(n==="inboundNodes"||n==="outputLayers"||n==="inputLayers")&&e===0&&typeof t=="string"}function If(n,e){if(n===null)return null;if(typeof n=="string")return bh(n);if(typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Array){const t=[],r=n.length;for(let s=0;s<r;++s){const a=n[s];yv(e,s,a)?t.push(a):t.push(If(a,e))}return t}{const t={};for(const r of Object.keys(n)){const s=n[r];if(r==="name"&&typeof s=="string")t[r]=s;else{const a=bh(r);t[a]=If(s,a)}}return t}}function M1(n,e){if(n==null)return null;if(typeof n=="string")return Bu(n);if(typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Array){const t=[],r=n.length;for(let s=0;s<r;++s){const a=n[s];yv(e,s,a)?t.push(a):t.push(M1(a,e))}return t}{const t={};for(const r of Object.keys(n)){const s=n[r];t[Bu(r)]=r!=="name"&&r!=="className"||typeof s!="string"?M1(s,r):s}return t}}const Lg="4.22.0";class oo extends bn{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){const N=this.getClassName().toLowerCase();this.name=fg(N)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Jl(this.inputs).length!==this.inputs.length)throw new ce(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(N=>N.name)}`);Jl(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(N=>N.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];
vendor: 4,128 bytes, line 78
78for(const N of this.outputs){const T=N.sourceLayer,$=N.nodeIndex,_=N.tensorIndex;this.outputLayers.push(T),this.outputLayersNodeIndices.push($),this.outputLayersTensorIndices.push(_)}for(const N of this.inputs){const T=N.sourceLayer,$=N.nodeIndex,_=N.tensorIndex;qo($===0,"input layer has >1 nodes"),qo(_===0,"input layer has >1 tensors"),this.inputLayers.push(T),this.inputLayersNodeIndices.push($),this.inputLayersTensorIndices.push(_)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let N=0;N<this.inputLayers.length;N++){const T=this.inputLayers[N];if(!(T instanceof Gd))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${N} (0-based) originates from layer type ${T.getClassName()}.`);this.inputNames.push(T.name),this.feedInputShapes.push(T.batchInputShape),this.feedInputNames.push(T.name)}for(const N of this.outputLayers)this.outputNames.push(N.name);this.internalInputShapes=this.inputs.map(N=>N.shape),this.internalOutputShapes=this.outputs.map(N=>N.shape);const t={},r={},s={},a={},i={},o=[],l=(N,T,$,_,L,z)=>{_!=null&&L!=null&&z!=null||(_=N.sourceLayer,L=N.nodeIndex,z=N.tensorIndex);const O=_.inboundNodes[L];if($.indexOf(O)!==-1)throw new di(`The tensor ${N.name} at layer "${_.name}" is part of a cycle.`);if(T.indexOf(O)!==-1)return;this.containerNodes.add(oo.nodeKey(_,L)),_.id in i||(i[_.id]=Object.keys(i).length),$.indexOf(O)===-1&&$.push(O);const V=O.inboundLayers.length;for(let U=0;U<V;U++){const X=O.inputTensors[U],ne=O.inboundLayers[U],ae=O.nodeIndices[U],Ie=O.tensorIndices[U];l(X,T,$,ne,ae,Ie)}for(T.push(O);$.indexOf(O)>=0;)$.splice($.indexOf(O),1);o.push(O)},p=[],c=[];for(const N of this.outputs)l(N,p,c);const h=o.slice().reverse();for(const N of h){r[N.id]=N,N.id in t||(t[N.id]=0);let T=t[N.id];const $=s[N.outboundLayer.id]==null?0:s[N.outboundLayer.id];T=Math.max(T,$),s[N.outboundLayer.id]=T,a[N.outboundLayer.id]=N.outboundLayer,t[N.id]=T;for(let _=0;_<N.inboundLayers.length;_++){const L=N.inboundLayers[_],z=N.nodeIndices[_],O=L.inboundNodes[z],V=t[O.id]==null?0:t[O.id];t[O.id]=Math.max(T+1,V),r[O.id]=O}}const d={};for(const N in t){const T=t[N];T in d||(d[T]=[]),d[T].push(r[N])}const m={};for(const N in s){const T=s[N];T in m||(m[T]=[]),m[T].push(a[N])}let g=Object.keys(m).map(N=>parseInt(N,10)).sort(dg);this.layers=[];for(const N of g){const T=m[N];T.sort(($,_)=>{const L=i[$.id],z=i[_.id];return L<z?-1:L>z?1:0});for(const $ of T)$ instanceof oo&&this.internalContainerRefs.push($),this.layers.push($)}this.layersByDepth=m,g=Object.keys(d).map(N=>parseInt(N,10)).sort(dg);const y=this.inputs.slice(),w=[];for(const N of g)for(const T of d[N]){const $=T.outboundLayer;if($!=null){for(const _ of T.inputTensors)if(y.indexOf(_)===-1)throw new di(`Graph disconnected: cannot obtain value for tensor ${_} at layer "${$.name}". The following previous layers were accessed without issue: ${w}`);for(const _ of T.outputTensors)y.push(_);w.push($.name)}}this.nodesByDepth=d;const v=this.layers.map(N=>N.name);for(const N of v){const T=v.filter($=>$===N).length;if(T!==1)throw new di(`The name "${N}" is used ${T} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(v))}this.outboundNodes=[],this.inboundNodes=[],new Tg({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(N=>null),outputMasks:this.outputs.map(N=>null),inputShapes:this.inputs.map(N=>N.shape),outputShapes:this.outputs.map(N=>N.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}
78set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(r=>r.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new ce("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const r of this.layers)t.push(...r.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const r={};let s=0;const a=(o=>{const l=Object.keys(o);if(l.length===0)return!1;const p=l[0].split("/");return!isNaN(parseInt(p[p.length-1],10))})(e);a&&this.parseWeights(e);for(const o of this.layers)for(const[l,p]of o.weights.entries()){const c=a?`${p.name.split("/").slice(0,-1).join("/")+"/"}${l}`:p.originalName;if(r[c]!=null)throw new ce(`Duplicate weight name: ${c}`);r[c]=p,s++}const i=[];for(const o in e){let l=o;if(r[o]==null){const p=o.split("/");l=p.slice(0,-2).concat([p[p.length-1]]).join("/")}if(r[l]!=null)i.push([r[l],e[o]]);else if(t)throw new ce(`Provided weight data has no target variable: ${o}`);delete r[l]}if(t){const o=[];for(const l in r)o.push(l);if(o.length>0)throw new ce(`${o.length} of ${s} weights are not set: ${o}`)}N1(i)}parseWeights(e){for(const t in Object.keys(e)){const r=t.split("/"),s=["vars","layer_checkpoint_dependencies"],a=r.map(i=>i.startsWith("_")?i.slice(1):i).filter(i=>!s.includes(i)).join("/");a!==t&&(e[a]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Lg}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const r=M1(this.updatedConfig());return t?JSON.stringify(r):r}call(e,t){return be(()=>{e=Un(e);const r=new nc;for(let s=0;s<this.inputs.length;++s)r.add(this.inputs[s],e[s]);return vf(this.outputs,r,t)})}computeMask(e,t){return be(()=>{let r;return e=Un(e),r=t==null?yh(null,e.length):Un(t),this.runInternalGraph(e,r)[1]})}computeOutputShape(e){const t=Ig(e);if(t.length!==this.inputLayers.length)throw new ce(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const r={};for(let o=0;o<t.length;o++){const l=this.inputLayers[o],p=t[o];r[l.name+"_0_0"]=p}const s=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(dg);if(s.length>1)for(const o of s){const l=this.nodesByDepth[o];for(const p of l){const c=p.outboundLayer;if(this.inputLayers.map(g=>g.id).indexOf(c.id)!==-1)continue;const h=[];for(let g=0;g<p.inboundLayers.length;g++){const y=p.inboundLayers[g],w=p.nodeIndices[g],v=p.tensorIndices[g],N=r[`${y.name}_${w}_${v}`];h.push(N)}const d=Ig(c.computeOutputShape(ca(h))),m=c.inboundNodes.indexOf(p);for(let g=0;g<d.length;g++)r[`${c.name}_${m}_${g}`]=d[g]}}const a=[],i=[];for(let o=0;o<this.outputLayers.length;o++){const l=this.outputLayers[o],p=this.outputLayersNodeIndices[o],c=this.outputLayersTensorIndices[o],h=`${l.name}_${p}_${c}`;i.push(h)}for(let o=0;o<i.length;o++){const l=i[o];qo(l in r),a.push(r[l])}return ca(a)}runInternalGraph(e,t){t==null&&(t=yh(null,e.length));const r={};for(let l=0;l<this.inputs.length;++l){const p=this.inputs[l],c=e[l],h=t[l];r[p.id]=[c,h]}const s=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(dg);for(const l of s){const p=this.nodesByDepth[l];for(const c of p){const h=c.outboundLayer,d=c.inputTensors,m=c.outputTensors,g=new Array;for(const y of d)y.id in r&&g.push(r[y.id]);if(g.length===d.length){let y,w,v,N,T={};if(c.callArgs!=null&&(T=c.callArgs),g.length===1){const[$,_]=g[0];T.mask==null&&(T.mask=_),v=Un(h.call($,T)),N=Un(h.computeMask($,_)),y=[$],w=[_]}else y=g.map($=>$[0]),w=g.map($=>$[1]),T.mask==null&&(T.mask=w),v=Un(h.call(y,T)),N=Un(h.computeMask(y,w));if(h.activityRegularizer)throw new gn("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let $=0;$<m.length;++$){const _=m[$],L=v[$],z=N[$];
vendor: 5,988 bytes, line 78
78r[_.id]=[L,z]}}}}const a=[],i=[],o=[];for(const l of this.outputs){qo(l.id in r,`Could not compute output ${l.name} : ${l.id}`);const[p,c]=r[l.id];o.push(p.shape),a.push(p),i.push(c)}return[a,i,o]}buildNodeConversionMap(e){const t={};let r;for(const s of this.layers){r=s instanceof oo?1:0;for(let a=0;a<s.inboundNodes.length;a++){const i=oo.nodeKey(s,a);this.containerNodes.has(i)&&(t[i]=r,r+=1)}}return t}getLayer(e,t){if(t!=null)return this.findLayer(t);if(e==null)throw new ce("Provide either a layer name or layer index");if(typeof e=="number")return this.findLayer(e);for(const r of this.layers)if(r.name===e)return r;throw new ce(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new ce(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return be(()=>{const e=[];for(const t of this.layers)for(let r=0;r<t.inboundNodes.length;++r){const s=oo.nodeKey(t,r);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),r=[];for(const i of this.layers){const o=i.getClassName(),l=i.getConfig(),p=[];for(let h=0;h<i.inboundNodes.length;h++){const d=i.inboundNodes[h],m=oo.nodeKey(i,h);let g={};if(this.containerNodes.has(m)){if(d.callArgs)try{JSON.stringify(d.callArgs),g=d.callArgs}catch{console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${d.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),g={}}if(d.inboundLayers.length>0){const y=[];for(let w=0;w<d.inboundLayers.length;w++){const v=d.inboundLayers[w],N=d.nodeIndices[w],T=d.tensorIndices[w];let $=t[oo.nodeKey(v,N)];$==null&&($=0),y.push([v.name,$,T,g])}p.push(y)}}}const c={};c.name=i.name,c.className=o,c.config=l,c.inboundNodes=p,r.push(c)}e.layers=r;const s=[];for(let i=0;i<this.inputLayers.length;i++){const o=this.inputLayers[i],l=this.inputLayersNodeIndices[i],p=oo.nodeKey(o,l);if(!this.containerNodes.has(p))continue;let c=t[p];c==null&&(c=0);const h=this.inputLayersTensorIndices[i];s.push([o.name,c,h])}e.inputLayers=s;const a=[];for(let i=0;i<this.outputLayers.length;i++){const o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],p=oo.nodeKey(o,l);if(!this.containerNodes.has(p))continue;let c=t[p];c==null&&(c=0);const h=this.outputLayersTensorIndices[i];a.push([o.name,c,h])}return e.outputLayers=a,e}static fromConfig(e,t,r={},s=!1){const a={},i={};function o(w,v){w.name in i?i[w.name].push(v):i[w.name]=[v]}function l(w,v){const N=[];let T;for(const $ of v){const _=$[0],L=$[1],z=$[2];if(T=$[3]==null?{}:$[3],!(_ in a))return void o(w,v);const O=a[_];if(O.inboundNodes.length<=L)return void o(w,v);const V=O.inboundNodes[L];N.push(V.outputTensors[z])}N.length>0&&w.apply(ca(N),T)}function p(w){const v=w.name,N=io(w,t.customObjects!=null?t.customObjects:{});N.setFastWeightInitDuringBuild(s),a[v]=N,w.inboundNodes.forEach(T=>{if(!(T instanceof Array))throw new ce(`Corrupted configuration, expected array for nodeData: ${T}`);o(N,T)})}const c=t.name,h=t.layers;for(const w of h)p(w);for(;!cE(i);)for(const w of h){const v=a[w.name];if(v.name in i){const N=i[v.name];delete i[v.name];for(const T of N)l(v,T)}}const d=[],m=[],g=t.inputLayers;for(const w of g){const v=w[0],N=w[1],T=w[2];qo(v in a);const $=a[v].inboundNodes[N].outputTensors;d.push($[T])}const y=t.outputLayers;for(const w of y){const v=w[0],N=w[1],T=w[2];qo(v in a);const $=a[v].inboundNodes[N].outputTensors;m.push($[T])}return new e({inputs:d,outputs:m,name:c})}get stateful(){if(this._stateful)throw new ce("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){be(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function bv(n,e){return function(t,r,s){const a=r.length;if(t==null||Array.isArray(t)&&t.length===0)return r.map(i=>null);if(a===1)return Array.isArray(t)&&t.length===1?t:typeof t=="object"&&r[0]in t?[t[r[0]]]:[t];if(Array.isArray(t)){if(t.length!==a)throw new Error(`Provided ${s} is an array of ${t.length} element(s), but the model has ${a} outputs. Make sure a set of weights is provided for each model output.`);return t}if(typeof t=="object"&&Object.keys(t).length>0&&typeof t[Object.keys(t)[0]]=="object"){const i=[];return r.forEach(o=>{o in t?i.push(t[o]):i.push(null)}),i}throw new Error(`The model has multiple (${a}) outputs, so ${s} must be either an array with ${a} elements or an object with ${r} keys. Provided ${s} not understood: ${JSON.stringify(t)}`)}(n,e,"classWeight")}async function xv(n,e,t,r){if(t!=null){const s=be(()=>{if(n.shape.length===1)return va(n);if(n.shape.length===2){if(n.shape[1]>1)return uh(n,1);if(n.shape[1]===1)return he(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await s.data());on(s);const i=[];return a.forEach(o=>{if(t[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(t[o])}),vs(i,"float32")}return null}function qE(n,e){return se(n,e)}function wv(n,e){let t,r;const s=e;t=s.xs,r=s.ys,A(t!=null&&r!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates ${e}`);const a=vv("input",n.inputNames,t),i=vv("output",n.outputNames,r),o=a[0].shape[0];A(a.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length}
78 inputs, but the dataset provides ${a.length} inputs.  (Expected input keys: ${JSON.stringify(n.inputNames)})`),A(i.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let l=0;l<a.length;l++)A(a[l].shape[0]===o,()=>`Batch size mismatch: input ${n.inputNames[l]} has ${a[l].shape[0]}; expected  ${o} based on input ${n.inputNames[0]}.`);for(let l=0;l<i.length;l++)A(i[l].shape[0]===o,()=>`Batch size mismatch: output ${n.outputNames[l]} has ${i[l].shape[0]}; expected  ${o} based on input ${n.inputNames[0]}.`);return{xs:a,ys:i}}function vv(n,e,t){if(t instanceof Sn)return[t];if(Array.isArray(t))return A(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${n} keys ${e}.`),t;{const r=[];for(const s of e){if(t[s]==null)throw new ce(`The feature data generated by the dataset lacks the required ${n} key '${s}'.`);r.push(t[s])}return r}}function kv(n){return typeof n.iterator=="function"}function O1(n){A(n>0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function Sf(n,e,t){return n==null?[null]:Array.isArray(n)?n.map(r=>vh(r,e,t-e)):vh(n,e,t-e)}function L1(n,e){return be(()=>n==null?null:Array.isArray(n)?n.map(t=>L1(t,e)):K2(n,e.dtype==="int32"?e:gt(e,"int32")))}function z1(n,e){const t=[];let r=0,s=null;for(;r<n;)s=r+e,s>=n&&(s=n),t.push([r,s]),r=s;return t}function Nv(n){const e=[];n instanceof Sn&&(n=[n]);for(let t=0;t<n.length;++t){const r=n[t];if(r.rank===1)e.push(bf(r,1));else{if(r.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(r)}}return e}function uo(n,e){if(n==null)return;const t=[];if(e instanceof Sn)t.push(e.id);else if(Array.isArray(e))e.forEach(s=>t.push(s.id));else if(e!=null)for(const s in e){const a=e[s];t.push(a.id)}const r=[];if(n instanceof Sn)t.indexOf(n.id)===-1&&r.push(n);else if(Array.isArray(n))n.forEach(s=>{t.indexOf(s.id)===-1&&r.push(s)});else if(n!=null)for(const s in n){const a=n[s];t.indexOf(a.id)===-1&&r.push(a)}r.forEach(s=>{s.isDisposed||s.dispose()})}function P1(n){return Array.isArray(n)}function Iv(n){return!function(e){return e instanceof Sn}(n)&&!P1(n)}function Sv(n,e,t,r=!0,s=""){if(e==null||e.length===0){if(n!=null){let i=!1;if(P1(n)&&n.length>0)i=!0;else if(Iv(n)){for(const o in n)if(n.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new ce(`Error when checking model ${s} expected no data, but got ${n}`)}return[]}if(n==null)return e.map(i=>null);let a;if(Iv(n)){a=[];for(const i of e){if(n[i]==null)throw new ce(`No data provided for "${i}". Need data for each key in: ${e}`);a.push(n[i])}}else if(P1(n)){if(n.length!==e.length)throw new ce(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${n}`);a=n}else{if(e.length>1)throw new ce(`The model ${s} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);a=[n]}if(a=Nv(a),t!=null)for(let i=0;i<e.length;++i){if(t[i]==null)continue;const o=a[i];if(o.shape.length!==t[i].length)throw new ce(`Error when checking ${s}: expected ${e[i]} to have ${t[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<t[i].length;++l){if(l===0&&!r)continue;const p=o.shape[l],c=t[i][l];if(c!=null&&c>=0&&p!==c)throw new ce(`${s} expected a batch of elements where each example has shape [${t[i].slice(1,t[i].length)}] (i.e.,tensor shape [*,${t[i].slice(1,t[i].length)}]) but the ${s} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return a}function Tv(n,e,t,r=!0,s=""){let a;if(Array.isArray(n)){if(n.length!==e.length)throw new ce(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${e.length} Tensor(s), but instead got ${n.length} Tensors(s).`);a=n}else{if(e.length>1)throw new ce(`The model expects ${e.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);a=[n]}if(t!=null)for(let i=0;i<e.length;++i){if(t[i]==null)continue;const o=a[i];if(o.shape.length!==t[i].length)throw new ce(`Error when checking ${s}: expected ${e[i]} to have ${t[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<t[i].length;++l){if(l===0&&!r)continue;const p=o.shape[l],c=t[i][l];if(c!=null&&c!==p)throw new ce(`Error when checking ${s}: expected ${e[i]} to have shape ${JSON.stringify(t[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}class Wu extends oo{constructor(e){super(e),this.isTraining=!1}summary(e,t,r=console.log){if(!this.built)throw new ce("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");(function(s,a,i,o=console.log){const l=function(g){let y=!0;const w=[],v=[];for(const N in g.nodesByDepth)w.push(g.nodesByDepth[N]);for(const N of w){if(N.length>1||N.length===1&&N[0].inboundLayers.length>1){y=!1;break}v.push(...N)}
78if(y)for(const N of g.layers){let T=!1;for(const $ of N.inboundNodes)if(v.indexOf($)!==-1){if(T){y=!1;break}T=!0}if(!y)break}return y}(s),p=["Layer (type)","Input Shape","Output shape","Param #"];let c;if(l?(a=a||90,i=i||[.32,.61,.89,1]):(a=a||115,i=i||[.24,.48,.7,.8,1]),i[i.length-1]<=1&&(i=i.map(g=>Math.floor(a*g))),!l){p.push("Receives inputs"),c=[];for(const g in s.nodesByDepth)c.push(...s.nodesByDepth[g])}o("_".repeat(a)),Og(p,i,o),o("=".repeat(a));const h=s.layers;for(let g=0;g<h.length;++g)l?jE(h[g],i,o):KE(h[g],i,c,o),o((g===h.length-1?"=":"_").repeat(a));s.checkTrainableWeightsConsistency();const d=function(g){let y;return y=g.collectedTrainableWeights!=null?Sg(g.collectedTrainableWeights):Sg(g.trainableWeights),y}(s),m=Sg(s.nonTrainableWeights);o(`Total params: ${d+m}`),o(`Trainable params: ${d}`),o(`Non-trainable params: ${m}`),o("_".repeat(a))})(this,e,t,r)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=function(i){const o={Adagrad:()=>gh.adagrad(.01),Adadelta:()=>gh.adadelta(1,.95,Xr()),Adam:()=>gh.adam(.001,.9,.999,Xr()),Adamax:()=>gh.adamax(.002,.9,.999,Xr(),0),RMSProp:()=>gh.rmsprop(.001,.9,0,Xr()),SGD:()=>gh.sgd(.01)};if(o.adagrad=o.Adagrad,o.adadelta=o.Adadelta,o.adam=o.Adam,o.adamax=o.Adamax,o.rmsprop=o.RMSProp,o.sgd=o.SGD,i in o)return o[i]();throw new ce(`Unknown Optimizer ${i}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof oi))throw new ce("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||typeof e.loss=="string"||typeof e.loss=="function")if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new ce(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>A1(o))}else{const i=A1(e.loss);this.outputs.forEach(o=>{t.push(i)})}else{e.loss=e.loss;for(const i in e.loss)if(this.outputNames.indexOf(i)===-1)throw new ce(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);for(const i of this.outputNames)e.loss[i]==null&&console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`),t.push(A1(e.loss[i]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let i=0;i<this.outputs.length;++i){const o=this.internalOutputShapes[i],l=this.outputNames[i];this.feedOutputNames.push(l),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[i])}const r=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],wh("loss",()=>{for(let i=0;i<this.outputs.length;++i){if(r.indexOf(i)!==-1)continue;const o=this.lossFunctions[i];this.outputs.length>1&&(this.metricsTensors.push([o,i]),this.metricsNames.push(this.outputNames[i]+"_loss"))}});const s=function(i,o){if(i==null||Array.isArray(i)&&i.length===0)return o.map(p=>[]);let l;if(typeof i=="string"||typeof i=="function")l=[i];else{if(!Array.isArray(i)&&typeof i!="object")throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${i}`);l=i}if(Array.isArray(l))return o.map(p=>l);{const p=[];for(const c of o){let h=l.hasOwnProperty(c)?l[c]:[];Array.isArray(h)||(h=[h]),p.push(h)}return p}}(e.metrics,this.outputNames),a=(i,o,l)=>{this.outputNames.length>1&&(o=this.outputNames[i]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([l,i])};wh("metric",()=>{for(let i=0;i<this.outputs.length;++i)r.indexOf(i)===-1&&(o=>{let l,p,c;for(const h of o){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){const m=this.internalOutputShapes[i];let g;m[m.length-1]===1||this.lossFunctions[i]===_g?["accuracy","acc"].indexOf(h)!==-1?p=R1:["crossentropy","ce"].indexOf(h)!==-1&&(p=pv):this.lossFunctions[i]===Rg?["accuracy","acc"].indexOf(h)!==-1?p=fv:["crossentropy","ce"].indexOf(h)!==-1&&(p=mv):["accuracy","acc"].indexOf(h)!==-1?p=_1:["crossentropy","ce"].indexOf(h)!==-1&&(p=D1),["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),c=p,l=""+g}else c=HE(h),l=""+Mg(h);let d;wh(l,()=>{d=c}),a(i,l,d)}})(s[i])}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did 
78you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,r={}){const s=r.batchSize==null?32:r.batchSize;O1(s);const a=this.standardizeUserDataXY(e,t,!0,s);try{const i=a[0].concat(a[1]);this.makeTestFunction();const o=this.testFunction;return ca(this.testLoop(o,i,s,r.verbose,r.steps))}finally{uo(a[0],e),uo(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(r,s,a){const i=(a=a||{}).batches!=null,o=r.testFunction;let l=[];if(a.verbose>0)throw new gn("Verbose mode is not implemented yet.");A(!i||a.batches>0&&Number.isInteger(a.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(a.batches)}`);const p=typeof s.next=="function"?s:await s.iterator();let c=0,h=0;for(;!i||h<a.batches;){const d=await p.next();if(l=be(()=>{if(d.value){const{xs:m,ys:g}=wv(r,d.value),y=m.concat(g),w=be(()=>o(y));if(on(y),h===0)for(let N=0;N<w.length;++N)l.push(Pt(0));const v=y[0].shape[0];for(let N=0;N<w.length;++N){const T=w[N],$=l[N];l[N]=be(()=>Ue(l[N],se(v,T))),h>0&&on($)}on(w),c+=v,++h}return l}),d.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${a.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let d=0;d<l.length;++d){const m=l[d];l[d]=Lt(l[d],c),on(m)}return ca(l)}(this,e,t)}checkNumSamples(e,t,r,s="steps"){let a;if(r!=null){if(a=null,t!=null)throw new ce(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(e==null)throw new ce(`Either the input data should have a defined shape, or ${s} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new ce("`outputs` is an empty Array, which is not allowed.");const r=Array.isArray(t),s=r?t:[t],a=this.retrieveSymbolicTensors(s),i=new nc;if(e instanceof Sn&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new ce(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let l=0;l<this.inputs.length;++l)i.add(this.inputs[l],e[l])}else for(const l of this.inputs){const p=e[l.name];if(p==null)throw new ce(`No value is provided for the model's input ${l.name}`);i.add(l,p)}const o=vf(a,i);return r?o:o[0]}retrieveSymbolicTensors(e){const t=yh(null,e.length);let r=e.length;for(const s of this.layers){const a=Array.isArray(s.output)?s.output:[s.output],i=a.map(o=>o.name);for(let o=0;o<e.length;++o){const l=i.indexOf(e[o]);if(l!==-1&&(t[o]=a[l],r--),r===0)break}if(r===0)break}if(r>0){const s=[];throw t.forEach((a,i)=>{a==null&&s.push(e[i])}),new ce(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,r=!1){return be(()=>{const s=this.checkNumSamples(e);if(r)throw new gn("Verbose predictLoop() is not implemented yet.");const a=z1(s,t),i=this.outputs.map(o=>[]);for(let o=0;o<a.length;++o)be(()=>{const l=a[o][0],p=a[o][1],c=Sf(e,l,p),h=[];if(Array.isArray(c))for(let m=0;m<c.length;++m)h.push({key:this.inputs[m],value:c[m]});else h.push({key:this.inputs[0],value:c});const d=new nc(h);return vf(this.outputs,d)}).forEach((l,p)=>i[p].push(l));return ca(i.map(o=>Fr(o,0)))})}predict(e,t={}){const r=Nv(e);Tv(r,this.inputNames,this.feedInputShapes,!1);try{const s=t.batchSize==null?32:t.batchSize;return O1(s),this.predictLoop(r,s)}finally{uo(r,e)}}predictOnBatch(e){Tv(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,r=!0,s){if(this.optimizer_==null)throw new di("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let i=0;i<this.feedOutputShapes.length;++i){const o=this.feedOutputShapes[i];this.feedLossFns[i]===Rg?a.push(o.slice(0,o.length-1).concat([1])):a.push(o)}if(function(i,o){const l=Jl(i.map(c=>c.shape[0]));l.sort();const p=Jl(o.map(c=>c.shape[0]));if(p.sort(),l.length>1)throw new ce(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(i.map(c=>c.shape))}`);if(p.length>1)throw new ce(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(o.map(c=>c.shape))}`);if(l.length>0&&p.length>0&&!le(l,p))throw new ce(`Input Tensors should have the same number of samples as target Tensors. Found ${l[0]} input sample(s) and ${p[0]} target sample(s).`)}(e=Sv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Sv(t,this.feedOutputNames,a,!1,"target")),function(i,o,l){const p=[kh,_g,Nf];for(let c=0;c<i.length;++c){const h=i[c],d=o[c],m=l[c];if(d!=null){if(d===Nf&&h.shape[h.shape.length-1]===1)throw new ce(`You are passing a target array of shape ${h.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(p.indexOf(d)!==-1){const g=h.shape.slice(1),y=m.slice(1);for(let w=0;w<g.length;++w){const v=g[w],N=y[w];if(N!=null&&v!==N)throw new ce(`A target Tensor with shape ${h.shape} was passed for an output of shape ${m}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!==0)throw new ce(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,r,s,a=!0,i){const[o,l]=this.standardizeUserDataXY(e,t,a,i);if(r!=null)throw new Error("sample weight is not supported yet.");let p=null;if(s!=null){const c=bv(s,this.outputNames);p=[];for(let h=0;h<c.length;++h)p.push(await xv(l[h],null,c[h]))}return[o,l,p]}testLoop(e,t,r,s=0,a){return be(()=>{const i=this.checkNumSamples(t,r,a,"steps"),o=[];if(s>0)throw new gn("Verbose mode is not implemented yet.");if(a!=null)throw new gn("steps mode in testLoop() is not implemented yet");{const l=z1(i,r),p=vs(ro(0,i));for(let c=0;c<l.length;++c){const h=l[c][0],d=l[c][1],m=vh(p,h,d-h),g=L1(t,m),y=e(g);if(c===0)for(let w=0;w<y.length;++w)o.push(Pt(0));for(let w=0;w<y.length;++w){const v=y[w];o[w]=Ue(o[w],se(d-h,v))}}for(let c=0;c<o.length;++c)o[c]=Lt(o[c],i)}return o}
78)}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let r=0;r<e.length;++r){const s=e[r];let a=s;z2(e,s)>1&&(a+=`_${z2(e.slice(0,r),s)}`),t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),i=[],o=this.collectedTrainableWeights.map(l=>l.read());return[this.optimizer_.minimize(()=>{const l=[];for(let d=0;d<this.inputs.length;++d)l.push({key:this.inputs[d],value:r[d]});const p=new nc(l),c=vf(this.outputs,p,{training:!0});let h;for(let d=0;d<this.lossFunctions.length;++d){let m=(0,this.lossFunctions[d])(s[d],c[d]);a[d]!=null&&(m=qE(m,a[d]));const g=Sr(m);t.push(g),h=d===0?m:Ue(h,m)}for(let d=0;d<this.metricsTensors.length;++d){let m;if(this.outputs.length>1&&d<this.outputs.length)m=t[d];else{const g=this.metricsTensors[d][0],y=this.metricsTensors[d][1];m=Sr(g(s[y],c[y]))}_r(m),i.push(m)}return h=Sr(h),this.calculateLosses().forEach(d=>{h=Ue(h,d)}),h},!0,o)].concat(i)}}makeTestFunction(){this.testFunction=e=>be(()=>{const t=[];let r;const s=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=[];for(let p=0;p<this.inputs.length;++p)i.push({key:this.inputs[p],value:s[p]});const o=new nc(i),l=vf(this.outputs,o);for(let p=0;p<this.lossFunctions.length;++p){const c=this.lossFunctions[p],h=Sr(c(a[p],l[p]));r=p===0?h:Ue(r,h),t.push(r)}for(let p=0;p<this.metricsTensors.length;++p){const c=this.metricsTensors[p][0],h=this.metricsTensors[p][1],d=Sr(c(a[h],l[h]));t.push(d)}return t})}async fit(e,t,r={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let s,a,i,o,l,p,c,h,d;this.isTraining=!0;try{const m=r.batchSize==null?32:r.batchSize;O1(m);const g=!1,y=await this.standardizeUserData(e,t,r.sampleWeight,r.classWeight,g,m);s=y[0],a=y[1],d=y[2];let w,v=!1;if(r.validationData!=null&&r.validationData.length>0){if(v=!0,r.validationData.length!==2)throw r.validationData.length===3?new gn("validationData including sample weights is not supported yet."):new ce(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);l=r.validationData[0],p=r.validationData[1];const O=!0,V=await this.standardizeUserData(l,p,null,null,O,m);c=V[0],h=V[1],w=c.concat(h)}else if(r.validationSplit!=null&&r.validationSplit>0&&r.validationSplit<1){v=!0;const O=Math.floor(s[0].shape[0]*(1-r.validationSplit)),V=s[0].shape[0];c=Sf(s,O,V),i=s,s=Sf(s,0,O),h=Sf(a,O,V),o=a,a=Sf(a,0,O),w=c.concat(h)}else r.validationSteps!=null&&(v=!0);const N=s.concat(a).concat(d);this.checkTrainableWeightsConsistency();const T=this.makeTrainFunction(),$=this.getDedupedMetricsNames();let _,L;v?(this.makeTestFunction(),_=this.testFunction,L=$.slice().concat($.map(O=>"val_"+O))):(_=null,w=[],L=$.slice());const z=lv(r.callbacks,r.yieldEvery);return await this.fitLoop(T,N,$,m,r.epochs,r.verbose,z,_,w,r.shuffle,L,r.initialEpoch,null,null)}finally{this.isTraining=!1,uo(s,e),uo(a,t),uo(i,e),uo(o,t),uo(c,l),uo(h,p),d!=null&&on(d)}}async fitLoop(e,t,r,s,a,i,o,l,p,c,h,d,m,g){s==null&&(s=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0);let y=!1;if(l!=null&&p!=null&&(y=!0),g!=null&&(y=!0,m==null))throw new ce("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const w=this.checkNumSamples(t,s,m,"steps_per_epoch");let v;w!=null&&(v=ro(0,w)),i==null&&(i=1);const{callbackList:N,history:T}=cv(o,i,a,d,w,m,s,y,h);N.setModel(this),this.history=T,await N.onTrainBegin(),this.stopTraining_=!1;for(let $=d;$<a;++$){await N.onEpochBegin($);const _={};if(m!=null)throw new gn("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new gn("batch shuffling is not implemneted yet");c&&B(v);const L=vs(v),z=z1(w,s);for(let O=0;O<z.length;++O){const V={};if(await N.onBatchBegin(O,V),be(()=>{const U=z[O][0],X=z[O][1],ne=vh(L,U,X-U);V.batch=O,V.size=X-U;const ae=L1(t,ne),Ie=e(ae);for(let me=0;me<r.length;++me){const we=r[me],$e=Ie[me];V[we]=$e,_r($e)}if(O===z.length-1&&y){const me=this.testLoop(l,p,s);for(let we=0;we<r.length;++we){const $e=r[we],ze=me[we];_r(ze),_["val_"+$e]=ze}}}),await N.onBatchEnd(O,V),sv(V),this.stopTraining_)break}L.dispose()}if(await N.onEpochEnd($,_),this.stopTraining_)break}return await N.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return async function(r,s,a){const i=a.batchesPerEpoch!=null;if(A(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),A(a!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),A(a.epochs!=null&&a.epochs>0&&Number.isInteger(a.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${a.epochs}
78`),A(!i||a.batchesPerEpoch>0&&Number.isInteger(a.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${a.batchesPerEpoch}`),A(a.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;try{const o=a.validationData!=null;let l,p;if(o)if(kv(a.validationData))A(a.validationBatches==null||a.validationBatches>0&&Number.isInteger(a.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${a.validationBatches}`);else{const T=function($){if($.length===3)throw new gn("Validation with sample weights is not implemented yet.");return{xs:$[0],ys:$[1]}}(a.validationData);l=T.xs,p=T.ys}const c=r.makeTrainFunction(),h=r.getDedupedMetricsNames();let d;d=o?h.slice().concat(h.map(T=>"val_"+T)):h.slice();
78const m=lv(a.callbacks,a.yieldEvery),g=a.verbose==null?1:a.verbose,{callbackList:y,history:w}=cv(m,g,a.epochs,null,null,function(T,$){let _=null;return $.batchesPerEpoch!=null?_=$.batchesPerEpoch:Number.isFinite(T.size)&&(_=T.size),_}(s,a),null,o,d);y.setModel(r),r.history=w,await y.onTrainBegin(),r.stopTraining_=!1;let v=a.initialEpoch==null?0:a.initialEpoch,N=await s.iterator();for(;v<a.epochs;){const T={};await y.onEpochBegin(v);let $=0,_=0;for(i||(N=await s.iterator());!i||$<a.batchesPerEpoch;){const L=await N.next();if(i&&L.done){console.warn(`You provided \`batchesPerEpoch\` as ${a.batchesPerEpoch}, but your dataset iterator ran out of data after ${$} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, `+a.batchesPerEpoch*a.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(L.value!=null){const{xs:z,ys:O}=wv(r,L.value),V={};V.batch=_,V.size=z[0].shape[0],await y.onBatchBegin(_,V);const U=[];if(a.classWeight!=null){const ae=bv(a.classWeight,r.outputNames);for(let Ie=0;Ie<ae.length;++Ie)U.push(await xv(O[Ie],null,ae[Ie]))}const X=z.concat(O).concat(U),ne=c(X);on(X);for(let ae=0;ae<h.length;++ae){const Ie=h[ae],me=ne[ae];V[Ie]=me,_r(me)}await y.onBatchEnd(_,V),sv(V),_++,$++}if(i?$>=a.batchesPerEpoch:L.done){if(o){let z;z=kv(a.validationData)?Un(await r.evaluateDataset(a.validationData,{batches:a.validationBatches})):Un(r.evaluate(l,p,{batchSize:a.validationBatchSize==null?32:a.validationBatchSize,verbose:0}));for(let O=0;O<r.metricsNames.length;++O)T[`val_${r.metricsNames[O]}`]=z[O]}break}if(r.stopTraining_)break}if(await y.onEpochEnd(v,T),v++,r.stopTraining_)break}return await y.onTrainEnd(),await r.history.syncData(),r.history}finally{r.isTraining=!1}}(this,e,t)}async trainOnBatch(e,t){const r=await this.standardizeUserData(e,t),s=r[0],a=r[1],i=this.makeTrainFunction()(s.concat(a)),o=[];for(const l of i){const p=await l.data();o.push(p[0])}return on(i),uo(r[0],e),uo(r[1],t),ca(o)}getNamedWeights(e){const t=[],r=e!=null&&e.trainableOnly,s=r?this.trainableWeights:this.weights,a=this.getWeights(r);for(let i=0;i<s.length;++i)r&&!s[i].trainable||t.push({name:s[i].originalName,tensor:a[i]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){const t=sd().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-sd().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Bu(this.loss);else if(Array.isArray(this.loss)){for(const t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>Bu(t))}else{const t=Object.keys(this.loss);e={};const r=this.loss;for(const s of t){if(typeof r[s]!="string")throw new Error("Serialization of non-string loss is not supported.");e[s]=Bu(r[s])}}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[Bu(Mg(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Bu(Mg(e)));{const e={};for(const t in this.metrics)e[t]=Bu(Mg(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=io(If(e.optimizer_config));let r,s;if(typeof e.loss=="string")r=bh(e.loss);else if(Array.isArray(e.loss))r=e.loss.map(a=>bh(a));else if(e.loss!=null){r={};for(const a in e.loss)r[a]=bh(e.loss[a])}if(Array.isArray(e.metrics))s=e.metrics.map(a=>bh(a));else if(e.metrics!=null){s={};for(const a in e.metrics)s[a]=bh(e.metrics[a])}this.compile({loss:r,metrics:s,optimizer:t})}async save(e,t){if(typeof e=="string"){const a=Vo(e);if(a.length===0)throw new ce(`Cannot find any save handlers for URL '${e}'`);if(a.length>1)throw new ce(`Found more than one (${a.length}) save handlers for URL '${e}'`);e=a[0]}if(e.save==null)throw new ce("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const r=await id(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${Lg}`,convertedBy:null};if(t!=null&&t.includeOptimizer&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();const a="optimizer",{data:i,specs:o}=await id(await this.optimizer.getWeights(),a);r.specs.push(...o),r.data=ld([r.data,i])}return this.userDefinedMetadata!=null&&(gv(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,e.save(s)}setUserDefinedMetadata(e){gv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Wu.className="Model",st(Wu);class Ev extends Wu{}async function XE(n,e){"modelTopology"in n||(n={modelTopology:n});let t=n.modelTopology;t.model_config!=null&&(t=t.model_config);const r=io(If(t),e);if(n.weightsManifest!=null){const s=await dr(n.weightsManifest,n.pathPrefix,r.weights.map(i=>i.originalName)),a={};for(const i of r.weights)a[i.originalName]=s[i.originalName];r.loadWeights(a),on(s)}return r}async function YE(n,e){if(e==null&&(e={}),typeof n=="string"){const t=_p(n,e);if(t.length===0)t.push(As(n,e));else if(t.length>1)throw new ce(`Found more than one (${t.length}) load handlers for URL '${n}'`);n=t[0]}return async function(t,r,s){if(s==null&&(s={}
78),t.load==null)throw new ce("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const a=await t.load();let i=a.modelTopology;i.model_config!=null&&(i=i.model_config);const o=s.strict==null||s.strict,l=a.weightData!=null&&a.weightSpecs!=null&&o,p=io(If(i),void 0,l),c=a.trainingConfig;if(c!=null&&p.loadTrainingConfig(c),a.userDefinedMetadata!=null&&p.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new ce("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:h,optimizerWeights:d}=function(m,g){const y=od(m,g),w={},v=[];return g.forEach(N=>{N.group==="optimizer"?v.push({name:N.name,tensor:y[N.name]}):w[N.name]=y[N.name]}),{modelWeights:w,optimizerWeights:v}}(a.weightData,a.weightSpecs);p.loadWeights(h,o),p.optimizer!=null&&d.length>0&&await p.optimizer.setWeights(d),on(h),on(d.map(m=>m.tensor))}return p}(n,0,e)}Ev.className="Functional",st(Ev);class Nh extends Wu{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:fg("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new ce(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Nh||e instanceof Wu;let r;if(t){if(r=e,r.outputs.length!==1)throw new ce("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(r.inputs.length!==1)throw new ce("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new ce("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const s=ev({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=r.outputs,this.inputs=r.inputs;else{if(e.inboundNodes.length!==1)throw new ce(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new ce("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=J2(this.outputs[0])}this.inboundNodes=[],new Tg({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:yh(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{const s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(Rn(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Wu({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supp
78ortsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,r=console.log){this.built||this.build(),super.summary(e,t,r)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,r={}){if(!this.built)throw new di("The model needs to be compiled before being used.");return this.model.evaluate(e,t,r)}async evaluateDataset(e,t){if(!this.built)throw new di("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,r={}){if(!this.built)throw new di("The model needs to be compiled before being used.");return this.model.fit(e,t,r)}async fitDataset(e,t){if(!this.built)throw new di("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,r={},s=!1){let a,i={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new ce("Legacy serialization format not supported yet.");a=t}else A(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),a=t.layers,delete t.layers,i=t;const o=new e(i);if(!(o instanceof Nh))throw new gn(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(const l of a){const p=io(l,void 0,s);s&&p.setFastWeightInitDuringBuild(!0),o.add(p)}return o}set stopTraining(e){if(this.model==null)throw new ce("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new ce("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const r={};r.className=t.getClassName(),r.config=t.getConfig(),e.push(r)}return{name:this.name,layers:e}}}function ZE(n){return new Wu(n)}function QE(n){return new Nh(n)}function Cv(n){return ev(n)}function JE(n,e){ja.registerCallbackConstructor(n,e)}Nh.className="Sequential",st(Nh);class _s extends ii{getConfig(){return{}}}class $v extends _s{apply(e,t=1){return function(r,s=1){if(s!==1)throw new gn(`Support for alpha values other than 1 (${s}) is not implemented yet.`);return _d(r)}(e,t)}}$v.className="elu",st($v);class Av extends _s{apply(e){return Hm(e)}}Av.className="selu",st(Av);class Rv extends _s{apply(e){return to(e)}}Rv.className="relu",st(Rv);class _v extends _s{apply(e){return be(()=>Xl(6,to(e)))}}_v.className="relu6",st(_v);class Dv extends _s{apply(e){return e}}Dv.className="linear",st(Dv);class Fv extends _s{apply(e){return eo(e)}}Fv.className="sigmoid",st(Fv);class Mv extends _s{apply(e){return function(t){return be(()=>{const r=Ue(.5,se(.2,t));return ia(r,0,1)})}(e)}}Mv.className="hardSigmoid",st(Mv);class Ov extends _s{apply(e){return dh(e)}}Ov.className="softplus",st(Ov);class Lv extends _s{apply(e){return function(t){return be(()=>Lt(t,Ue(An(t),1)))}(e)}}Lv.className="softsign",st(Lv);class zv extends _s{apply(e){return jl(e)}}zv.className="tanh",st(zv);class B1 extends _s{apply(e,t=-1){return cf(e,t)}}B1.className="softmax",st(B1);class Pv extends _s{apply(e,t=-1){return zm(e,t)}}Pv.className="logSoftmax",st(Pv);class Bv extends _s{apply(e){return be(()=>be(()=>{const t=Math.sqrt(2),r=se(.5,Ue(1,Om(Lt(e,t))));return se(e,r)}))}}Bv.className="gelu",st(Bv);class Vv extends _s{apply(e){return be(()=>se(.5,se(e,Ue(1,jl(se(qn(Lt(2,Math.PI)),Ue(e,se(.044715,Ar(e,3)))))))))}}Vv.className="gelu_new",st(Vv);class Uv extends _s{apply(e){return be(()=>se(e,jl(dh(e))))}}Uv.className="mish",st(Uv);class Wv extends _s{apply(e,t=1){return be(()=>se(eo(se(e,t)),e))}}function sc(n){return n.getClassName()}function V1(n,e={}){return gf(n,as.getMap().classNameMap,e,"activation")}function ac(n){if(n==null)return V1({className:"linear",config:{}});if(typeof n=="string"){const e={};return e.className=n,e.config={},V1(e)}return n instanceof _s?n:V1(n)}function U1(n){if(n!=null&&typeof n!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}Wv.className="swish",st(Wv);class Gv extends ii{}class Tf extends Gv{constructor(e){super(),U1(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return be(()=>{let t=Wr([1]);return this.hasL1&&(t=Ue(t,Dt(se(this.l1,An(e))))),this.hasL2&&(t=Ue(t,Dt(se(this.l2,xf(e))))),he(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Tf.className="L1L2",st(Tf);const Hv={l1l2:"L1L2"};function nr(n){return i1(n)}function jv(n,e={}){return gf(n,as.getMap().classNameMap,e,"regularizer")}function wr(n){return n==null?null:typeof n=="string"?jv({className:n in Hv?Hv[n]:n,config:{}}):n instanceof Gv?n:jv(n)}class W1 extends bn{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=sn(e);let r=to(e);return this.maxValue!=null&&(r=ia(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}W1.className="ReLU",st(W1);class G1 extends bn{constructor(e){super(e??{}),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const r=sn(e);return Jp(r,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}G1.className="LeakyReLU",st(G1);class H1 extends bn{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=xr(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=wr(e.alphaRegularizer),this.alphaConstraint=Zr(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if(typeof e.sharedAxes!="number")throw new ce(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=Rn(e)).slice(1);if(this.sharedAxes!=null)for(const s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const r={};if(this.sharedAxes!=null)for(let s=1;s<e.length;++s)r[s]=e[s];this.inputSpec=[new Gr({ndim:e.length,axes:r})],this.built=!0}call(e,t){return e=sn(e),of(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Tr(this.alphaInitializer),alphaRegularizer:nr(this.alphaRegularizer),alphaConstraint:Yr(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}H1.className="PReLU",st(H1);
vendor: 6,922 bytes, line 78
78class j1 extends bn{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new gn(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const r=sn(e);return _d(r)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}j1.className="ELU",st(j1);class K1 extends bn{constructor(e){super(e??{}),this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const r=sn(e);return se(r,gt(Gs(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}K1.className="ThresholdedReLU",st(K1);class q1 extends bn{constructor(e){super(e??{}),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new B1().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){return be(()=>{let r=sn(e);const s=t.mask;if(s!=null){const a=se(ot(ua(r.shape),gt(s,r.dtype)),Pt(-1e9));r=Ue(r,a)}return this.axis instanceof Array?this.axis.length>1?oa(ot(r,tf(r,this.axis,!0))):this.softmax(r,this.axis[0]):this.softmax(r,this.axis)})}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Kd(n,e,t){if(typeof n=="number")return yh(n,e);if(n.length!==e)throw new ce(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${n.length} elements.`);for(let r=0;r<e;++r){const s=n[r];if(!bE(s))throw new ce(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(n)} including a non-integer number ${s}`)}return n}function lo(n,e,t,r,s=1){if(n==null)return n;let a;return a=t==="same"?n:n-(e+(e-1)*(s-1))+1,Math.floor((a+r-1)/r)}function Xo(n,e,t,r){if(n==null)return null;if(r==="valid")n=n*e+tc([t-e,0]);else{if(r!=="same")throw new ce(`Unsupport padding mode: ${r}.`);n*=e}return n}function X1(n,e){return be(()=>(Lr(e),e==="channelsFirst"?Qt(n,[0,2,3,1]):n))}function Kv(n,e){return be(()=>(Lr(e),e==="channelsFirst"?Qt(n,[0,2,3,4,1]):n))}function qv(n,e,t,r=[1,1],s="valid",a,i,o=null){return be(()=>{if(a==null&&(a="channelsLast"),Lr(a),n.rank!==3&&n.rank!==4)throw new ce(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(e.rank!==3&&e.rank!==4)throw new ce(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let l=X1(n,a);if(s==="causal")throw new gn("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Gw({x:l,filter:e,strides:r,pad:s==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:t,activation:o}),a==="channelsFirst"&&(l=Qt(l,[0,3,1,2])),l})}q1.className="Softmax",st(q1);class zg extends bn{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",zg.verifyArgs(t),this.rank=e,ls(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new gn(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Kd(t.kernelSize,e,"kernelSize"),this.strides=Kd(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Ha(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Lr(this.dataFormat),this.activation=ac(t.activation),this.useBias=t.useBias==null||t.useBias,this.biasInitializer=xr(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Zr(t.biasConstraint),this.biasRegularizer=wr(t.biasRegularizer),this.activityRegularizer=wr(t.activityRegularizer),this.dilationRate=Kd(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new ce(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new ce(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new ce(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(qo("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!u1(e.kernelSize,"number",1,3))throw new ce(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:sc(this.activation),useBias:this.useBias,biasInitializer:Tr(this.biasInitializer),biasRegularizer:nr(this.biasRegularizer),activityRegularizer:nr(this.activityRegularizer),biasConstraint:Yr(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class qd extends zg{constructor(e,t){super(e,t),this.kernel=null,qd.verifyArgs(t),this.filters=t.filters,ls(this.filters,"filters"),this.kernelInitializer=xr(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Zr(t.kernelConstraint),this.kernelRegularizer=wr(t.kernelRegularizer)}build(e){e=Rn(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new ce(`The channel dimension of the input should be defined. Found ${e[t]}`);const r=e[t],s=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:r}}],this.built=!0}call(e,t){return be(()=>{let r;e=sn(e);const s=this.bias==null?null:this.bias.read(),a=B2(this.activation.getClassName());if(a!=null&&this.rank===2)r=qv(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,a);else{if(this.rank===1)r=function(i,o,l,p=1,c="valid",h,d=1){return be(()=>{if(h==null&&(h="channelsLast"),Lr(h),i.shape.length!==3)throw new ce(`The input of a conv1dWithBias operation should be 3, but is ${i.shape.length} instead.`);if(o.shape.length!==3)throw new ce(`The kernel for a conv1dWithBias operation should be 3, but is ${o.shape.length} instead`);if(l!=null&&l.shape.length!==1)throw new ce(`The bias for a conv1dWithBias operation should be 1, but is ${l.shape.length} instead`);
78if(h==="channelsFirst"&&(i=Qt(i,[0,2,1])),c==="causal")throw new gn("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let m=_m(i,o,p,c==="same"?"same":"valid","NWC",d);return l!=null&&(m=so(m,l)),m})}(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)r=qv(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(this.rank!==3)throw new gn("convolutions greater than 3D are not implemented yet.");r=function(i,o,l,p=[1,1,1],c="valid",h,d){return be(()=>{if(h==null&&(h="channelsLast"),Lr(h),i.rank!==4&&i.rank!==5)throw new ce(`conv3dWithBias expects input to be of rank 4 or 5, but received ${i.rank}.`);if(o.rank!==4&&o.rank!==5)throw new ce(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${i.rank}.`);let m=Kv(i,h);if(c==="causal")throw new gn("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return m=n0(m,o,p,c==="same"?"same":"valid","NDHWC",d),l!=null&&(m=so(m,l)),h==="channelsFirst"&&(m=Qt(m,[0,4,1,2,3])),m})}(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate)}this.activation!=null&&(r=this.activation.apply(r))}return r})}computeOutputShape(e){e=Rn(e);const t=[],r=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let a=0;a<r.length;++a){const i=lo(r[a],this.kernelSize[a],this.padding,this.strides[a],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[a]);t.push(i)}let s=[e[0]];return this.dataFormat==="channelsLast"?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){const e={filters:this.filters,kernelInitializer:Tr(this.kernelInitializer),kernelRegularizer:nr(this.kernelRegularizer),kernelConstraint:Yr(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new ce(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class Xd extends qd{constructor(e){super(2,e),Xd.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!u1(e.kernelSize,"number",1,2))throw new ce(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Xd.className="Conv2D",st(Xd);class Yd extends qd{constructor(e){super(3,e),Yd.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&(!Array.isArray(e.kernelSize)||e.kernelSize.length!==1&&e.kernelSize.length!==3))throw new ce(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Yd.className="Conv3D",st(Yd);class Y1 extends Xd{constructor(e){if(super(e),this.inputSpec=[new Gr({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new ce(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if((e=Rn(e)).length!==4)throw new ce("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new ce("The channel dimension of the inputs should be defined. Found `None`.");const r=e[t],s=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Gr({ndim:4,axes:{[t]:r}})],this.built=!0}call(e,t){return be(()=>{let r=sn(e);if(r.shape.length!==4)throw new ce(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);const s=r.shape,a=s[0];let i,o;this.dataFormat==="channelsFirst"?(i=2,o=3):(i=1,o=2);const l=s[i],p=s[o],c=this.kernelSize[0],h=this.kernelSize[1],d=this.strides[0],m=this.strides[1],g=[a,Xo(l,d,c,this.padding),Xo(p,m,h,this.padding),this.filters];this.dataFormat!=="channelsLast"&&(r=Qt(r,[0,2,3,1]));let y=Dm(r,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(y=Qt(y,[0,3,1,2])),this.bias!=null&&(y=so(y,this.bias.read(),this.dataFormat)),this.activation!=null&&(y=this.activation.apply(y)),y})}computeOutputShape(e){const t=(e=Rn(e)).slice();let r,s,a;this.dataFormat==="channelsFirst"?(r=1,s=2,a=3):(r=3,s=1,a=2);const i=this.kernelSize[0],o=this.kernelSize[1],l=this.strides[0],p=this.strides[1];return t[r]=this.filters,t[s]=Xo(t[s],l,i,this.padding),t[a]=Xo(t[a],p,o,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Y1.className="Conv2DTranspose",st(Y1);class Z1 extends Yd{constructor(e){if(super(e),this.inputSpec=[new Gr({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new ce(`Conv3DTranspose currently supports only padding modes '
78same' and 'valid', but received padding mode ${this.padding}`)}build(e){if((e=Rn(e)).length!==5)throw new ce("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new ce("The channel dimension of the inputs should be defined. Found `None`.");const r=e[t],s=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Gr({ndim:5,axes:{[t]:r}})],this.built=!0}call(e,t){return be(()=>{let r=sn(e);if(r.shape.length!==5)throw new ce(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);const s=r.shape,a=s[0];let i,o,l;this.dataFormat==="channelsFirst"?(l=2,i=3,o=4):(l=1,i=2,o=3);const p=s[l],c=s[i],h=s[o],d=this.kernelSize[0],m=this.kernelSize[1],g=this.kernelSize[2],y=this.strides[0],w=this.strides[1],v=this.strides[2],N=[a,Xo(p,y,d,this.padding),Xo(c,w,m,this.padding),Xo(h,v,g,this.padding),this.filters];this.dataFormat!=="channelsLast"&&(r=Qt(r,[0,2,3,4,1]));let T=r0(r,this.kernel.read(),N,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(T=Qt(T,[0,4,1,2,3])),this.bias!==null&&(T=so(T,this.bias.read(),this.dataFormat)),this.activation!==null&&(T=this.activation.apply(T)),T})}computeOutputShape(e){const t=(e=Rn(e)).slice();let r,s,a,i;this.dataFormat==="channelsFirst"?(r=1,s=2,a=3,i=4):(r=4,s=1,a=2,i=3);const o=this.kernelSize[0],l=this.kernelSize[1],p=this.kernelSize[2],c=this.strides[0],h=this.strides[1],d=this.strides[2];return t[r]=this.filters,t[s]=Xo(t[s],c,o,this.padding),t[a]=Xo(t[a],h,l,this.padding),t[i]=Xo(t[i],d,p,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Z1.className="Conv3DTranspose",st(Z1);class Xv extends qd{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new ce("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new ce("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new ce(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=xr(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=wr(t.depthwiseRegularizer),this.depthwiseConstraint=Zr(t.depthwiseConstraint),this.pointwiseInitializer=xr(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=wr(t.pointwiseRegularizer),this.pointwiseConstraint=Zr(t.pointwiseConstraint)}build(e){if((e=Rn(e)).length<this.rank+2)throw new ce(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new ce(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const r=e[t],s=this.kernelSize.concat([r,this.depthMultiplier]),a=[];for(let o=0;o<this.rank;++o)a.push(1);a.push(r*this.depthMultiplier,this.filters);const i=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,i,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,i,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,i,this.biasConstraint):this.bias=null,this.inputSpec=[new Gr({ndim:this.rank+2,axes:{[t]:r}})],this.built=!0}call(e,t){return be(()=>{let r;if(e=sn(e),this.rank===1)throw new gn("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Qt(e,[0,2,3,1])),r=jm(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=so(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),this.dataFormat==="channelsFirst"&&(r=Qt(r,[0,3,1,2])),r})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Tr(this.depthwiseInitializer),e.pointwiseInitializer=Tr(this.pointwiseInitializer),e.depthwiseRegularizer=nr(this.depthwiseRegularizer),e.pointwiseRegularizer=nr(this.pointwiseRegularizer),e.depthwiseConstraint=Yr(this.depthwiseConstraint),e.pointwiseConstraint=Yr(this.pointwiseConstraint),e}}Xv.className="SeparableConv";class Q1 extends Xv{constructor(e){super(2,e)}}Q1.className="SeparableConv2D",st(Q1);class Ef extends qd{constructor(e){super(1,e),Ef.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!u1(e.kernelSize,"number",1,1))throw new ce(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Ef.className="Conv1D",st(Ef);class J1 extends bn{constructor(e){super(e),typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return be(()=>{if(e=sn(e),this.dataFormat==="channelsLast"){const r=mg(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return mg(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const r=mg(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return mg(r,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}J1.className="Cropping2D",st(J1);class eb extends bn{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Lr(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,t=this.interpolation,xh(pE,"InterpolationFormat",t)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],r=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,r]}{const t=e[1]==null?null:this.size[0]*e[1],r=e[2]==null?null:this.size[1]*e[2];return[e[0],t,r,e[3]]}}call(e,t){return be(()=>{let r=sn(e);const s=r.shape;if(this.dataFormat==="channelsFirst"){r=Qt(r,[0,2,3,1]);const a=this.size[0]*s[2],i=this.size[1]*s[3],o=this.interpolation==="nearest"?hi.resizeNearestNeighbor(r,[a,i]):hi.resizeBilinear(r,[a,i]);return Qt(o,[0,3,1,2])}{const a=this.size[0]*s[1],i=this.size[1]*s[2];return this.interpolation==="nearest"?hi.resizeNearestNeighbor(r,[a,i]):hi.resizeBilinear(r,[a,i])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}eb.className="UpSampling2D",st(eb);class tb extends zg{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=xr(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Zr(e.depthwiseConstraint),this.depthwiseRegularizer=wr(e.depthwiseRegularizer)}build(e){if((e=Rn(e)).length<4)throw new ce(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new ce(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const r=e[t],s=[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[r*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return be(()=>{let r=function(s,a,i=[1,1],o="valid",l,p){return be(()=>{l==null&&(l="channelsLast"),Lr(l);let c=X1(s,l);if(s.rank!==4)throw new ce(`Input for depthwiseConv2d is required to be 4-D, but is instead ${s.rank}
78-D`);if(a.rank!==4)throw new ce(`depthwiseKernel is required to be 4-D, but is instead ${a.rank}-D`);return c=Rd(c,a,i,o==="same"?"same":"valid","NHWC",p),l==="channelsFirst"&&(c=Qt(c,[0,3,1,2])),c})}(e=sn(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=so(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=Rn(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=lo(t,this.kernelSize[0],this.padding,this.strides[0]),i=lo(r,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,a,i]:[e[0],a,i,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Tr(this.depthwiseInitializer),e.depthwiseRegularizer=nr(this.depthwiseRegularizer),e.depthwiseConstraint=Yr(this.depthwiseRegularizer),e}}function Yv(n,e,t,r){if(Array.isArray(n)){if(e!=null||t!=null)throw new ce("When inputs is an array, neither initialState or constants should be provided");r!=null&&(t=n.slice(n.length-r,n.length),n=n.slice(0,n.length-r)),n.length>1&&(e=n.slice(1,n.length)),n=n[0]}function s(a){return a==null||Array.isArray(a)?a:[a]}return{inputs:n,initialState:e=s(e),constants:t=s(t)}}function Zv(n,e,t,r=!1,s,a,i=!1,o=!1){return be(()=>{const l=e.shape.length;if(l<3)throw new ce(`Input should be at least 3D, but is ${l}D.`);const p=[1,0].concat(ro(2,l));e=Qt(e,p),a!=null,i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),s!=null&&((s=gt(gt(s,"bool"),"float32")).rank===l-1&&(s=ws(s,-1)),s=Qt(s,p)),r&&(e=Wa(e,0),s!=null&&(s=Wa(s,0)));const c=[];let h,d=t;const m=e.shape[0],g=Ga(e);let y,w;s!=null&&(y=Ga(s));for(let v=0;v<m;++v){const N=g[v],T=be(()=>n(N,d));if(s==null)h=T[0],d=T[1];else{const $=be(()=>{const _=y[v],L=ot(Ta(_),_);return{output:Ue(se(T[0],_),se(d[0],L)),newStates:d.map((z,O)=>Ue(se(T[1][O],_),se(z,L)))}});h=$.output,d=$.newStates}o&&c.push(h)}return o&&(w=Hs(c,1)),[h,w,d]})}tb.className="DepthwiseConv2D",st(tb);class co extends bn{constructor(e){let t;if(super(e),e.cell==null)throw new ce("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Vg({cells:e.cell}):e.cell,t.stateSize==null)throw new ce("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences!=null&&e.returnSequences,this.returnState=e.returnState!=null&&e.returnState,this.goBackwards=e.goBackwards!=null&&e.goBackwards,this._stateful=e.stateful!=null&&e.stateful,this.unroll=e.unroll!=null&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Gr({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return this.states_==null?ro(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(e=>null):this.states_}setStates(e){this.states_=e}computeOutputShape(e){v1(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const r=t[0];let s;if(s=this.returnSequences?[e[0],e[1],r]:[e[0],r],this.returnState){const a=[];for(const i of t)a.push([e[0],i]);return[s].concat(a)}return s}computeMask(e,t){return be(()=>{Array.isArray(t)&&(t=t[0]);const r=this.returnSequences?t:null;if(this.returnState){const s=this.states.map(a=>null);return[r].concat(s)}return r})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let r=0;r<e;++r)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(this.numConstants!=null)throw new gn("Constants support is not implemented in RNN yet.");v1(e)&&(e=e[0]);const t=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new Gr({shape:[t,null,...r]});const s=[e[0]].concat(e.slice(2));let a;if(this.cell.build(s),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],this.stateSpec!=null){if(!le(this.stateSpec.map(i=>i.shape[i.shape.length-1]),a))throw new ce(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(i=>new Gr({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){be(()=>{if(!this.stateful)throw new Ko("Cannot call resetStates() on an RNN Layer that is not stateful.");const r=this.inputSpec[0].shape[0];if(r==null)throw new ce("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Wr([r,s])):this.states_=[Wr([r,this.cell.stateSize])];else if(e==null)on(this.states_),this.keptStates!=null&&(on(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Wr([r,s])):this.states_[0]=Wr([r,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new ce(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):on(this.states_);for(let s=0;s<this.states_.length;++s){const a=e[s],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[s]:this.cell.stateSize,o=[r,i];if(!le(a.shape,o))throw new ce(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${a.shape}`);this.states_[s]=a}}this.states_=this.states_.map(s=>_r(s.clone()))})}apply(e,t){let r=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const a=Yv(e,r,s,this.numConstants);e=a.inputs,r=a.initialState,s=a.constants;let i=[],o=[];if(r!=null){t.initialState=r,i=i.concat(r),this.stateSpec=[];for(const l of r)this.stateSpec.push(new Gr({shape:l.shape}));o=o.concat(this.stateSpec)}if(s!=null&&(t.constants=s,i=i.concat(s),this.numConstants=s.length),i[0]instanceof ao){const l=[e].concat(i),p=this.inputSpec.concat(o),c=this.inputSpec;this.inputSpec=p;const h=super.apply(l,t);return this.inputSpec=c,h}return super.apply(e,t)}call(e,t){return be(()=>{const r=t==null?null:t.mask,s=t==null?null:t.training;let a=t==null?null:t.initialState;e=sn(e),a==null&&(a=this.stateful?this.states_:this.getInitialState(e));const i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==i)throw new ce(`RNN Layer has ${i} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const o={training:s},l=Zv((m,g)=>{const y=this.cell.call([m].concat(g),o);return[y[0],y.slice(1)]},e,a,this.goBackwards,r,null,this.unroll,this.returnSequences),p=l[0],c=l[1],h=l[2];this.stateful&&this.resetStates(h,s);const d=this.returnSequences?c:p;return this.returnState?[d].concat(h):d})}getInitialState(e){return be(()=>{let t=Wr(e.shape);return t=Dt(t,[1,2]),t=bf(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(r=>r>1?d1(t,[1,r]):t):this.cell.stateSize>1?[d1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);const r=this.cell.getConfig();return this.getClassName()===co.className&&(t.cell={className:this.cell.getClassName(),config:r}),Object.assign(Object.assign(Object.assign({},r),e),t)}static fromConfig(e,t,r={}){const s=io(t.cell,r);return new e(Object.assign(t,{cell:s}))}}co.className="RNN",st(co);class Cf extends bn{}class Pg extends Cf{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ls(this.units,"units"),this.activation=ac(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null||e.useBias,this.kernelInitializer=xr(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xr(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xr(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=wr(e.kernelRegularizer),this.recurrentRegularizer=wr(e.recurrentRegularizer),this.biasRegularizer=wr(e.biasRegularizer),this.kernelConstraint=Zr(e.kernelConstraint),this.recurrentConstraint=Zr(e.recurrentConstraint),this.biasConstraint=Zr(e.biasConstraint),this.dropout=Wd([1,tc([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Wd([1,tc([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Rn(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return be(()=>{if(e.length!==2)throw new ce(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];const s=t.training!=null&&t.training;let a;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ic({ones:()=>Ta(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ic({ones:()=>Ta(r),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=this.recurrentDropoutMask;a=Uu(i!=null?se(e,i):e,this.kernel.read()),this.bias!=null&&(a=so(a,this.bias.read())),o!=null&&(r=se(r,o));let l=Ue(a,Uu(r,this.recurrentKernel.read()));return this.activation!=null&&(l=this.activation.apply(l)),[l,l]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:sc(this.activation),useBias:this.useBias,kernelInitializer:Tr(this.kernelInitializer),recurrentInitializer:Tr(this.recurrentInitializer),biasInitializer:Tr(this.biasInitializer),kernelRegularizer:nr(this.kernelRegularizer),recurrentRegularizer:nr(this.recurrentRegularizer),biasRegularizer:nr(this.biasRegularizer),activityRegularizer:nr(this.activityRegularizer),kernelConstraint:Yr(this.kernelConstraint),recurrentConstraint:Yr(this.recurrentConstraint),biasConstraint:Yr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}Pg.className="SimpleRNNCell",st(Pg);class nb extends co{constructor(e){e.cell=new Pg(e),super(e)}call(e,t){return be(()=>{this.cell.dropoutMask!=null&&(on(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(on(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const r=t==null?null:t.mask,s=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:s,initialState:a})})}static fromConfig(e,t){return new e(t)}}nb.className="SimpleRNN",st(nb);class Bg extends Cf{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new ce("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ls(this.units,"units"),this.activation=ac(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ac(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null||e.useBias,this.kernelInitializer=xr(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xr(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xr(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=wr(e.kernelRegularizer),this.recurrentRegularizer=wr(e.recurrentRegularizer),this.biasRegularizer=wr(e.biasRegularizer),this.kernelConstraint=Zr(e.kernelConstraint),this.recurrentConstraint=Zr(e.recurrentConstraint),this.biasConstraint=Zr(e.biasConstraint),this.dropout=Wd([1,tc([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Wd([1,tc([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=Rn(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return be(()=>{if(e.length!==2)throw new ce(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const r=t.training!=null&&t.training;let s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ic({ones:()=>Ta(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ic({ones:()=>Ta(s),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,l,p;0<this.dropout&&this.dropout<1&&(e=se(e,a[0]));let c=Uu(e,this.kernel.read());this.useBias&&(c=so(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=se(s,i[0]));const h=this.recurrentKernel.read(),[d,m]=la(h,[2*this.units,this.units],h.rank-1),g=Uu(s,d),[y,w,v]=la(c,3,c.rank-1),[N,T]=la(g,2,g.rank-1);o=this.recurrentActivation.apply(Ue(y,N)),l=this.recurrentActivation.apply(Ue(w,T));const $=Uu(se(l,s),m);p=this.activation.apply(Ue(v,$));const _=Ue(se(o,s),se(Ue(1,Vn(o)),p));return[_,_]}
78)}getConfig(){const e=super.getConfig(),t={units:this.units,activation:sc(this.activation),recurrentActivation:sc(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Tr(this.kernelInitializer),recurrentInitializer:Tr(this.recurrentInitializer),biasInitializer:Tr(this.biasInitializer),kernelRegularizer:nr(this.kernelRegularizer),recurrentRegularizer:nr(this.recurrentRegularizer),biasRegularizer:nr(this.biasRegularizer),activityRegularizer:nr(this.activityRegularizer),kernelConstraint:Yr(this.kernelConstraint),recurrentConstraint:Yr(this.recurrentConstraint),biasConstraint:Yr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Bg.className="GRUCell",st(Bg);class rb extends co{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Bg(e),super(e)}call(e,t){return be(()=>{this.cell.dropoutMask!=null&&(on(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(on(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const r=t==null?null:t.mask,s=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:s,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}rb.className="GRU",st(rb);class $f extends Cf{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ls(this.units,"units"),this.activation=ac(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ac(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null||e.useBias,this.kernelInitializer=xr(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xr(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xr(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=wr(e.kernelRegularizer),this.recurrentRegularizer=wr(e.recurrentRegularizer),this.biasRegularizer=wr(e.biasRegularizer),this.kernelConstraint=Zr(e.kernelConstraint),this.recurrentConstraint=Zr(e.recurrentConstraint),this.biasConstraint=Zr(e.biasConstraint),this.dropout=Wd([1,tc([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Wd([1,tc([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const r=(e=Rn(e))[e.length-1];let s;if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const a=this.biasInitializer,i=this.units;s=new((t=class extends fi{apply(o,l){const p=a.apply([i]),c=new yg().apply([i]),h=a.apply([2*i]);return j2(j2(p,c),h)}}).className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return be(()=>{const r=t.training!=null&&t.training;if(e.length!==3)throw new ce(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ic({ones:()=>Ta(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ic({ones:()=>Ta(s),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=this.recurrentDropoutMask;let l,p,c,h;0<this.dropout&&this.dropout<1&&(e=se(e,i[0]));let d=Uu(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=se(s,o[0])),d=Ue(d,Uu(s,this.recurrentKernel.read())),this.useBias&&(d=so(d,this.bias.read()));const[m,g,y,w]=la(d,4,d.rank-1);l=this.recurrentActivation.apply(m),p=this.recurrentActivation.apply(g),c=Ue(se(p,a),se(l,this.activation.apply(y))),h=this.recurrentActivation.apply(w);const v=se(h,this.activation.apply(c));return[v,v,c]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:sc(this.activation),recurrentActivation:sc(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Tr(this.kernelInitializer),recurrentInitializer:Tr(this.recurrentInitializer),biasInitializer:Tr(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:nr(this.kernelRegularizer),recurrentRegularizer:nr(this.recurrentRegularizer),biasRegularizer:nr(this.biasRegularizer),activityRegularizer:nr(this.activityRegularizer),kernelConstraint:Yr(this.kernelConstraint),recurrentConstraint:Yr(this.recurrentConstraint),biasConstraint:Yr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}$f.className="LSTMCell",st($f);
vendor: 5,725 bytes, line 78
78class sb extends co{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new $f(e),super(e)}call(e,t){return be(()=>{this.cell.dropoutMask!=null&&(on(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(on(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const r=t==null?null:t.mask,s=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:s,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}sb.className="LSTM",st(sb);class Vg extends Cf{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return be(()=>{let r=e.slice(1);const s=[];for(const o of this.cells.slice().reverse())Array.isArray(o.stateSize)?s.push(r.splice(0,o.stateSize.length)):s.push(r.splice(0,1));s.reverse();const a=[];let i;for(let o=0;o<this.cells.length;++o){const l=this.cells[o];r=s[o],i=o===0?[e[0]].concat(r):[i[0]].concat(r),i=l.call(i,t),a.push(i.slice(1))}r=[];for(const o of a.slice().reverse())r.push(...o);return[i[0]].concat(r)})}build(e){let t;v1(e)&&(e=e[0]),this.cells.forEach((r,s)=>{wh(`RNNCell_${s}`,()=>{r.build(e),t=Array.isArray(r.stateSize)?r.stateSize[0]:r.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map(r=>({className:r.getClassName(),config:r.getConfig()}))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,r={}){const s=[];for(const a of t.cells)s.push(io(a,r));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const r of this.cells)t.push(...r.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return k1(e)}setWeights(e){const t=[];for(const r of this.cells){const s=r.weights.length,a=e.splice(s);for(let i=0;i<r.weights.length;++i)t.push([r.weights[i],a[i]])}N1(t)}}function ic(n){const{ones:e,rate:t,training:r=!1,count:s=1,dropoutFunc:a}=n,i=()=>a!=null?a(e(),t):q2(e(),t),o=()=>wf(i,e,r);return!s||s<=1?_r(o().clone()):Array(s).fill(void 0).map(o).map(l=>_r(l.clone()))}Vg.className="StackedRNNCells",st(Vg);class Qv extends co{constructor(e){if(e.unroll)throw new gn("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new gn("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Gr({ndim:5})]}call(e,t){return be(()=>{if(this.cell.dropoutMask!=null&&(on(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(on(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new ce("ConvRNN2D cell does not support constants");const r=t==null?null:t.mask,s=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:s,initialState:a})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return be(()=>{const{stateSize:t}=this.cell,r=e.shape,s=this.computeSingleOutputShape(r),a=Wr([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){be(()=>{if(!this.stateful)throw new Ko("Cannot call resetStates() on an RNN Layer that is not stateful.");const r=this.inputSpec[0].shape,s=this.computeSingleOutputShape(r),a=[s[0],...s.slice(2)];if(r[0]==null)throw new ce("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Wr(a)):this.states_=[Wr(a)];else if(e==null)on(this.states_),this.keptStates!=null&&(on(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Wr(a)):this.states_[0]=Wr(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new ce(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):on(this.states_);for(let i=0;i<this.states_.length;++i){const o=e[i],l=a;if(!le(o.shape,l))throw new ce(`State ${i} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${o.shape}`);this.states_[i]=o}}this.states_=this.states_.map(i=>_r(i.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:r,kernelSize:s,padding:a,strides:i,dilationRate:o}=this.cell,l=t==="channelsFirst",p=e[l?3:2],c=e[l?4:3],h=lo(p,s[0],a,i[0],o[0]),d=lo(c,s[1],a,i[1],o[1]);return[...e.slice(0,2),...l?[r,h,d]:[h,d,r]]}}Qv.className="ConvRNN2D";class Ug extends $f{constructor(e){const{filters:t,kernelSize:r,strides:s,padding:a,dataFormat:i,dilationRate:o}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,ls(this.filters,"filters"),this.kernelSize=Kd(r,2,"kernelSize"),this.kernelSize.forEach(l=>ls(l,"kernelSize")),this.strides=Kd(s||1,2,"strides"),this.strides.forEac
78h(l=>ls(l,"strides")),this.padding=a||"valid",Ha(this.padding),this.dataFormat=i||"channelsLast",Lr(this.dataFormat),this.dilationRate=Kd(o||1,2,"dilationRate"),this.dilationRate.forEach(l=>ls(l,"dilationRate"))}build(e){var t;e=Rn(e);const r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new ce(`The channel dimension of the input should be defined. Found ${e[r]}`);const s=e[r],a=this.kernelSize.concat([s,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const i=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){const l=this.biasInitializer,p=this.filters;o=new((t=class extends fi{apply(c,h){return h1([l.apply([p]),ua([p]),l.apply([2*p])])}}).className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return be(()=>{if(e.length!==3)throw new ce(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const r=t.training||!1,s=e[0],a=e[1],i=e[2];0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ic({ones:()=>Ta(s),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const o=this.dropoutMask,l=(ze,We,Je)=>We&&We[Je]?se(We[Je],ze):ze;let p=l(s,o,0),c=l(s,o,1),h=l(s,o,2),d=l(s,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ic({ones:()=>Ta(a),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const m=this.recurrentDropoutMask;let g=l(a,m,0),y=l(a,m,1),w=l(a,m,2),v=l(a,m,3);const[N,T,$,_]=la(this.kernel.read(),4,3),[L,z,O,V]=this.useBias?la(this.bias.read(),4):[null,null,null,null];p=this.inputConv(p,N,L,this.padding),c=this.inputConv(c,T,z,this.padding),h=this.inputConv(h,$,O,this.padding),d=this.inputConv(d,_,V,this.padding);const[U,X,ne,ae]=la(this.recurrentKernel.read(),4,3);g=this.recurrentConv(g,U),y=this.recurrentConv(y,X),w=this.recurrentConv(w,ne),v=this.recurrentConv(v,ae);const Ie=this.recurrentActivation.apply(Ue(p,g)),me=this.recurrentActivation.apply(Ue(c,y)),we=Ue(se(me,i),se(Ie,this.activation.apply(Ue(h,w)))),$e=se(this.recurrentActivation.apply(Ue(d,v)),this.activation.apply(we));return[$e,$e,we]})}getConfig(){const e=super.getConfig(),{units:t}=e,r=function(a,i){var o={};for(var l in a)Object.prototype.hasOwnProperty.call(a,l)&&i.indexOf(l)<0&&(o[l]=a[l]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var p=0;for(l=Object.getOwnPropertySymbols(a);p<l.length;p++)i.indexOf(l[p])<0&&Object.prototype.propertyIsEnumerable.call(a,l[p])&&(o[l[p]]=a[l[p]])}return o}(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},r),s)}inputConv(e,t,r,s){const a=Fu(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return r?so(a,r,this.dataFormat):a}recurrentConv(e,t){return Fu(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}Ug.className="ConvLSTM2DCell",st(Ug);class ab extends Qv{constructor(e){const t=new Ug(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}ab.className="ConvLSTM2D",st(ab);class Wg extends bn{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;const t=e.shape,r=[];for(let s=0;s<this.noiseShape.length;++s)r.push(this.noiseShape[s]==null?t[s]:this.noiseShape[s]);return r}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e);if(0<this.rate&&this.rate<1){const s=t.training!=null&&t.training,a=this.getNoiseShape(r);return wf(()=>q2(r,this.rate,a,this.seed),()=>
78r,s)}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Wg.className="Dropout",st(Wg);class ib extends Wg{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}ib.className="SpatialDropout1D",st(ib);class ob extends bn{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,ls(this.units,"units"),this.activation=ac(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=xr(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=xr(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Zr(e.kernelConstraint),this.biasConstraint=Zr(e.biasConstraint),this.kernelRegularizer=wr(e.kernelRegularizer),this.biasRegularizer=wr(e.biasRegularizer),this.activityRegularizer=wr(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=Rn(e))[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=Rn(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e),s=B2(this.activation.getClassName());let a;return s!=null?a=Uu(r,this.kernel.read(),s,this.bias?this.bias.read():null):(a=Uu(r,this.kernel.read()),this.bias!=null&&(a=so(a,this.bias.read())),this.activation!=null&&(a=this.activation.apply(a))),a})}getConfig(){const e={units:this.units,activation:sc(this.activation),useBias:this.useBias,kernelInitializer:Tr(this.kernelInitializer),biasInitializer:Tr(this.biasInitializer),kernelRegularizer:nr(this.kernelRegularizer),biasRegularizer:nr(this.biasRegularizer),activityRegularizer:nr(this.activityRegularizer),kernelConstraint:Yr(this.kernelConstraint),biasConstraint:Yr(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}ob.className="Dense",st(ob);class ub extends bn{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Rn(e);for(const t of e.slice(1))if(t==null)throw new ce(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ec(e,1)]}call(e,t){return be(()=>{this.invokeCallHook(e,t);let r=sn(e);if(this.dataFormat==="channelsFirst"&&r.rank>1){const s=[0];for(let a=2;a<r.rank;++a)s.push(a);s.push(1),r=Qt(r,s)}return function(s){if(s.rank<=1)throw new ce(`batchFlatten requires a minimum rank of 2. Got rank: ${s.rank}.`);const a=[s.shape[0],ec(s.shape,1)];return he(s,a)}(r)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}ub.className="Flatten",st(ub);class lb extends bn{constructor(e){super(e),this.supportsMasking=!0,this.activation=ac(e.activation)}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e);return this.activation.apply(r)})}getConfig(){const e={activation:sc(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}lb.className="Activation",st(lb);class cb extends bn{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return be(()=>{return e=sn(e),r=e,s=this.n,be(()=>{if(r.shape.length!==2)throw new ce(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);return d1(bf(r,1),[1,s,1])});var r,s})}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}cb.className="RepeatVector",st(cb);class hb extends bn{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){const r="Total size of new array must be unchanged.",s=t.slice();let a=1,i=null;for(let l=0;l<s.length;++l){const p=s[l];
vendor: 4,792 bytes, line 78
78if(this.isUnknown(p)){if(i!==null)throw new ce("Can only specifiy one unknown dimension.");i=l}else a*=p}const o=ec(e);if(i!==null){if(a===0||o%a!==0)throw new ce(r);s[i]=o/a}else if(o!==a)throw new ce(r);return s}computeOutputShape(e){let t=!1;for(let r=0;r<e.length;++r)if(this.isUnknown(e[r])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e),s=r.shape,a=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return he(r,a)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}hb.className="Reshape",st(hb);class db extends bn{constructor(e){if(super(e),e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=ro(1,e.dims.length+1);if(!le(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Gr({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=Rn(e)).slice();return this.dims.forEach((r,s)=>{t[s+1]=e[r]}),t}call(e,t){return Qt(sn(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}db.className="Permute",st(db);class pb extends bn{constructor(e){super(e??{}),this.supportsMasking=!0,this.maskValue=e!=null?e.maskValue==null?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const r=sn(e);return Hp(ph(r,this.maskValue),-1)}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e),s=Hp(ph(r,this.maskValue),-1,!0);return se(r,gt(s,r.dtype))})}}pb.className="Masking",st(pb);class fb extends bn{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Un(e.inputLength))}this.inputDim=e.inputDim,ls(this.inputDim,"inputDim"),this.outputDim=e.outputDim,ls(this.outputDim,"outputDim"),this.embeddingsInitializer=xr(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=wr(e.embeddingsRegularizer),this.activityRegularizer=wr(e.activityRegularizer),this.embeddingsConstraint=Zr(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return be(()=>this.maskZero?(e=sn(e),ph(e,mn(e))):null)}computeOutputShape(e){if(e=Rn(e),this.inputLength==null)return[...e,this.outputDim];const t=Un(this.inputLength);if(t.length!==e.length-1)throw new ce(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let s=0;s<t.length;++s){const a=t[s],i=e[s+1];if(a!=null&&i!=null&&a!==i)throw new ce(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);a==null&&(t[r]=i),r++}}return[e[0],...t,this.outputDim]}call(e,t){return be(()=>{this.invokeCallHook(e,t);let r=sn(e);r.dtype!=="int32"&&(r=Vu(r,"int32"));const s=K2(this.embeddings.read(),he(r,[r.size]));return he(s,Rn(this.computeOutputShape(r.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Tr(this.embeddingsInitializer),embeddingsRegularizer:nr(this.embeddingsRegularizer),activityRegularizer:nr(this.activityRegularizer),embeddingsConstraint:Yr(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}fb.className="Embedding",st(fb);class Ih extends bn{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new gn}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;const r=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){const a=e[e.length-t.length+s],i=t[s];if(a==null||i==null||a<0||i<0)r.push(null);else if(a===1)r.push(i);else if(i===1)r.push(a);else{if(a!==i)throw new ce("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));
78r.push(a)}}return r}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Rn(e)]),e.length<2)throw new ce(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const a of e)a!=null&&a[0]!==null&&t.push(a[0]);if(t=Jl(t),t.length>1)throw new ce(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let r=e[0]==null?null:e[0].slice(1);for(let a=1;a<e.length;++a){const i=e[a]==null?null:e[a].slice(1);r=this.computeElementwiseOpOutputShape(r,i)}const s=e.map(a=>a.length);e.indexOf(null)===-1&&Jl(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return be(()=>{if(this.reshapeRequired){const r=[],s=e.map(a=>a.rank);if(s.indexOf(null)===-1){const a=tc(s);for(let i of e){const o=i.rank;for(let l=0;l<a-o;++l)i=bf(i,1);r.push(i)}return this.mergeFunction(r)}{let a=!1;for(const l of e){const p=l.rank;if(p==null){const c=l.shape,h=c[0],d=c.slice(1).concat([h]);let m=he(l,[h].concat(ec(c.slice(1))));m=Qt(m,[1,0]),m=he(m,d),r.push(m),a=!0}else if(p>1){const c=ro(1,p).concat([0]);r.push(Qt(l,c)),a=!0}else r.push(l)}let i=this.mergeFunction(r);const o=i.rank;if(a){if(o==null){const l=i.shape,p=l[l.length-1],c=[p].concat(l.slice(0,l.length-1));i=he(Qt(he(i,[-1,p]),[1,0]),c)}else if(o>1){const l=[o-1].concat(ro(0,o-1));i=Qt(i,l)}}return i}}return this.mergeFunction(e)})}computeOutputShape(e){let t;t=e[0]==null?null:e[0].slice(1);for(let s=1;s<e.length;++s){const a=e[s]==null?null:e[s].slice(1);t=this.computeElementwiseOpOutputShape(t,a)}let r=[];for(const s of e)s!=null&&s[0]!==null&&r.push(s[0]);return r=Jl(r),t=r.length===1?r.concat(t):[null].concat(t),t}computeMask(e,t){return be(()=>{if(t==null)return null;if(!Array.isArray(t))throw new ce("`mask` should be an Array");if(!Array.isArray(e))throw new ce("`inputs` should be an Array");if(t.length!==e.length)throw new ce(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;let r=(t=t.map(s=>s==null?s:ws(s,0)))[0];for(let s=1;s<t.length-1;++s)r=ci(r,t[s]);return r})}}class mb extends Ih{constructor(e){super(e)}mergeFunction(e){return be(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=Ue(t,e[r]);return t})}}mb.className="Add",st(mb);class gb extends Ih{constructor(e){super(e)}mergeFunction(e){return be(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=se(t,e[r]);return t})}}gb.className="Multiply",st(gb);class yb extends Ih{constructor(e){super(e)}mergeFunction(e){return be(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=Ue(t,e[r]);return se(1/e.length,t)})}}yb.className="Average",st(yb);class bb extends Ih{constructor(e){super(e)}mergeFunction(e){return be(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=Nr(t,e[r]);return t})}}bb.className="Maximum",st(bb);class xb extends Ih{constructor(e){super(e)}mergeFunction(e){return be(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=Xl(t,e[r]);return t})}}xb.className="Minimum",st(xb);class wb extends Ih{constructor(e){super(e),this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||e.length===1)throw new ce("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const s of e)if(s!=null){t=!1;break}if(t)return;const r=[];for(let s=0;s<e.length;++s){const a=e[s].slice();a.splice(this.axis,1);let i=!1;for(const o of r)if(le(o,a)){i=!0;break}i||r.push(a)}if(r.length>1)throw new ce("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return be(()=>h1(e,this.axis))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new ce("A `Concatenate` layer should be called on a list of inputs.");const t=e,r=t[0].slice(),s=this.axis<0?r.length+this.axis:this.axis;for(const a of t.slice(1)){if(r[s]==null||a[s]==null){r[s]=null;break}r[s]+=a[s]}return r}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new ce("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new ce("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new ce(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return be(()=>{let r=!0;if(t.forEach(i=>
78{i==null||(r=!1)}),r)return null;const s=[];for(let i=0;i<e.length;++i)t[i]==null?s.push(gt(Ta(e[i]),"bool")):t[i].rank<e[i].rank?s.push(ws(t[i],-1)):s.push(t[i]);const a=Fr(s,this.axis);return Rm(a,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Af(n,e){for(;n<0;)n+=e;return n}wb.className="Concatenate",st(wb);class vb extends Ih{constructor(e){super(e),this.axes=e.axes,this.normalize=e.normalize!=null&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){A(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],r=e[1];if(t.length>3||r.length>3)throw new gn("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,r);if(t[s[0]]!==r[s[1]])throw new ce(`Dimension incompatibility: ${t[s[0]]} !== ${r[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new ce(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,r=e[0],s=e[1];return t=Array.isArray(this.axes)?this.axes.map((a,i)=>Af(a,e[i].shape.length)):[Af(this.axes,r.shape.length),Af(this.axes,s.shape.length)],this.normalize&&(r=$g(r,t[0]),s=$g(s,t[1])),function(a,i,o){if(a.shape.length>3||i.shape.length>3)throw new gn("batchDot is not implemented for tensors of 4D or higher rank yet");if(A(a.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${a.shape.length}`),A(a.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${i.shape.length}`),typeof o=="number"&&(o=[o,o]),a.dtype==="complex64"||i.dtype==="complex64")throw new gn("batchDot is not implemented for complex64-type Tensors yet.");const l=a.shape.length,p=i.shape.length;o==null&&(o=[l-1,p-2]);const c=o;return be(()=>{let h,d;if(l>p){h=l-p;const m=[];for(let g=0;g<h;++g)m.push(1);i=he(i,i.shape.concat(m))}else if(p>l){h=p-l;const m=[];for(let g=0;g<h;++g)m.push(1);a=he(a,a.shape.concat(m))}else h=0;if(a.shape.length===2&&i.shape.length===2)d=c[0]===c[1]?Dt(se(a,i),c[0]):Dt(se(Qt(a,[1,0]),i),c[1]);else{const m=c[0]!==a.shape.length-1,g=c[1]===i.shape.length-1;d=Yt(a,i,m,g)}if(h>0){let m;m=l>p?l+p-3:l-1;const g=[];for(let y=m;y<m+h;++y)g.push(y);d=Zl(d,g)}return d.shape.length===1&&(d=ws(d,1)),d})}(r,s,t)}interpretAxes(e,t){let r;return r=Array.isArray(this.axes)?this.axes:[Af(this.axes,e.length),Af(this.axes,t.length)],r}computeOutputShape(e){A(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),r=e[1].slice();if(t.length>3||r.length>3)throw new gn("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,r);t.splice(s[0],1),r.splice(s[1],1),r.splice(0,1);const a=t.concat(r);return a.length===1&&a.push(1),a}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}vb.className="Dot",st(vb);class kb extends bn{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e);return wf(()=>Ue(gg(r.shape,0,this.stddev),r),()=>r,t.training||!1)})}}kb.className="GaussianNoise",st(kb);class Nb extends bn{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return be(()=>{this.invokeCallHook(e,t);const r=sn(e);return this.rate>0&&this.rate<1?wf(()=>{const s=Math.sqrt(this.rate/(1-this.rate));return se(r,gg(r.shape,1,s))},()=>r,t.training||!1):r})}}Nb.className="GaussianDropout",st(Nb);class Ib extends bn{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||sn(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return be(()=>{if(this.rate<1&&this.rate>0){const r=this._getNoiseShape(e);return wf(()=>{const a=sn(e),i=-1.7580993408473766;let o=Mu(Yl(r),this.rate);o=Vu(o,"float32");const l=((1-this.rate)*(1+this.rate*i**2))**-.5,p=-l*i*this.rate,c=Ue(se(a,o),se(Ue(o,-1),i));return Ue(se(c,l),p)},()=>sn(e),t.training||!1)}return e})}}function Rf(n,e,t,r,s,a=.001){let i;if(n.rank===2)i=jy(n,e,t,r,s,a);else if(n.rank===3)i=Ky(n,e,t,r,s,a);else{if(n.rank!==4)throw new gn(`batchNormalization is not implemented for array of rank ${n.rank}
78 yet`);i=qy(n,e,t,r,s,a)}return i}Ib.className="AlphaDropout",st(Ib);class Sb extends bn{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null||e.center,this.scale=e.scale==null||e.scale,this.betaInitializer=xr(e.betaInitializer||"zeros"),this.gammaInitializer=xr(e.gammaInitializer||"ones"),this.movingMeanInitializer=xr(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=xr(e.movingVarianceInitializer||"ones"),this.betaConstraint=Zr(e.betaConstraint),this.gammaConstraint=Zr(e.gammaConstraint),this.betaRegularizer=wr(e.betaRegularizer),this.gammaRegularizer=wr(e.gammaRegularizer)}build(e){e=Rn(e);const t=this.axis>=0?this.axis:this.axis+e.length,r=e[t];if(r==null)throw new ce(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Gr({ndim:e.length,axes:{[t]:r}})];const s=[r];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return be(()=>{const r=t.training!=null&&t.training,s=sn(e),a=s.shape,i=a.length,o=ro(0,i),l=this.axis>=0?this.axis:this.axis+i;o.splice(l,1);const p=yh(1,i);p[l]=a[l];const c=o.slice();c.sort();const h=!le(c,ro(0,i).slice(0,i-1));if(!r)return(()=>{if(h){const w=he(this.movingMean.read(),p),v=he(this.movingVariance.read(),p),N=this.center?he(this.beta.read(),p):null,T=this.scale?he(this.gamma.read(),p):null;return Rf(s,w,v,N,T,this.epsilon)}return Rf(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)})();const[d,m,g]=function(w,v,N,T,$=.001){return le(T.slice().sort(),ro(0,w.rank-1))?function(_,L,z,O,V=.001){return be(()=>{const U=sf(_,O),X=U.mean,ne=U.variance;return[Rf(_,X,ne,z,L,V),X,ne]})}(w,v,N,T,$):function(_,L,z,O,V=.001){return be(()=>{const U=sf(_,O),X=U.mean,ne=U.variance,ae=[];for(const ze of ro(0,_.rank))O.indexOf(ze)!==-1?ae.push(1):ae.push(_.shape[ze]);const Ie=he(X,ae),me=he(ne,ae),we=L==null?null:he(L,ae),$e=z==null?null:he(z,ae);return[Rf(_,Ie,me,$e,we,V),X,ne]})}(w,v,N,T,$)}(s,this.gamma.read(),this.beta.read(),o,this.epsilon),y=(w,v,N)=>{be(()=>{const T=1-N,$=w.read(),_=se(ot($,v),T);w.write(ot($,_))})};return y(this.movingMean,m,this.momentum),y(this.movingVariance,g,this.momentum),d})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Tr(this.betaInitializer),gammaInitializer:Tr(this.gammaInitializer),movingMeanInitializer:Tr(this.movingMeanInitializer),movingVarianceInitializer:Tr(this.movingVarianceInitializer),betaRegularizer:nr(this.betaRegularizer),gammaRegularizer:nr(this.gammaRegularizer),betaConstraint:Yr(this.betaConstraint),gammaConstraint:Yr(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Sb.className="BatchNormalization",st(Sb);class Tb extends bn{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null||e.center,this.scale=e.scale==null||e.scale,this.betaInitializer=xr(e.betaInitializer||"zeros"),this.gammaInitializer=xr(e.gammaInitializer||"ones"),this.betaRegularizer=wr(e.betaRegularizer),this.gammaRegularizer=wr(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=Rn(e)).length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let a=0;a<this.axis.length;++a)this.axis[a]<0&&(this.axis[a]+=t);for(const a of this.axis)if(a<0||a>=t)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==Jl(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const r=this.axis.map(a=>e[a]),s=!0;this.scale?this.gamma=this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){const r=sn(e),s=r.shape,a=s.length;return be(()=>{let{mean:i,variance:o}=sf(r,this.axis,!0);const l=yh(1,a);for(const g of this.axis)l[g]=s[g];const p=g=>g!=null&&g.shape.length!==a?he(g,l):g;let c=this.scale?p(this.gamma.read()):null,h=this.center?p(this.beta.read()):null;const d=[],m=[];for(let g=0;g<a;++g)this.axis.indexOf(g)!==-1?(d.push(s[g]),m.push(1)):(d.push(1),m.push(s[g]));return i=Ua(i,d),o=Ua(o,d),c!=null&&(c=Ua(c,m)),h!=null&&(h=Ua(h,m)),Rf(r,i,o,h,c,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Tr(this.betaInitializer),gammaInitializer:Tr(this.gammaInitializer),betaRegularizer:nr(this.betaRegularizer),gammaRegularizer:nr(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}Tb.className="LayerNormalization",st(Tb);class Eb extends bn{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new ce(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,r;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],r=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new ce(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new ce(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);r=e.padding[1]}this.padding=[t,r]}this.inputSpec=[new Gr({ndim:4})]}computeOutputShape(e){let t,r;return e=Rn(e),this.dataFormat==="channelsFirst"?(t=e[2]!=null&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,r=e[3]!=null&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,r]):(t=e[1]!=null&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,r=e[2]!=null&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,r,e[3]])}call(e,t){return be(()=>{return r=sn(e),s=this.padding,a=this.dataFormat,be(()=>{if(r.rank!==4)throw new ce(`temporalPadding expects input tensor to be 4-D, but received a ${r.rank}-D tensor.`);if(s==null&&(s=[[1,1],[1,1]]),s.length!==2||s[0].length!==2||s[1].length!==2)throw new ce("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(a==null&&(a="channelsLast"),a!=="channelsLast"&&a!=="channelsFirst")throw new ce(`Unknown data format: ${a}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let i;return i=a==="channelsFirst"?[[0,0],[0,0],s[0],s[1]]:[[0,0],s[0],s[1],[0,0]],Ou(r,i)});var r,s,a})}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function Gg(n,e,t,r,s,a){return be(()=>{let i;Lr(s),U2(a),Ha(r),t==null&&(t=[1,1]),r==null&&(r="valid"),s==null&&(s="channelsLast"),a==null&&(a="max"),n=X1(n,s);const o=r==="same"?"same":"valid";return i=a==="max"?rf(n,e,t,o):Xp(n,e,t,o),s==="channelsFirst"&&(i=Qt(i,[0,3,1,2])),i})}function Jv(n,e,t,r,s,a){return be(()=>{let i;Lr(s),U2(a),Ha(r),t==null&&(t=[1,1,1]),r==null&&(r="valid"),s==null&&(s="channelsLast"),a==null&&(a="max"),n=Kv(n,s);const o=r==="same"?"same":"valid";return i=a==="max"?b0(n,e,t,o):Hy(n,e,t,o),s==="channelsFirst"&&(i=Qt(i,[0,4,1,2,3])),i})}Eb.className="ZeroPadding2D",st(Eb);class ek extends bn{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||e.poolSize.length!==1||typeof e.poolSize[0]!="number")throw new ce(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(ls(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else{if(!Array.isArray(e.strides)||e.strides.length!==1||typeof e.strides[0]!="number")throw new ce(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}ls(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Ha(this.padding),this.inputSpec=[new Gr({ndim:3})]}computeOutputShape(e){const t=lo((e=Rn(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return be(()=>{this.invokeCallHook(e,t),e=bf(sn(e),2);const r=this.poolingFunction(sn(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Zl(r,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Cb extends ek{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Gg(e,t,r,s,a,"max")}}Cb.className="MaxPooling1D",st(Cb);class $b extends ek{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Gg(e,t,r,s,a,"avg")}}$b.className="AveragePooling1D",st($b);class tk extends bn{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new ce(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];ls(this.poolSize,"poolSize"),ls(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Lr(this.dataFormat),Ha(this.padding),this.inputSpec=[new Gr({ndim:4})]}computeOutputShape(e){e=Rn(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];
78return t=lo(t,this.poolSize[0],this.padding,this.strides[0]),r=lo(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r]:[e[0],t,r,e[3]]}call(e,t){return be(()=>(this.invokeCallHook(e,t),this.poolingFunction(sn(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ab extends tk{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Gg(e,t,r,s,a,"max")}}Ab.className="MaxPooling2D",st(Ab);class Rb extends tk{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Gg(e,t,r,s,a,"avg")}}Rb.className="AveragePooling2D",st(Rb);class nk extends bn{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new ce(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];ls(this.poolSize,"poolSize"),ls(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Lr(this.dataFormat),Ha(this.padding),this.inputSpec=[new Gr({ndim:5})]}computeOutputShape(e){e=Rn(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=lo(t,this.poolSize[0],this.padding,this.strides[0]),r=lo(r,this.poolSize[1],this.padding,this.strides[1]),s=lo(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r,s]:[e[0],t,r,s,e[4]]}call(e,t){return be(()=>(this.invokeCallHook(e,t),this.poolingFunction(sn(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class _b extends nk{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Jv(e,t,r,s,a,"max")}}_b.className="MaxPooling3D",st(_b);class Db extends nk{constructor(e){super(e)}poolingFunction(e,t,r,s,a){return Lr(a),Ha(s),Jv(e,t,r,s,a,"avg")}}Db.className="AveragePooling3D",st(Db);class rk extends bn{constructor(e){super(e),this.inputSpec=[new Gr({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new gn}}class Fb extends rk{constructor(e){super(e||{})}call(e,t){return be(()=>{const r=sn(e);return Sr(r,1)})}}Fb.className="GlobalAveragePooling1D",st(Fb);class Mb extends rk{constructor(e){super(e||{})}call(e,t){return be(()=>{const r=sn(e);return Va(r,1)})}}Mb.className="GlobalMaxPooling1D",st(Mb);class sk extends bn{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Lr(this.dataFormat),this.inputSpec=[new Gr({ndim:4})]}computeOutputShape(e){return this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new gn}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ob extends sk{call(e,t){return be(()=>{const r=sn(e);return this.dataFormat==="channelsLast"?Sr(r,[1,2]):Sr(r,[2,3])})}}Ob.className="GlobalAveragePooling2D",st(Ob);class Lb extends sk{call(e,t){return be(()=>{const r=sn(e);return this.dataFormat==="channelsLast"?Va(r,[1,2]):Va(r,[2,3])})}}Lb.className="GlobalMaxPooling2D",st(Lb);class ak extends bn{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null&&this.layer.trainable}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,r={}){const s=io(t.layer,r);delete t.layer;const a={layer:s};return Object.assign(a,t),new e(a)}}class zb extends ak{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=Rn(e)).length<3)throw new ce(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=Rn(e))[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),s=e[1];return[r[0],s].concat(r.slice(1))}call(e,t){return be(()=>Zv((r,s)=>[sn(this.layer.call(r,t)),[]],e=sn(e),[],!1,null,null,!1,!0)[1])}}zb.className="TimeDistributed",st(zb);class Pb extends ak{constructor(e){super(e);const t=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=t,this.forwardLayer=io(r),t.goBackwards=t.goBackwards!==!0;const s={};var a;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=io(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?"concat":e.mergeMode,a=this.mergeMode,xh(gE,"BidirectionalMergeMode",a),e.weights)throw new gn("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))}computeOutputShape(e){let t,r,s,a=this.forwardLayer.computeOutputShape(e);
78return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState&&(s=a.slice(1)),t=a[0],this.mergeMode==="concat"?(t[t.length-1]*=2,r=[t]):r=this.mergeMode==null?[t,t.slice()]:[t],this.returnState?this.mergeMode==null?r.concat(s).concat(s.slice()):[t].concat(s).concat(s.slice()):ca(r)}apply(e,t){let r=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const a=Yv(e,r,s,this.numConstants);if(e=a.inputs,r=a.initialState,s=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&s==null)return super.apply(e,t);const i=[],o=[];if(r!=null){const p=r.length;if(p%2>0)throw new ce("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=r,i.push(...r);const c=r.map(h=>new Gr({shape:h.shape}));this.forwardLayer.stateSpec=c.slice(0,p/2),this.backwardLayer.stateSpec=c.slice(p/2),o.push(...c)}if(s!=null)throw new gn("Support for constants in Bidirectional layers is not implemented yet.");const l=i[0]instanceof ao;for(const p of i)if(p instanceof ao!==l)throw new ce("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(l){const p=[e].concat(i),c=this.inputSpec.concat(o),h=this.inputSpec;this.inputSpec=c;const d=super.apply(p,t);return this.inputSpec=h,d}return super.apply(e,t)}call(e,t){return be(()=>{const r=t.initialState;let s,a,i,o;if(r==null)s=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const l=r.slice(0,r.length/2),p=r.slice(r.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:l})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:p}))}return this.returnState&&(Array.isArray(s)&&(i=s.slice(1).concat(a.slice(1))),s=s[0],a=a[0]),this.returnSequences&&(a=Wa(a,1)),this.mergeMode==="concat"?o=h1([s,a]):this.mergeMode==="sum"?o=Ue(s,a):this.mergeMode==="ave"?o=se(.5,Ue(s,a)):this.mergeMode==="mul"?o=se(s,a):this.mergeMode==null&&(o=[s,a]),this.returnState?this.mergeMode==null?o.concat(i):[o].concat(i):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){wh(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),wh(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){let r;if(Array.isArray(t)&&(t=t[0]),r=this.returnSequences?this.mergeMode==null?[t,t]:t:this.mergeMode==null?[null,null]:null,this.returnState){const s=this.forwardLayer.states.map(a=>null);return Array.isArray(r)?r.concat(s).concat(s):[r].concat(s).concat(s)}return r}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const r=io(t.layer);if(delete t.layer,t.numConstants!=null)throw new gn("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=r,new e(s)}}Pb.className="Bidirectional",st(Pb);class Bb extends bn{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return be(()=>((e=sn(e)).dtype!=="float32"&&(e=Vu(e,"float32")),Ue(se(e,this.scale),this.offset)))}}Bb.className="Rescaling",st(Bb);const{resizeBilinear:eC,cropAndResize:tC}=hi;class Vb extends bn{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,r,s,a,i,o,l){return be(()=>{let p,c=!1;const h=[t/i,r/o,(s+t)/i,(a+r)/o],d=[];e.rank===3?(c=!0,p=Hs([e])):p=e;for(let w=0;w<p.shape[0];w++)d.push(h);const m=Bs(d,[d.length,4]),g=fh(0,d.length,1,"int32"),y=tC(p,m,g,[s,a],"nearest");return Vu(c?sn(Ga(y)):y,l)})}upsize(e,t,r,s){return be(()=>Vu(eC(e,[t,r]),s))}call(e,t){return be(()=>{const r=sn(e),s=r.dtype,a=r.shape,i=a[a.length-3],o=a[a.length-2];let l=0;i!==this.height&&(l=Math.floor((i-this.height)/2));let p=0;return o!==this.width&&(p=Math.floor((o-this.width)/2),p===0&&(p=1)),l>=0&&p>=0?this.centerCrop(r,l,p,this.height,this.width,i,o,s):this.upsize(e,this.height,this.width,s)})}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=Rn(e)).length-3,r=e.length-2;return e[t]=this.height,e[r]=this.width,e}}Vb.className="CenterCrop",st(Vb);class Ub extends bn{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return(e=Rn(e))==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return be(()=>{let r;if((e=sn(e)).dtype!=="int32"&&(e=Vu(e,"int32")),t.countWeights!==void 0){if(this.outputMode!=="count")throw new ce(`countWeights is not used when outputMode !== count.
79              Received countWeights=${t.countWeights}`);r=sn(t.countWeights)}const s=Va(e),a=Dd(e),i=Gs(this.numTokens,s).bufferSync().get(0),o=Mu(a,0).bufferSync().get(0);if(!i||!o)throw new ce(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(l,p,c,h){let d=sn(l);if(d.dtype!=="int32"&&(d=Vu(d,"int32")),p==="int")return d;const m=d.shape;
79if(d.rank===0&&(d=ws(d,-1)),p==="oneHot"&&d.shape[d.shape.length-1]!==1&&(d=ws(d,-1)),d.rank>2)throw new ce(`When outputMode is not int, maximum output rank is 2 Received outputMode ${p} and input shape ${m} which would result in output rank ${d.rank}.`);const g=["multiHot","oneHot"].includes(p);let y;if(y=s0(d,h!==void 0&&p==="count"?h:[],c,g),p!=="tfIdf")return y;if(h)return se(y,h);throw new ce("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,r)})}}Ub.className="CategoryEncoding",st(Ub);const ik=new Set(["bilinear","nearest"]);class Wb extends bn{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!ik.has(e.interpolation))throw new ce(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){const t=(e=Rn(e))[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return be(()=>{const r=[this.height,this.width];if(this.interpolation==="bilinear")return hi.resizeBilinear(e,r,!this.cropToAspectRatio);if(this.interpolation==="nearest")return hi.resizeNearestNeighbor(e,r,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...ik]} are supported`)})}}Wb.className="Resizing",st(Wb);class ok{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}}ok.className="RandomSeed";class uk extends bn{constructor(e){super(e),this.randomGenerator=new ok(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}uk.className="BaseRandomLayer";const lk=new Set(["bilinear","nearest"]);class Gb extends uk{constructor(e){super(e);const{factor:t,interpolation:r="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new ce(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new ce(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new ce(`factor cannot have upper bound less than lower bound.
80        Got upper bound: ${this.widthUpper}.
81        Got lower bound: ${this.widthLower}
82      `);if(r){if(!lk.has(r))throw new ce(`Invalid interpolation parameter: ${r} is not implemented`);this.interpolation=r}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=Rn(e))[2];return[this.imgHeight,-1,t]}call(e,t){return be(()=>{const r=sn(e);this.imgHeight=r.shape[r.shape.length-3];const s=r.shape[r.shape.length-2];this.widthFactor=Yl([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let a=this.widthFactor.dataSync()[0]*s;a=Math.round(a);const i=[this.imgHeight,a];switch(this.interpolation){case"bilinear":return hi.resizeBilinear(e,i);case"nearest":return hi.resizeNearestNeighbor(e,i);default:throw new Error(`Interpolation is ${this.interpolation}
83          but only ${[...lk]} are supported`)}})}}function nC(n){return new Gd(n)}function rC(n){return new j1(n)}function sC(n){return new W1(n)}function aC(n){return new G1(n)}function iC(n){return new H1(n)}function oC(n){return new q1(n)}function uC(n){return new K1(n)}function lC(n){return new Ef(n)}function cC(n){return new Xd(n)}function hC(n){return new Y1(n)}function dC(n){return new Yd(n)}function pC(n){return new Z1(n)}function fC(n){return new Q1(n)}function mC(n){return new J1(n)}function gC(n){return new eb(n)}function yC(n){return new tb(n)}function bC(n){return new lb(n)}function xC(n){return new ob(n)}function wC(n){return new Wg(n)}function vC(n){return new ib(n)}function kC(n){return new ub(n)}function NC(n){return new cb(n)}function IC(n){return new hb(n)}function SC(n){return new db(n)}function TC(n){return new fb(n)}function EC(n){return new mb(n)}function CC(n){return new yb(n)}function $C(n){return new wb(n)}function AC(n){return new bb(n)}function RC(n){return new xb(n)}function _C(n){return new gb(n)}function DC(n){return new vb(n)}function FC(n){return new Sb(n)}function MC(n){return new Tb(n)}function OC(n){return new Eb(n)}function Hb(n){return new $b(n)}function LC(n){return Hb(n)}function zC(n){return Hb(n)}function jb(n){return new Rb(n)}function PC(n){return jb(n)}function BC(n){return jb(n)}function Kb(n){return new Db(n)}function VC(n){return Kb(n)}function UC(n){return Kb(n)}function WC(n){return new Fb(n)}function GC(n){return new Ob(n)}function ck(n){return new Mb(n)}function hk(n){return new Lb(n)}function dk(n){return new Cb(n)}function pk(n){return new Ab(n)}function HC(n){return new _b(n)}function jC(n){return new rb(n)}function KC(n){return new Bg(n)}function qC(n){return new sb(n)}function XC(n){return new $f(n)}function YC(n){return new nb(n)}function ZC(n){return new Pg(n)}function QC(n){return new ab(n)}function JC(n){return new Ug(n)}function e$(n){return new co(n)}function t$(n){return new Vg(n)}function n$(n){return new Pb(n)}function r$(n){return new zb(n)}
83Gb.className="RandomWidth",st(Gb);const s$=ck,a$=hk,i$=dk,o$=pk;function u$(n){return new kb(n)}function l$(n){return new Nb(n)}function c$(n){return new Ib(n)}function h$(n){return new pb(n)}function d$(n){return new Bb(n)}function p$(n){return new Vb(n)}function f$(n){return new Wb(n)}function m$(n){return new Ub(n)}function g$(n){return new Gb(n)}function y$(n,e){return R1(n,e)}function b$(n,e){return pv(n,e)}function x$(n,e){return fv(n,e)}function w$(n,e){return _1(n,e)}function v$(n,e){return D1(n,e)}function k$(n,e){return dv(n,e)}function N$(n,e){return function(t,r){return be(()=>{const s=hv(t,r),a=function(o,l){return be(()=>gt(Dt(ci(Ia(o,1),Ia(l,0))),"float32"))}(t,r),i=Ue(s,a);return gt(os(Gs(i,0),Lt(s,i),0),"float32")})}(n,e)}function I$(n,e){return $1(n,e)}function S$(n,e){return Ag(n,e)}function T$(n,e){return jd(n,e)}function E$(n,e){return jd(n,e)}function C$(n,e){return jd(n,e)}function $$(n,e){return kh(n,e)}function A$(n,e){return kh(n,e)}function R$(n,e){return kh(n,e)}function _$(n,e){return function(t,r){return be(()=>{const s=t.sub(r).square().sum(),a=t.sub(t.mean()).square().sum();return Pt(1).sub(s.div(a))})}(n,e)}function D$(n){return new Tf(n)}function F$(n){return U1(e=n),new Tf({l1:e!=null?e.l1:null,l2:0});var e}function M$(n){return U1(e=n),new Tf({l2:e!=null?e.l2:null,l1:0});var e}class fk extends Hd{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Wu))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Hg(n,e){return n<e}function O$(n,e){return n>e}class mk extends fk{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new gn("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Hg:this.mode==="max"||this.monitor.indexOf("acc")!==-1?this.monitorFunc=O$:this.monitorFunc=Hg,this.monitorFunc===Hg&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Hg?1/0:-1/0}async onEpochEnd(e,t){await rc(t);const r=this.getMonitorValue(t);r!=null&&(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});const t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const L$={earlyStopping:function(n){return new mk(n)}};var Ea,gk;xe().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.")}),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"}(Ea||(Ea={})),function(n){(function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))}(gk||(gk={}));const qb={};
83function z$(n,e){const t={tfOpName:n,category:"custom",inputs:[],attrs:[],customExecutor:e};qb[n]=t}function yk(n){return qb[n]}function P$(n){delete qb[n]}function R(n,e,t,r,s){const a=e.inputParams[n];if(a&&a.inputIndexStart!==void 0){const o=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?o+1:a.inputIndexEnd,p=o<0?e.inputNames.length+o:o;if(a.type==="tensor")return ks(e.inputNames[p],t,r,s);if(a.type==="tensors"){const d=e.inputs.slice(o,l);return e.inputNames.slice(o,l).filter((m,g)=>{var y;return((y=d[g])===null||y===void 0?void 0:y.op)!=="NoOp"}).map(m=>ks(m,t,r,s))}const c=ks(e.inputNames[p],t,r,s),h=c.dataSync();return a.type==="number"?h[0]:Ss(c.shape,h)}const i=e.attrParams[n];return i&&i.value}function ks(n,e,t,r){const[s,a]=Ca(n,t);if(r!=null){const o=r.getHashTableHandleByName(s);if(o!=null)return o}const i=t.currentContextIds.find(o=>!!e[jg(s,o)]);return i!==void 0?e[jg(s,i)][a]:void 0}function bk(n,e,t){return e[jg(n,t.currentContextId)]}function Gu(n,e){const[t,r,s]=Ca(n,e);return[jg(t,e&&e.currentContextId),r,s]}function jg(n,e){return e?`${n}-${e}`:n}function Ca(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],i=r.length===3?r[1]:void 0;s=[a,Number(r[r.length-1]),i]}return t&&e.parseNodeNameCache.set(n,s),s}function Kg(n,e,t){let r=R("pad",n,e,t);if(r==="explicit"){r=R("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[2*a],s[a][1]=r[2*a+1];return s}return r}function oc(n){return n.kept?n:va(n)}const B$=[{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}
83]},{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}]}],V$=[{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}
83]},{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}]}],U$
vendor: 7,589 bytes, line 83
83=[{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"}]}]
83,W$=[{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}
83,{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"}]}],G$=[{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}
83]},{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"}]}],H$=[{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}
83]},{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}]}],j$=[{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"}]}],K$=[{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"}]}],q$=[{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"}
83],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"}]}],X$=[{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"}]}],Y$=[{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"}]}],Z$=[{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}
83,{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"}]}],Q$=[{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"}]}],J$=[{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}
83]},{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"}]}],eA=[{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"}]}],tA=[{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"}]}
83,{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"}]}],nA=[{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}]}],rA=[{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"}]}],sA=[{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:[]}];class xk{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[G,Be,Ze,$t,Wt,yn,Jt,fn,cn,Yn,Dn,zn,De,Ye,rt,qe,He,At,Ut].map(t=>t.json));this.opMappers=e.reduce((t,r)=>(t[r.tfOpName]=r,t),{})}transformGraph(e,t={}){const r=e.node,s=[],a=[],i=[],o=r.reduce((y,w)=>(y[w.name]=this.mapNode(w),w.op.startsWith("Placeholder")?s.push(y[w.name]):w.op==="Const"?a.push(y[w.name]):w.input!=null&&w.input.length!==0||i.push(y[w.name]),y),{});let l=[];const p=[];let c={},h={};t!=null&&(c=this.mapSignatureEntries(t.inputs),h=this.mapSignatureEntries(t.outputs));const d=Object.keys(o);d.forEach(y=>{const w=o[y];
83w.inputNames.forEach((v,N)=>{const[T,,$]=Gu(v),_=o[T];if(_.outputs!=null){const L=_.outputs.indexOf($);if(L!==-1){const z=`${T}:${L}`;w.inputNames[N]=z}}w.inputs.push(_),_.children.push(w)})}),Object.keys(h).length===0?d.forEach(y=>{const w=o[y];w.children.length===0&&p.push(w)}):Object.keys(h).forEach(y=>{const[w]=Gu(y),v=o[w];v!=null&&(v.signatureKey=h[y],p.push(v))}),Object.keys(c).length>0?Object.keys(c).forEach(y=>{const[w]=Gu(y),v=o[w];v&&(v.signatureKey=c[y],l.push(v))}):l=s;let m={};e.library!=null&&e.library.function!=null&&(m=e.library.function.reduce((y,w)=>(y[w.signature.name]=this.mapFunction(w),y),{}));const g={nodes:o,inputs:l,outputs:p,weights:a,placeholders:s,signature:t,functions:m};return i.length>0&&(g.initNodes=i),g}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,r)=>(t[e[r].name]=r,t),{})}mapNode(e){const t=yk(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 i=a.type;let o;switch(a.type){case"string":o=Xb(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=Xb(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":o=rx(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=rx(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":o=Zb(e.attr,a.tfName,a.defaultValue||0),o===void 0&&a.tfDeprecatedName&&(o=Zb(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":o=nx(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=nx(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":o=Yb(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=Yb(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":o=ax(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=ax(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":o=tx(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=tx(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":o=sx(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=sx(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":o=Jb(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=Jb(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":o=ex(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=ex(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":o=vk(e.attr,a.tfName,a.defaultValue),o===void 0&&a.tfDeprecatedName&&(o=vk(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:o,type:i},s},{})),r}mapFunction(e){const t=e.nodeDef,r=[];let s={};t!=null&&(s=t.reduce((p,c)=>(p[c.name]=this.mapNode(c),c.op==="Const"&&r.push(p[c.name]),p),{}));const a=[],i=[];e.signature.inputArg.forEach(p=>{const[c]=Gu(p.name),h={name:c,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Qb(p.type),type:"dtype"}},children:[]};h.signatureKey=p.name,a.push(h),s[c]=h}),Object.keys(s).forEach(p=>{const c=s[p];c.inputNames.forEach((h,d)=>{const[m,,g]=Gu(h),y=s[m];if(y.outputs!=null){const w=y.outputs.indexOf(g);if(w!==-1){const v=`${m}:${w}`;c.inputNames[d]=v}}c.inputs.push(y),y.children.push(c)})});const o=e.ret;e.signature.outputArg.forEach(p=>{const[c,h]=Gu(o[p.name]),d=s[c];d!=null&&(d.defaultOutput=h,i.push(d))});const l=this.mapArgsToSignature(e);return{nodes:s,inputs:a,outputs:i,weights:r,placeholders:[],signature:l}}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 wk(n,e){const t=Array.isArray(n)?String.fromCharCode.apply(null,n):function(r){const s=xe().global;if(s.atob!==void 0)return s.atob(r);if(typeof Buffer<"u")return new Buffer(r,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(n);return e?t:t.toLowerCase()}function Xb(n,e,t,r=!1){const s=n[e];return s!=null?wk(s.s,r):t}function Yb(n,e,t){const r=n[e];return r?r.b:t}function Zb(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 Qb(n){switch(typeof n=="string"&&(n=Ea[n]),n){case Ea.DT_FLOAT:case Ea.DT_HALF:return"float32";case Ea.DT_INT32:case Ea.DT_INT64:case Ea.DT_INT8:case Ea.DT_UINT8:return"int32";case Ea.DT_BOOL:return"bool";case Ea.DT_DOUBLE:return"float32";case Ea.DT_STRING:return"string";case Ea.DT_COMPLEX64:case Ea.DT_COMPLEX128:return"complex64";default:return null}}function vk(n,e,t){const r=n[e];return r&&r.func?r.func.name:t}function Jb(n,e,t){const r=n[e];return r&&r.type?Qb(r.type):t}function ex(n,e,t){const r=n[e];return r&&r.list&&r.list.type?r.list.type.map(s=>Qb(s)):t}function kk(n){if(!n.unknownRank)return n.dim!=null?n.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function tx(n,e,t){const r=n[e];return r&&r.shape?kk(r.shape):t}function nx(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 rx(n,e,t,r=!1){const s=n[e];return s&&s.list&&s.list.s?s.list.s.map(a=>wk(a,r)):t}function sx(n,e,t){const r=n[e];return r&&r.list&&r.list.shape?r.list.shape.map(s=>kk(s)):t}function ax(n,e,t){const r=n[e];return r&&r.list&&r.list.b?r.list.b:t}class aA{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 ks(e,this.tensorMap,this.context)}getAttr(e,t){const r=this.node.rawAttrs[e];if(r.tensor!=null)return ks(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return Zb(this.node.rawAttrs,e,t);if(r.s!=null)return Xb(this.node.rawAttrs,e,t);if(r.b!=null)return Yb(this.node.rawAttrs,e,t);if(r.shape!=null)return tx(this.node.rawAttrs,e,t);if(r.type!=null)return Jb(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return nx(this.node.rawAttrs,e,t);if(r.list.s!=null)return rx(this.node.rawAttrs,e,t);if(r.list.shape!=null)return sx(this.node.rawAttrs,e,t);if(r.list.b!=null)return ax(this.node.rawAttrs,e,t);if(r.list.type!=null)return ex(this.node.rawAttrs,e,t)}return t}}function mi(n,e,t=""){if(typeof n!="number"&&typeof e!="number"){A(n.length===e.length,()=>t+` Shapes ${n} and ${e} must match`);for(let r=0;r<n.length;r++){const s=n[r],a=e[r];A(s<0||a<0||s===a,()=>t+` Shapes ${n} and ${e} must match`)}}}function Nk(n){return typeof n!="number"&&!n.some(e=>e<0)}function _f(n,e,t){let r=ix(n,t);const s=!Nk(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=ix(a.shape,r)}),!Nk(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function ix(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<n.length;++r){const s=n[r],a=e[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${n} vs. ${e}`);t[r]=s>=0?s:a}return t}class iA{constructor(e,t,r,s,a,i,o){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=s,this.identicalElementShapes=a,this.dynamicSize=i,this.clearAfterRead=o,this.tensors=[],this.closed_
83=!1,this.idTensor=Pt(0),_r(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},
84          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),mi(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,_r(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.size();s++)e.push(s)}if(e.length===0)return Bs([],[0].concat(this.elementShape));const r=this.readMany(e);return mi(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),Hs(r,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return Bs([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const r=this.readMany(t);return mi(this.elementShape,r[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${r[0].shape})`),Fr(r,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const r=Math.max(...e);if(!this.dynamicSize&&r>=this.maxSize)throw new Error(`Max index must be < array size (${r}  vs. ${this.maxSize})`);this.writeMany(e,Ga(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
85          tensor.shape[0], but sum of lengths is
86        ${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,i=[];be(()=>{t=he(t,[1,r,a]);for(let l=0;l<e.length;++l){const p=[0,l===0?0:s[l-1],0],c=[1,e[l],a];i[l]=he(Tn(t,p,c),this.elementShape)}return i});const o=[];for(let l=0;l<e.length;l++)o[l]=l;this.writeMany(o,i)}}class Sh{get id(){return this.idTensor.id}constructor(e,t,r,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=r,e?.forEach(a=>{if(r!==a.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${a.dtype}`);mi(t,a.shape,"TensorList shape mismatch: "),_r(a)}),this.idTensor=Pt(0),this.maxNumElements=s,_r(this.idTensor)}copy(){return new Sh([...this.tensors],this.elementShape,this.elementDtype)}
86clearAndClose(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.`);mi(e,this.elementShape,"TensorList shape mismatch: ");const s=_f(this.elementShape,this.tensors,e);return be(()=>{const a=this.tensors.map(i=>he(i,s));return Hs(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=_f(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,mi(s.shape,e,"TensorList shape mismatch: "),he(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(mi(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");_r(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 Sh([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let r=0;r<Math.min(this.tensors.length,e);++r)t.tensors[r]=this.tensors[r];return t}getItem(e,t,r){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);if(e<0||e>this.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.`);mi(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=_f(this.elementShape,this.tensors,t);return he(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.`);mi(this.elementShape,t.shape,"TensorList shape mismatch: "),_r(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}`);mi(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=_f(this.elementShape,this.tensors,r);return e.length===0?Bs([],[0].concat(s)):be(()=>{const a=e.map(i=>he(this.tensors[i],s));return Hs(a,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);mi(this.elementShape,t,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,t);return this.size()===0?Bs([],[0].concat(r)):be(()=>{const s=this.tensors.map(a=>he(a,r));return Fr(s,0)})}}function Ik(n,e,t){const[r,s]=R("fusedOps",n,e,t),a=r==="biasadd",i=!a,o=s==="prelu",l=r==="fusedbatchnorm",p=R("numArgs",n,e,t);if(a){if(o&&p!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&p!==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 c=R("strides",n,e,t),h=Kg(n,e,t),d=R("dataFormat",n,e,t).toUpperCase(),m=R("dilations",n,e,t);let[g,y]=R("args",n,e,t);return i&&(y=g,g=void 0),{stride:c,pad:h,dataFormat:d,dilations:m,biasArg:g,preluArg:y,activationFunc:s,leakyreluAlpha:R("leakyreluAlpha",n,e,t)}}function ox(n,e,t){return{boxes:R("boxes",n,e,t),scores:R("scores",n,e,t),maxOutputSize:R("maxOutputSize",n,e,t),iouThreshold:R("iouThreshold",n,e,t),scoreThreshold:R("scoreThreshold",n,e,t),softNmsSigma:R("softNmsSigma",n,e,t)}}class oA{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Pt(0),this.tensorMap=new Map,_r(this.handle)}
86clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Pt(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(),be(()=>{const s=Ga(t),a=r.length,i=s.length;A(a===i,()=>`The number of elements doesn't match, keys has ${a} elements, the values has ${i} elements.`);for(let o=0;o<a;o++){const l=r[o],p=s[o];_r(p),this.tensorMap.set(l,p)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);const r=await e.data();return be(()=>{const s=[];for(let a=0;a<r.length;a++){const i=r[a],o=this.findWithDefault(i,t);s.push(o)}return Hs(s)})}findWithDefault(e,t){const r=this.tensorMap.get(e);return r??t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function Sk(n,e,t,r,s=be){const a=((i,o,l)=>{switch(i.category){case"arithmetic":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"BiasAdd":case"AddV2":case"Add":return[m.add(R("a",c,h,d),R("b",c,h,d))];case"AddN":return[m.addN(R("tensors",c,h,d))];case"FloorMod":case"Mod":return[m.mod(R("a",c,h,d),R("b",c,h,d))];case"Mul":return[m.mul(R("a",c,h,d),R("b",c,h,d))];case"RealDiv":case"Div":return[m.div(R("a",c,h,d),R("b",c,h,d))];case"DivNoNan":return[m.divNoNan(R("a",c,h,d),R("b",c,h,d))];case"FloorDiv":return[m.floorDiv(R("a",c,h,d),R("b",c,h,d))];case"Sub":return[m.sub(R("a",c,h,d),R("b",c,h,d))];case"Minimum":return[m.minimum(R("a",c,h,d),R("b",c,h,d))];case"Maximum":return[m.maximum(R("a",c,h,d),R("b",c,h,d))];case"Pow":return[m.pow(R("a",c,h,d),R("b",c,h,d))];case"SquaredDifference":return[m.squaredDifference(R("a",c,h,d),R("b",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"basic_math":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Abs":case"ComplexAbs":return[m.abs(R("x",c,h,d))];case"Acos":return[m.acos(R("x",c,h,d))];case"Acosh":return[m.acosh(R("x",c,h,d))];case"Asin":return[m.asin(R("x",c,h,d))];case"Asinh":return[m.asinh(R("x",c,h,d))];case"Atan":return[m.atan(R("x",c,h,d))];case"Atan2":return[m.atan2(R("x",c,h,d),R("y",c,h,d))];case"Atanh":return[m.atanh(R("x",c,h,d))];case"Ceil":return[m.ceil(R("x",c,h,d))];case"Complex":return[m.complex(R("real",c,h,d),R("imag",c,h,d))];case"Cos":return[m.cos(R("x",c,h,d))];case"Cosh":return[m.cosh(R("x",c,h,d))];case"Elu":return[m.elu(R("x",c,h,d))];case"Erf":return[m.erf(R("x",c,h,d))];case"Exp":return[m.exp(R("x",c,h,d))];case"Expm1":return[m.expm1(R("x",c,h,d))];case"Floor":return[m.floor(R("x",c,h,d))];case"Log":return[m.log(R("x",c,h,d))];case"Log1p":return[m.log1p(R("x",c,h,d))];case"Imag":return[m.imag(R("x",c,h,d))];case"Neg":return[m.neg(R("x",c,h,d))];case"Reciprocal":return[m.reciprocal(R("x",c,h,d))];case"Real":return[m.real(R("x",c,h,d))];case"Relu":return[m.relu(R("x",c,h,d))];case"Round":return[m.round(R("x",c,h,d))];case"Selu":return[m.selu(R("x",c,h,d))];case"Sigmoid":return[m.sigmoid(R("x",c,h,d))];case"Sin":return[m.sin(R("x",c,h,d))];case"Sign":return[m.sign(R("x",c,h,d))];case"Sinh":return[m.sinh(R("x",c,h,d))];case"Softplus":return[m.softplus(R("x",c,h,d))];case"Sqrt":return[m.sqrt(R("x",c,h,d))];case"Square":return[m.square(R("x",c,h,d))];case"Tanh":return[m.tanh(R("x",c,h,d))];case"Tan":return[m.tan(R("x",c,h,d))];case"ClipByValue":return[m.clipByValue(R("x",c,h,d),R("clipValueMin",c,h,d),R("clipValueMax",c,h,d))];case"Relu6":return[m.relu6(R("x",c,h,d))];case"Rsqrt":return[m.rsqrt(ks(c.inputNames[0],h,d))];case"LeakyRelu":return[m.leakyRelu(R("x",c,h,d),R("alpha",c,h,d))];case"Prelu":return[m.prelu(R("x",c,h,d),R("alpha",c,h,d))];case"IsNan":return[m.isNaN(ks(c.inputNames[0],h,d))];case"IsInf":return[m.isInf(ks(c.inputNames[0],h,d))];case"IsFinite":return[m.isFinite(ks(c.inputNames[0],h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"control":return(async(c,h,d)=>
86{switch(c.op){case"If":case"StatelessIf":{const m=R("thenBranch",c,h,d),g=R("elseBranch",c,h,d),y=R("cond",c,h,d),w=R("args",c,h,d);return(await y.data())[0]?d.functionMap[m].executeFunctionAsync(w,d.tensorArrayMap,d.tensorListMap):d.functionMap[g].executeFunctionAsync(w,d.tensorArrayMap,d.tensorListMap)}case"While":case"StatelessWhile":{const m=R("body",c,h,d),g=R("cond",c,h,d),y=R("args",c,h,d),w=await d.functionMap[g].executeFunctionAsync(y,d.tensorArrayMap,d.tensorListMap),v=y.map($=>$.id);let N=await w[0].data();w.forEach($=>{$.kept||v.indexOf($.id)!==-1||$.dispose()});let T=y;for(;N[0];){const $=T;T=await d.functionMap[m].executeFunctionAsync(T,d.tensorArrayMap,d.tensorListMap);const _=T.map(z=>z.id);$.forEach(z=>{z.kept||v.indexOf(z.id)!==-1||_.indexOf(z.id)!==-1||z.dispose()});const L=await d.functionMap[g].executeFunctionAsync(T,d.tensorArrayMap,d.tensorListMap);N=await L[0].data(),L.forEach(z=>{z.kept||v.indexOf(z.id)!==-1||_.indexOf(z.id)!==-1||z.dispose()})}return T}case"LoopCond":return[oc(R("pred",c,h,d))];case"Switch":{const m=R("pred",c,h,d);let g=R("data",c,h,d);return g.kept||(g=oc(g)),(await m.data())[0]?[void 0,g]:[g,void 0]}case"Merge":{const m=c.inputNames.find(g=>ks(g,h,d)!==void 0);return m?[oc(ks(m,h,d))]:void 0}case"Enter":{const m=R("frameName",c,h,d),g=R("tensor",c,h,d);return d.enterFrame(m),[oc(g)]}case"Exit":{const m=R("tensor",c,h,d);return d.exitFrame(),[oc(m)]}case"NextIteration":{const m=R("tensor",c,h,d);return d.nextIteration(),[oc(m)]}case"TensorArrayV3":{const m=R("size",c,h,d),g=R("dtype",c,h,d),y=R("elementShape",c,h,d),w=R("dynamicSize",c,h,d),v=R("clearAfterRead",c,h,d),N=R("identicalElementShapes",c,h,d),T=R("name",c,h,d),$=new iA(T,g,m,y,N,w,v);return d.addTensorArray($),[$.idTensor,Pt(1)]}case"TensorArrayWriteV3":{const m=R("tensorArrayId",c,h,d),g=R("index",c,h,d),y=R("tensor",c,h,d),w=d.getTensorArray(m.id);return w.write(g,y),[w.idTensor]}case"TensorArrayReadV3":{const m=R("tensorArrayId",c,h,d),g=R("index",c,h,d);return[d.getTensorArray(m.id).read(g)]}case"TensorArrayGatherV3":{const m=R("tensorArrayId",c,h,d),g=R("indices",c,h,d),y=R("dtype",c,h,d);return[d.getTensorArray(m.id).gather(g,y)]}case"TensorArrayScatterV3":{const m=R("tensorArrayId",c,h,d),g=R("indices",c,h,d),y=R("tensor",c,h,d),w=d.getTensorArray(m.id);return w.scatter(g,y),[w.idTensor]}case"TensorArrayConcatV3":{const m=R("tensorArrayId",c,h,d),g=d.getTensorArray(m.id),y=R("dtype",c,h,d);return[g.concat(y)]}case"TensorArraySplitV3":{const m=R("tensorArrayId",c,h,d),g=R("tensor",c,h,d),y=R("lengths",c,h,d),w=d.getTensorArray(m.id);return w.split(y,g),[w.idTensor]}case"TensorArraySizeV3":{const m=R("tensorArrayId",c,h,d);return[Pt(d.getTensorArray(m.id).size(),"int32")]}case"TensorArrayCloseV3":{const m=R("tensorArrayId",c,h,d),g=d.getTensorArray(m.id);return g.clearAndClose(),[g.idTensor]}case"TensorListSetItem":{const m=R("tensorListId",c,h,d),g=R("index",c,h,d),y=R("tensor",c,h,d),w=d.getTensorList(m.id);return w.setItem(g,y),[w.idTensor]}case"TensorListGetItem":{const m=R("tensorListId",c,h,d),g=R("index",c,h,d),y=R("elementShape",c,h,d),w=R("elementDType",c,h,d);return[d.getTensorList(m.id).getItem(g,y,w)]}case"TensorListScatterV2":case"TensorListScatter":{const m=R("indices",c,h,d),g=function(y,w,v,N){if(w.length!==y.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${w.length} vs. ${y.shape[0]}`);const T=Math.max(...w);if(N!=null&&N!==-1&&T>=N)throw new Error(`Max index must be < array size (${T}  vs. ${N})`);const $=new Sh([],v,y.dtype,N),_=Ga(y,0);return w.forEach((L,z)=>{$.setItem(L,_[z])}),$}(R("tensor",c,h,d),m,R("elementShape",c,h,d),R("numElements",c,h,d));return d.addTensorList(g),[g.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const m=R("elementShape",c,h,d),g=R("elementDType",c,h,d);let y;y=c.op==="TensorListReserve"?"numElements":"maxNumElements";const w=R(y,c,h,d),v=function(N,T,$,_){return new Sh([],N,T,_)}(m,g,0,c.op==="TensorListReserve"?-1:w);return d.addTensorList(v),[v.idTensor]}case"TensorListGather":{const m=R("tensorListId",c,h,d),g=R("indices",c,h,d),y=R("elementShape",c,h,d),w=R("elementDType",c,h,d);return[d.getTensorList(m.id).gather(g,w,y)]}case"TensorListStack":{const m=R("tensorListId",c,h,d),g=R("elementShape",c,h,d),y=R("elementDType",c,h,d),w=R("numElements",c,h,d);return[d.getTensorList(m.id).stack(g,y,w)]}case"TensorListFromTensor":{const m=function(g,y,w){const v=g.dtype;if(g.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${g.shape}`);if(g.dtype!==w)throw new Error(`Invalid data types; op elements ${g.dtype}, but list elements ${w}`);mi(g.shape.slice(1),y,"TensorList shape mismatch: ");const N=Ga(g);return new Sh(N,y,v)}(R("tensor",c,h,d),R("elementShape",c,h,d),R("elementDType",c,h,d));return d.addTensorList(m),[m.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const m=R("tensorListId",c,h,d),g=d.getTensorList(m.id),y=R("dtype",c,h,d),w=R("elementShape",c,h,d);return[g.concat(y,w)]}case"TensorListPushBack":{const m=R("tensorListId",c,h,d),g=R("tensor",c,h,d),y=d.getTensorList(m.id);return y.pushBack(g),[y.idTensor]}case"TensorListPopBack":{const m=R("tensorListId",c,h,d),g=R("elementShape",c,h,d),y=R("elementDType",c,h,d);return[d.getTensorList(m.id).popBack(g,y)]}case"TensorListSplit":{const m=R("tensor",c,h,d),g=R("elementShape",c,h,d),y=function(w,v,N){let T=0;const $=v.map(V=>(T+=V,T));if(T!==w.shape[0])throw new Error(`Expected sum of lengths to be equal to
87          tensor.shape[0], but sum of lengths is
88        ${T}, and tensor's shape is: ${w.shape}`);const _=ix(w.shape.slice(1),N),L=T===0?0:w.size/T,z=be(()=>{const V=[];w=he(w,[1,T,L]);for(let U=0;U<v.length;++U){const X=[0,U===0?0:$[U-1],0],ne=[1,v[U],L];V[U]=he(Tn(w,X,ne),_)}return w.dispose(),V}),O=new Sh([],N,w.dtype,v.length);for(let V=0;V<z.length;V++)O.setItem(V,z[V]);return O}(m,R("lengths",c,h,d),g);return d.addTensorList(y),[y.idTensor]}case"TensorListLength":{const m=R("tensorListId",c,h,d);return[Pt(d.getTensorList(m.id).size(),"int32")]}case"TensorListResize":{const m=R("tensorListId",c,h,d),g=R("size",c,h,d),y=d.getTensorList(m.id).resize(g);return d.addTensorList(y),[y.idTensor]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l);case"convolution":return s(()=>((c,h,d,m=at)=>
vendor: 8,592 bytes, line 88
88{switch(c.op){case"Conv1D":{const g=R("stride",c,h,d),y=R("pad",c,h,d),w=R("dataFormat",c,h,d).toUpperCase(),v=R("dilation",c,h,d);return[m.conv1d(R("x",c,h,d),R("filter",c,h,d),g,y,w,v)]}case"Conv2D":{const g=R("strides",c,h,d),y=Kg(c,h,d),w=R("dataFormat",c,h,d).toUpperCase(),v=R("dilations",c,h,d);return[m.conv2d(R("x",c,h,d),R("filter",c,h,d),[g[1],g[2]],y,w,[v[1],v[2]])]}case"_FusedConv2D":{const{stride:g,pad:y,dataFormat:w,dilations:v,biasArg:N,preluArg:T,activationFunc:$,leakyreluAlpha:_}=Ik(c,h,d);return[m.fused.conv2d({x:R("x",c,h,d),filter:R("filter",c,h,d),strides:[g[1],g[2]],pad:y,dataFormat:w,dilations:[v[1],v[2]],bias:N,activation:$,preluActivationWeights:T,leakyreluAlpha:_})]}case"FusedDepthwiseConv2dNative":{const{stride:g,pad:y,dataFormat:w,dilations:v,biasArg:N,preluArg:T,activationFunc:$,leakyreluAlpha:_}=Ik(c,h,d);return[m.fused.depthwiseConv2d({x:R("x",c,h,d),filter:R("filter",c,h,d),strides:[g[1],g[2]],pad:y,dataFormat:w,dilations:[v[1],v[2]],bias:N,activation:$,preluActivationWeights:T,leakyreluAlpha:_})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const g=R("outputShape",c,h,d),y=R("strides",c,h,d),w=Kg(c,h,d);return[m.conv2dTranspose(R("x",c,h,d),R("filter",c,h,d),g,[y[1],y[2]],w)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const g=R("strides",c,h,d),y=Kg(c,h,d),w=R("dilations",c,h,d),v=R("dataFormat",c,h,d).toUpperCase();return[m.depthwiseConv2d(R("input",c,h,d),R("filter",c,h,d),[g[1],g[2]],y,v,[w[1],w[2]])]}case"Conv3D":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("dataFormat",c,h,d).toUpperCase(),v=R("dilations",c,h,d);return[m.conv3d(R("x",c,h,d),R("filter",c,h,d),[g[1],g[2],g[3]],y,w,[v[1],v[2],v[3]])]}case"AvgPool":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("kernelSize",c,h,d);return[m.avgPool(R("x",c,h,d),[w[1],w[2]],[g[1],g[2]],y)]}case"MaxPool":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("kernelSize",c,h,d);return[m.maxPool(R("x",c,h,d),[w[1],w[2]],[g[1],g[2]],y)]}case"MaxPoolWithArgmax":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("kernelSize",c,h,d),v=R("includeBatchInIndex",c,h,d),{result:N,indexes:T}=m.maxPoolWithArgmax(R("x",c,h,d),[w[1],w[2]],[g[1],g[2]],y,v);return[N,T]}case"AvgPool3D":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("kernelSize",c,h,d);return[m.avgPool3d(R("x",c,h,d),[w[1],w[2],w[3]],[g[1],g[2],g[3]],y)]}case"MaxPool3D":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("kernelSize",c,h,d);return[m.maxPool3d(R("x",c,h,d),[w[1],w[2],w[3]],[g[1],g[2],g[3]],y)]}case"Dilation2D":{const g=R("strides",c,h,d),y=R("pad",c,h,d),w=R("dilations",c,h,d),v=g[1],N=g[2],T=w[1],$=w[2];return[m.dilation2d(R("x",c,h,d),R("filter",c,h,d),[v,N],y,[T,$],"NHWC")]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"creation":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Fill":{const g=R("shape",c,h,d),y=R("dtype",c,h,d),w=R("value",c,h,d);return[m.fill(g,w,y)]}case"LinSpace":{const g=R("start",c,h,d),y=R("stop",c,h,d),w=R("num",c,h,d);return[m.linspace(g,y,w)]}case"Multinomial":{const g=R("logits",c,h,d),y=R("numSamples",c,h,d),w=R("seed",c,h,d);return[m.multinomial(g,y,w)]}case"OneHot":{const g=R("indices",c,h,d),y=R("depth",c,h,d),w=R("onValue",c,h,d),v=R("offValue",c,h,d),N=R("dtype",c,h,d);return[m.oneHot(g,y,w,v,N)]}case"Ones":return[m.ones(R("shape",c,h,d),R("dtype",c,h,d))];case"OnesLike":return[m.onesLike(R("x",c,h,d))];case"RandomStandardNormal":return[m.randomStandardNormal(R("shape",c,h,d),R("dtype",c,h,d),R("seed",c,h,d))];case"RandomUniform":return[m.randomUniform(R("shape",c,h,d),R("minval",c,h,d),R("maxval",c,h,d),R("dtype",c,h,d))];case"RandomUniformInt":return[m.randomUniformInt(R("shape",c,h,d),R("minval",c,h,d),R("maxval",c,h,d),R("seed",c,h,d))];case"Range":{const g=R("start",c,h,d),y=R("stop",c,h,d),w=R("step",c,h,d);return[m.range(g,y,w,R("dtype",c,h,d))]}case"TruncatedNormal":{const g=R("shape",c,h,d),y=R("mean",c,h,d),w=R("stdDev",c,h,d),v=R("seed",c,h,d);return[m.truncatedNormal(g,y,w,R("dtype",c,h,d),v)]}case"Zeros":return[m.zeros(R("shape",c,h,d),R("dtype",c,h,d))];case"ZerosLike":return[m.zerosLike(R("x",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"dynamic":return(async(c,h,d,m,g=at)=>{switch(c.op){case"NonMaxSuppressionV5":{const{boxes:y,scores:w,maxOutputSize:v,iouThreshold:N,scoreThreshold:T,softNmsSigma:$}=ox(c,h,d),_=await g.image.nonMaxSuppressionWithScoreAsync(y,w,v,N,T,$);return[_.selectedIndices,_.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:y,scores:w,maxOutputSize:v,iouThreshold:N,scoreThreshold:T}=ox(c,h,d),$=R("padToMaxOutputSize",c,h,d),_=await g.image.nonMaxSuppressionPaddedAsync(y,w,v,N,T,$);return[_.selectedIndices,_.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:y,scores:w,maxOutputSize:v,iouThreshold:N,scoreThreshold:T}=ox(c,h,d);return[await g.image.nonMaxSuppressionAsync(y,w,v,N,T)]}case"Where":{const y=g.cast(R("condition",c,h,d),"bool"),w=[await g.whereAsync(y)];return y.dispose(),w}case"ListDiff":return g.setdiff1dAsync(R("x",c,h,d),R("y",c,h,d));default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l);case"evaluation":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"LowerBound":{const g=R("sortedSequence",c,h,d),y=R("values",c,h,d);return[m.lowerBound(g,y)]}case"TopKV2":{const g=R("x",c,h,d),y=R("k",c,h,d),w=R("sorted",c,h,d),v=m.topk(g,y,w);return[v.values,v.indices]}case"UpperBound":{const g=R("sortedSequence",c,h,d),y=R("values",c,h,d);return[m.upperBound(g,y)]}case"Unique":{const g=R("x",c,h,d),y=m.unique(g);return[y.values,y.indices]}case"UniqueV2":{const g=R("x",c,h,d),y=R("axis",c,h,d),w=m.unique(g,y);return[w.values,w.indices]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"image":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"ResizeBilinear":{const g=R("images",c,h,d),y=R("size",c,h,d),w=R("alignCorners",c,h,d),v=R("halfPixelCenters",c,h,d);return[m.image.resizeBilinear(g,[y[0],y[1]],w,v)]}case"ResizeNearestNeighbor":{const g=R("images",c,h,d),y=R("size",c,h,d),w=R("alignCorners",c,h,d),v=R("halfPixelCenters",c,h,d);return[m.image.resizeNearestNeighbor(g,[y[0],y[1]],w,v)]}case"CropAndResize":{const g=R("image",c,h,d),y=R("boxes",c,h,d),w=R("boxInd",c,h,d),v=R("cropSize",c,h,d),N=R("method",c,h,d),T=R("extrapolationValue",c,h,d);return[m.image.cropAndResize(g,y,w,v,N,T)]}case"ImageProjectiveTransformV3":{const g=R("images",c,h,d),y=R("transforms",c,h,d),w=R("outputShape",c,h,d),v=R("fillValue",c,h,d),N=R("interpolation",c,h,d),T=R("fillMode",c,h,d);return[m.image.transform(g,y,N.toLowerCase(),T.toLowerCase(),v,w)]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"graph":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Const":return h[c.name];case"PlaceholderWithDefault":const g=R("default",c,h,d);return[ks(c.name,h,d)||g];case"Placeholder":return[ks(c.name,h,d)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[oc(R("x",c,h,d))];case"IdentityN":return R("x",c,h,d).map(T=>oc(T));case"Shape":return[m.tensor1d(R("x",c,h,d).shape,"int32")];case"ShapeN":return R("x",c,h,d).map(T=>m.tensor1d(T.shape));case"Size":return[m.scalar(R("x",c,h,d).size,"int32")];case"Rank":return[m.scalar(R("x",c,h,d).rank,"int32")];case"NoOp":return[m.scalar(1)];case"Print":const y=R("x",c,h,d),w=R("data",c,h,d),v=R("message",c,h,d),N=R("summarize",c,h,d);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(v);for(let T=0;T<w.length;T++)console.log(Array.prototype.slice.call(w[T].dataSync()).slice(0,N));return[y];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"logical":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Equal":return[m.equal(R("a",c,h,d),R("b",c,h,d))];case"NotEqual":return[m.notEqual(R("a",c,h,d),R("b",c,h,d))];case"Greater":return[m.greater(R("a",c,h,d),R("b",c,h,d))];case"GreaterEqual":return[m.greaterEqual(R("a",c,h,d),R("b",c,h,d))];case"Less":return[m.less(R("a",c,h,d),R("b",c,h,d))];case"LessEqual":return[m.lessEqual(R("a",c,h,d),R("b",c,h,d))];case"LogicalAnd":return[m.logicalAnd(R("a",c,h,d),R("b",c,h,d))];case"LogicalNot":return[m.logicalNot(R("a",c,h,d))];case"LogicalOr":return[m.logicalOr(R("a",c,h,d),R("b",c,h,d))];case"Select":case"SelectV2":return[m.where(R("condition",c,h,d),R("a",c,h,d),R("b",c,h,d))];case"BitwiseAnd":return[m.bitwiseAnd(R("a",c,h,d),R("b",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"matrices":return s(()=>((c,h,d,m=at)=>
88{switch(c.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[m.matMul(R("a",c,h,d),R("b",c,h,d),R("transposeA",c,h,d),R("transposeB",c,h,d))];case"Einsum":return[m.einsum(R("equation",c,h,d),...R("tensors",c,h,d))];case"Transpose":return[m.transpose(R("x",c,h,d),R("perm",c,h,d))];case"_FusedMatMul":const[g,y]=R("fusedOps",c,h,d),w=g==="biasadd",v=y==="prelu",N=R("numArgs",c,h,d),T=R("leakyreluAlpha",c,h,d);if(w){if(v&&N!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!v&&N!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[$,_]=R("args",c,h,d);return[m.fused.matMul({a:R("a",c,h,d),b:R("b",c,h,d),transposeA:R("transposeA",c,h,d),transposeB:R("transposeB",c,h,d),bias:$,activation:y,preluActivationWeights:_,leakyreluAlpha:T})];case"MatrixBandPart":return[m.linalg.bandPart(R("a",c,h,d),R("numLower",c,h,d),R("numUpper",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"normalization":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"EuclideanNorm":return[m.euclideanNorm(R("x",c,h,d),R("axis",c,h,d),R("keepDims",c,h,d))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[m.batchNorm(R("x",c,h,d),R("mean",c,h,d),R("variance",c,h,d),R("offset",c,h,d),R("scale",c,h,d),R("epsilon",c,h,d))];case"LRN":return[m.localResponseNormalization(R("x",c,h,d),R("radius",c,h,d),R("bias",c,h,d),R("alpha",c,h,d),R("beta",c,h,d))];case"Softmax":return[m.softmax(R("x",c,h,d))];case"LogSoftmax":return[m.logSoftmax(R("x",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"ragged":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"RaggedGather":{const{outputNestedSplits:g,outputDenseValues:y}=m.raggedGather(R("paramsNestedSplits",c,h,d),R("paramsDenseValues",c,h,d),R("indices",c,h,d),R("outputRaggedRank",c,h,d));return g.concat(y)}case"RaggedRange":{const{rtNestedSplits:g,rtDenseValues:y}=m.raggedRange(R("starts",c,h,d),R("limits",c,h,d),R("splits",c,h,d));return[g,y]}case"RaggedTensorToTensor":return[m.raggedTensorToTensor(R("shape",c,h,d),R("values",c,h,d),R("defaultValue",c,h,d),R("rowPartitionTensors",c,h,d),R("rowPartitionTypes",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"reduction":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Max":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.max(R("x",c,h,d),v,N)]}case"Mean":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.mean(R("x",c,h,d),v,N)]}case"Min":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.min(R("x",c,h,d),v,N)]}case"Sum":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.sum(R("x",c,h,d),v,N)]}case"All":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.all(R("x",c,h,d),v,N)]}case"Any":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.any(R("x",c,h,d),v,N)]}case"ArgMax":{const v=R("axis",c,h,d);return[m.argMax(R("x",c,h,d),v)]}case"ArgMin":{const v=R("axis",c,h,d);return[m.argMin(R("x",c,h,d),v)]}case"Prod":{const v=R("axis",c,h,d),N=R("keepDims",c,h,d);return[m.prod(R("x",c,h,d),v,N)]}case"Cumprod":{const v=R("axis",c,h,d),N=R("exclusive",c,h,d),T=R("reverse",c,h,d);return[m.cumprod(R("x",c,h,d),v,N,T)]}case"Cumsum":{const v=R("axis",c,h,d),N=R("exclusive",c,h,d),T=R("reverse",c,h,d);return[m.cumsum(R("x",c,h,d),v,N,T)]}case"Bincount":const g=R("x",c,h,d),y=R("weights",c,h,d),w=R("size",c,h,d);return[m.bincount(g,y,w)];case"DenseBincount":{const v=R("x",c,h,d),N=R("weights",c,h,d),T=R("size",c,h,d),$=R("binaryOutput",c,h,d);return[m.denseBincount(v,N,T,$)]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"slice_join":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"ConcatV2":case"Concat":{const g=R("n",c,h,d),y=R("axis",c,h,d);let w=R("tensors",c,h,d);return w=w.slice(0,g),[m.concat(w,y)]}case"Gather":{const g=R("x",c,h,d),y=R("indices",c,h,d);return[m.gather(g,m.cast(y,"int32"),0)]}case"GatherV2":{const g=R("axis",c,h,d),y=R("batchDims",c,h,d),w=R("x",c,h,d),v=R("indices",c,h,d);return[m.gather(w,m.cast(v,"int32"),g,y)]}case"Reverse":{const g=R("dims",c,h,d),y=[];for(let v=0;v<g.length;v++)g[v]&&y.push(v);const w=R("x",c,h,d);return[m.reverse(w,y)]}case"ReverseV2":{const g=R("axis",c,h,d),y=R("x",c,h,d);return[m.reverse(y,g)]}case"Slice":{const g=R("begin",c,h,d),y=R("size",c,h,d);return[m.slice(R("x",c,h,d),g,y)]}
88case"StridedSlice":{const g=R("begin",c,h,d),y=R("end",c,h,d),w=R("strides",c,h,d),v=R("beginMask",c,h,d),N=R("endMask",c,h,d),T=R("ellipsisMask",c,h,d),$=R("newAxisMask",c,h,d),_=R("shrinkAxisMask",c,h,d),L=R("x",c,h,d);return[m.stridedSlice(L,g,y,w,v,N,T,$,_)]}case"Pack":return be(()=>{const g=R("axis",c,h,d),y=R("tensors",c,h,d),w=y[0].shape,v=m.squeeze(y[0]).shape,N=y.map(T=>{const $=le(T.shape,w);if(!$&&!le(m.squeeze(T).shape,v))throw new Error("the input tensors shape does not match");return $?T:m.reshape(T,w)});return[m.stack(N,g)]});case"Unpack":{const g=R("axis",c,h,d),y=R("tensor",c,h,d);return m.unstack(y,g)}case"Tile":{const g=R("reps",c,h,d);return[m.tile(R("x",c,h,d),g)]}case"Split":case"SplitV":{const g=R("axis",c,h,d),y=R("numOrSizeSplits",c,h,d),w=R("x",c,h,d);return m.split(w,y,g)}case"ScatterNd":{const g=R("indices",c,h,d),y=R("values",c,h,d),w=R("shape",c,h,d);return[m.scatterND(g,y,w)]}case"GatherNd":{const g=R("x",c,h,d),y=R("indices",c,h,d);return[m.gatherND(g,y)]}case"SparseToDense":{const g=R("sparseIndices",c,h,d),y=R("outputShape",c,h,d),w=R("sparseValues",c,h,d),v=R("defaultValue",c,h,d);return[m.sparseToDense(g,w,y,w.dtype===v.dtype?v:m.cast(v,w.dtype))]}case"TensorScatterUpdate":{const g=R("indices",c,h,d),y=R("values",c,h,d),w=R("tensor",c,h,d);return[m.tensorScatterUpdate(w,g,y)]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"sparse":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"SparseFillEmptyRows":{const{outputIndices:g,outputValues:y,emptyRowIndicator:w,reverseIndexMap:v}=m.sparse.sparseFillEmptyRows(R("indices",c,h,d),R("values",c,h,d),R("denseShape",c,h,d),R("defaultValue",c,h,d));return[g,y,w,v]}case"SparseReshape":{const{outputIndices:g,outputShape:y}=m.sparse.sparseReshape(R("inputIndices",c,h,d),R("inputShape",c,h,d),R("newShape",c,h,d));return[g,y]}case"SparseSegmentMean":return[m.sparse.sparseSegmentMean(R("data",c,h,d),R("indices",c,h,d),R("segmentIds",c,h,d))];case"SparseSegmentSum":return[m.sparse.sparseSegmentSum(R("data",c,h,d),R("indices",c,h,d),R("segmentIds",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"spectral":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"FFT":return[m.fft(R("x",c,h,d))];case"IFFT":return[m.ifft(R("x",c,h,d))];case"RFFT":return[m.rfft(R("x",c,h,d))];case"IRFFT":return[m.irfft(R("x",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"string":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"StaticRegexReplace":return[m.string.staticRegexReplace(R("input",c,h,d),R("pattern",c,h,d),R("rewrite",c,h,d),R("replaceGlobal",c,h,d))];case"StringNGrams":{const{nGrams:g,nGramsSplits:y}=m.string.stringNGrams(R("data",c,h,d),R("dataSplits",c,h,d),R("separator",c,h,d),R("nGramWidths",c,h,d),R("leftPad",c,h,d),R("rightPad",c,h,d),R("padWidth",c,h,d),R("preserveShortSequences",c,h,d));return[g,y]}case"StringSplit":{const{indices:g,values:y,shape:w}=m.string.stringSplit(R("input",c,h,d),R("delimiter",c,h,d),R("skipEmpty",c,h,d));return[g,y,w]}case"StringToHashBucketFast":return[m.string.stringToHashBucketFast(R("input",c,h,d),R("numBuckets",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"transformation":return s(()=>((c,h,d,m=at)=>{switch(c.op){case"Cast":return[m.cast(R("x",c,h,d),R("dtype",c,h,d))];case"ExpandDims":{const g=R("axis",c,h,d);return[m.expandDims(R("x",c,h,d),g)]}case"Squeeze":{const g=R("axis",c,h,d);return[m.squeeze(R("x",c,h,d),g)]}case"Reshape":return[m.reshape(R("x",c,h,d),R("shape",c,h,d))];case"EnsureShape":return[m.ensureShape(R("x",c,h,d),R("shape",c,h,d))];case"MirrorPad":return[m.mirrorPad(R("x",c,h,d),R("padding",c,h,d),R("mode",c,h,d))];case"PadV2":case"Pad":return[m.pad(R("x",c,h,d),R("padding",c,h,d),R("constantValue",c,h,d))];case"SpaceToBatchND":{const g=R("blockShape",c,h,d),y=R("paddings",c,h,d);return[m.spaceToBatchND(R("x",c,h,d),g,y)]}case"BatchToSpaceND":{const g=R("blockShape",c,h,d),y=R("crops",c,h,d);return[m.batchToSpaceND(R("x",c,h,d),g,y)]}case"DepthToSpace":{const g=R("blockSize",c,h,d),y=R("dataFormat",c,h,d).toUpperCase();return[m.depthToSpace(R("x",c,h,d),g,y)]}case"BroadcastTo":return[m.broadcastTo(R("x",c,h,d),R("shape",c,h,d))];case"BroadcastArgs":return[m.broadcastArgs(R("s0",c,h,d),R("s1",c,h,d))];default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l));case"hash_table":return(async(c,h,d,m)=>
88{switch(c.op){case"HashTable":case"HashTableV2":{const g=m.getHashTableHandleByName(c.name);if(g!=null)return[g];{const y=R("keyDType",c,h,d),w=R("valueDType",c,h,d),v=new oA(y,w);return m.addHashTable(c.name,v),[v.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const g=R("tableHandle",c,h,d,m),y=R("keys",c,h,d),w=R("values",c,h,d);return[await m.getHashTableById(g.id).import(y,w)]}case"LookupTableFind":case"LookupTableFindV2":{const g=R("tableHandle",c,h,d,m),y=R("keys",c,h,d),w=R("defaultValue",c,h,d);return[await m.getHashTableById(g.id).find(y,w)]}case"LookupTableSize":case"LookupTableSizeV2":{const g=R("tableHandle",c,h,d,m);return[m.getHashTableById(g.id).tensorSize()]}default:throw TypeError(`Node type ${c.op} is not implemented`)}})(i,o,l,r);case"custom":const p=yk(i.op);if(p&&p.customExecutor)return p.customExecutor(new aA(i,o,l));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.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 Ya(a)?a.then(i=>[].concat(i)):[].concat(a)}class Tk{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;t<this.contexts.length-1;t++){const r=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(r))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.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))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{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))}}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)}}function Ek(n,e,t,r){const s=new Set,a=[];let i=null,o=null;const l=new Set,p=new Set(Object.keys(n).map(d=>Ca(d)[0]));r=r||[];const c=new Set(r.map(d=>Ca(d.name)[0])),h=[...e];for(;h.length>0;){const d=h.pop();(Th(d)||hA(d)||dA(d))&&i==null&&(i=d,o=i.children.map(m=>m.name).filter(m=>s.has(m))),s.add(d.name),t[d.name]==null&&(p.has(d.name)||c.has(d.name)||(d.inputs.length!==0?d.inputs.forEach(m=>{l.has(m.name)||(l.add(m.name),h.push(m))}):a.push(d.name)))}return{inputs:n,outputs:e,usedNodes:s,missingInputs:a,dynamicNode:i,syncInputs:o}}class qg extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const uA=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),lA=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),cA=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Th(n){return uA.has(n.op)}function hA(n){return lA.has(n.op)}function dA(n){return cA.has(n.op)}class Xg{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(r=>e[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)=>
88(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 Xg(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=Ek(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:a,syncInputs:i}=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 [${i}]`);if(s.length>0){const p=t.map(h=>h.name),c=Object.keys(e);throw new Error(`Cannot compute the outputs [${p}] from the provided inputs [${c}]. Missing the following inputs: [${s}]`)}const o=function(p,c){const{usedNodes:h,inputs:d}=c,m=Object.keys(d).map(O=>Ca(O)[0]).map(O=>p.nodes[O]),g=p.initNodes||[],y=O=>h.has(typeof O=="string"?O:O.name);function w(O){return[...new Map(O.map(V=>[V.name,V])).values()]}const v=w([...m,...p.weights,...g]).filter(y),N=w([...v,...Object.values(p.nodes)]).filter(y),T=new Map(N.map(O=>[O.name,O])),$={};for(const O of N){$[O.name]=$[O.name]||0;for(const V of O.children)y(V)||($[V.name]=Number.POSITIVE_INFINITY),$[V.name]=($[V.name]||0)+1}const _=Object.entries($).filter(([,O])=>O===0).map(([O])=>O),L=[..._];for(;_.length>0;){const O=_.pop(),V=T.get(O);for(const U of V.children.filter(y))--$[U.name]===0&&(L.push(U.name),_.push(U.name))}const z=function(O,V){const U=new Map(O.map(ae=>[ae.name,ae])),X=V.map(ae=>ae.name),ne=new Set(X);for(;X.length>0;){const ae=X.pop(),Ie=U.get(ae);for(const me of Ie.children)U.has(me.name)&&!ne.has(me.name)&&(ne.add(me.name),X.push(me.name))}return O.filter(ae=>ne.has(ae.name))}(L.map(O=>T.get(O)),v);return function(O,V){const U=new Map(O.map((me,we)=>[me.name,we])),X=new Set(V.map(me=>me.name)),ne=me=>X.has(typeof me=="string"?me:me.name),ae=new Set(O.map(me=>me.name)),Ie=me=>ae.has(typeof me=="string"?me:me.name);for(const me of O){for(const we of me.children.filter(Ie)){if(!U.has(we.name))throw new qg(`Child ${we.name} of node ${me.name} is unreachable.`);if(U.get(me.name)>U.get(we.name))throw new qg(`Node ${me.name} is scheduled to run after its child ${we.name}.`)}if(!ne(me))for(const we of me.inputs){if(!U.has(we.name))throw new qg(`Input ${we.name} of node ${me.name} is unreachable.`);if(U.get(we.name)>U.get(me.name))throw new qg(`Node ${me.name} is scheduled to run before its input ${we.name}.`)}}}(z,v),z}(this.graph,r),l=function(p){const c=new Map(p.map((w,v)=>[w.name,v])),h=Number.MAX_SAFE_INTEGER,d=p.map((w,v)=>Th(w)?h:v),m=w=>{const v=d[c.get(w.name)];return v??-1},g=p.map((w,v)=>w.children.map(m).reduce((N,T)=>Math.max(N,T),d[v])),y=new Map;for(let w=0;w<p.length;++w){const v=g[w];if(v===h)continue;const N=p[w],T=p[v];y.has(T.name)||y.set(T.name,[]),y.get(T.name).push(N)}return y}(o);return{orderedNodes:o,nodeLiveUntilMap:l}}cloneAndKeepTensor(e){if(e==null)return null;const t=e.clone();return _r(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(d=>this.graph.nodes[Ca(d)[0]]),a=t.map(d=>Ca(d)[0]),i=new Set(a);let o=a.map(d=>this.graph.nodes[d]);o.length===0&&(o=this._outputs);const l=this.getCompilationKey(s,o);let p=this.compiledMap.get(l);p==null&&(p=this.compile(e,o),this.compiledMap.set(l,p));try{this.keepIntermediateTensors=xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const c={},h={};return be(()=>{const d=new Tk(this.weightMap,c,h,this.functionExecutorMap,this.parseNodeNameCache),m=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(v=>{const[N,T]=Ca(v,d),$=[];$[T]=e[v],m[N]=$,this.keepIntermediateTensors&&(this.clonedTensorsMap[N]=this.cloneTensorList($))});const g=this.getFrozenTensorIds(m),{orderedNodes:y,nodeLiveUntilMap:w}=p;for(const v of y){if(m[v.name])continue;const N=Sk(v,m,d,this._resourceManager);
88if(Ya(N))throw new Error(`The execution of the op '${v.op}' returned a promise. Please use model.executeAsync() instead.`);m[v.name]=N,this.keepIntermediateTensors&&(this.clonedTensorsMap[v.name]=this.cloneTensorList(N)),this.checkTensorForDisposalWithNodeLiveUntilInfo(v,m,d,g,i,w.get(v.name))}return this.parent==null&&d.dispose(g),t.map(v=>ks(v,m,d))})}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,i,o){if(!Th(t)&&!i.has(e)){for(const l of r[e])l!=null&&(o[l.id]=(o[l.id]||0)+t.children.length);for(const l of t.inputs){if(Th(l))continue;const p=bk(l.name,r,s);if(p!=null)for(const c of p){if(!c||c.kept||a.has(c.id))continue;const h=o[c.id];h===1?(c.dispose(),delete o[c.id]):h!=null&&o[c.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,r,s,a,i){function o(l){return Th(l)||a.has(l.name)}if(!Th(e)&&i!=null)for(const l of i){if(o(l))continue;const p=bk(l.name,t,r);for(const c of p)!c||c.kept||s.has(c.id)||c.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=xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const i=new Tk(this.weightMap,s,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,i,t,r),l=t.map(d=>ks(d,o,i)),p=l.map(d=>d.id),c=Object.keys(e).map(d=>e[d].id),h=new Set([...p,...c,...this.weightIds]);return Object.values(o).forEach(d=>{d.forEach(m=>{!m||m.isDisposed||h.has(m.id)||m.dispose()})}),this.parent==null&&i.dispose(h),l}async executeFunctionAsync(e,t,r){const s=e.reduce((a,i,o)=>(a[this.inputs[o].name]=i,a),{});return this._executeAsync(s,this.outputNodes,!0,t,r)}async executeWithControlFlow(e,t,r,s){const a=Object.keys(e),i=a.map($=>this.graph.nodes[Ca($)[0]]),o=r.map($=>Ca($)[0]),l=new Set(o);let p=o.map($=>this.graph.nodes[$]);p.length===0&&(p=this._outputs);const{usedNodes:c,missingInputs:h,dynamicNode:d,syncInputs:m}=Ek(e,p,this.weightMap,this._initNodes),g=[...i,...this.graph.weights,...this._initNodes||[]].map($=>({node:$,contexts:t.currentContext})),y=Object.assign({},this.weightMap);Object.keys(e).forEach($=>{const[_,L]=Ca($),z=[];z[L]=e[$],y[_]=z});const w={},v=this.getFrozenTensorIds(y),N={};for(;g.length>0;){const $=this.processStack(i,g,t,y,N,v,l,w,c);await Promise.all($)}d!=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 T=p.filter($=>!Th($)&&!ks($.name,y,t)).map($=>$.name);if(T.length>0){let $="";throw d!=null&&($=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`),new Error(`Cannot compute the outputs [${T}] from the provided inputs [${a}]. Consider providing the following inputs: [${h}]. ${$}`)}return y}processStack(e,t,r,s,a,i,o,l,p){const c=[];for(;t.length>0;){const h=t.pop();r.currentContext=h.contexts;let d="";if(h.node.op==="Enter"&&R("isConstant",h.node,s,r)&&([d]=Gu(h.node.name,r)),s[h.node.name]==null){const m=Sk(h.node,s,r,this._resourceManager);d||([d]=Gu(h.node.name,r));const g=r.currentContext;Ya(m)?c.push(m.then(y=>(s[d]=y,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(y)),r.currentContext=g,this.checkTensorForDisposal(d,h.node,s,r,i,o,l),this.processChildNodes(h.node,t,r,s,a,p),y))):(s[d]=m,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(m)),this.checkTensorForDisposal(d,h.node,s,r,i,o,l),this.processChildNodes(h.node,t,r,s,a,p))}else this.processChildNodes(h.node,t,r,s,a,p)}return c}
88processChildNodes(e,t,r,s,a,i){e.children.forEach(o=>{const[l]=Gu(o.name,r);!a[l]&&i.has(o.name)&&(o.op==="Merge"?o.inputNames.some(p=>!!ks(p,s,r))&&(a[l]=!0,t.push({contexts:r.currentContext,node:o})):o.inputNames.every(p=>!!ks(p,s,r))&&(a[l]=!0,t.push({contexts:r.currentContext,node:o})))})}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]=Ca(t),a=this.graph.nodes[s];if(a.attrParams.shape&&a.attrParams.shape.value){const i=a.attrParams.shape.value;A(i.length===r.shape.length&&r.shape.every((o,l)=>i[l]===-1||i[l]===o),()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${i}], but was [${r.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&A(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 i=(r=(t=this._signature)===null||t===void 0?void 0:t.inputs)===null||r===void 0?void 0:r[a];i!=null?s[i.name]=e[a]:s[a]=e[a]}return s}checkInputs(e){const t=Object.keys(e).filter(r=>{const[s]=Ca(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]=Ca(t);if(!this.graph.nodes[r])throw new Error(`The output '${t}' is not found in the graph`)})}}class pA{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]}}const fA="?tfjs-format=file",mA="model.json";class ux{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=Te){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=r,t==null&&(this.loadOptions={}),this.resourceManager=new pA}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 Ya(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 mm(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 Xg(xk.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=xk.Instance.transformGraph(e.modelInitializer);this.initializer=new Xg(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={};return(e instanceof Sn?[e]:e).forEach((r,s)=>t[this.structuredOutputKeys[s]]=r),t}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 Sn||Array.isArray(e))){const a=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(a!=null)for(const i in a){const o=a[i];o.resourceId!=null&&(e[i]=this.resourceIdToCapturedInput[o.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,i)=>{var o,l,p;const c=(p=(l=(o=this.signature)===null||o===void 0?void 0:o.inputs)===null||l===void 0?void 0:l[i])===null||p===void 0?void 0:p.resourceId;return a[i]=c!=null?this.resourceIdToCapturedInput[c]: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;s<r.length;s++){const a=t[r[s]];this.resourceIdToCapturedInput[a.resourceId]=e[s]}}}execute(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const r=this.executor.execute(e,t);return r.length>1?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&&on(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function gA(n,e={},t=Te){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=function(s){return s.endsWith("/")||(s+="/"),`${s}${mA}${fA}`}(n));const r=new ux(n,e,t);return await r.load(),r}function yA(n){if(n==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let e;if(n instanceof Array){const[r,s]=n;if(!r)throw new Error("modelJSON must be the first element of the array");if(!(s&&s instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in r))throw new Error("Model JSON is missing 'modelTopology'");
vendor: 10,039 bytes, line 88
88if(!("weightsManifest"in r))throw new Error("Model JSON is missing 'weightsManifest'");e=ah(Eu(r,Cu(r.weightsManifest),s))}else if("load"in n)e=n;else{if(!("modelTopology"in n&&"weightSpecs"in n&&"weightData"in n))throw new Error("Unknown model format");e=ah(n)}const t=new ux(e);return t.load(),t}const Ck="4.22.0";function Yg(n,e,t=new Map,r=new Set){if(n==null)return null;if(typeof Blob=="function"&&n instanceof Blob)return n.slice();if(r.has(n))throw new Error("Circular references are not supported.");if(t.has(n))return t.get(n);const s=e(n);if(s.recurse&&s.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse){if(Zd(n)){const a=Array.isArray(n)?[]:{};r.add(n);for(const i in n){const o=Yg(n[i],e,t,r);a[i]=o}return r.delete(n),n.__proto__&&(a.__proto__=n.__proto__),a}throw new Error(`Can't recurse into non-iterable type: ${n}`)}return t.set(n,s.value),s.value}function bA(n,e=Ak){return $k(n,e)}function $k(n,e,t=new Set){const r=n[0];if(t.has(r))throw new Error("Circular references are not supported.");const s=e(n);if(s.recurse&&s.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse){if(Zd(r)){const a=Array.isArray(r)?[]:{};t.add(r);for(const i in r){const o=$k(n.map(l=>l[i]),e,t);a[i]=o}return t.delete(r),a}throw new Error(`Can't recurse into non-iterable type: ${r}`)}return s.value}function Ak(n){return n===null?null:Zd(n[0])?{value:null,recurse:!0}:{value:n,recurse:!1}}async function Rk(n,e){const t=new Map;Yg(n,e,t);for(const r of Array.from(t.keys())){const s=t.get(r);if(Ya(s)){const a=await s;t.set(r,a)}}return Yg(n,e,t)}function Zd(n){let e=!1;if(xe().get("IS_BROWSER"))e=n instanceof TextDecoder;else{const{StringDecoder:t}=Z(551);e=n instanceof t}return n!=null&&!ArrayBuffer.isView(n)&&(Array.isArray(n)||typeof n=="object"&&!(n instanceof Sn)&&!(n instanceof Promise)&&!e)}function xA(n){return n instanceof Sn?{value:n.clone(),recurse:!1}:Zd(n)?{value:null,recurse:!0}:{value:n,recurse:!1}}class _k{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),r=this.get(t);return this.set(t,this.pop()),r}}class Zg extends _k{constructor(){super(Zg.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),r=this.length();for(let s=0;s<r;s++)t[s]=this.get(this.wrap(this.begin+s));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=r}}function Dk(n){return new wA(n)}function lx(n){return new vA(n)}Zg.INITIAL_CAPACITY=32;class cs{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let r=await e.next();for(;!r.done;)t.push(r.value),r=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),r=e(t.value);for(;!t.done&&r;)t=await this.next(),r=e(t.value)}handleErrors(e){return new CA(this,e)}filter(e){return new TA(this,e)}map(e){return new EA(this,e)}mapAsync(e){return new Fk(this,e)}serialMapAsync(e){return new Fk(this,e).serial()}flatmap(e){return new $A(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new SA(this,e,t)}columnMajorBatch(e,t=!0,r=Ak){return this.rowMajorBatch(e,t).map(s=>bA(s,r))}concatenate(e,t){return new Mk(Dk([this,e]),t)}take(e){return e<0||e==null?this:new IA(this,e)}skip(e){return e<0||e==null?this:new NA(this,e)}prefetch(e){return new Ok(this,e)}shuffle(e,t){return new RA(this,e,t)}serial(){return new kA(this)}}class wA extends cs{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:(t=e,function(r,s){return Yg(r,s)}(t,xA)),done:!1};var t}}class vA extends cs{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class kA extends cs{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class NA extends cs{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;on(e.value)}return this.upstream.next()}}class IA extends cs{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class SA extends cs{constructor(e,t,r=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=r,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class TA extends cs{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;on(e.value)}}}class EA extends cs{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=si(e.value),r=this.transform(e.value),s=si(r);for(const a of t)td(a,s)||a.dispose();return{value:r,done:!1}}}class CA extends cs{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class Fk extends cs{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=si(e.value),r=await this.transform(e.value),s=si(r);for(const a of t)td(a,s)||a.dispose();return{value:r,done:!1}}}class cx extends cs{constructor(){super(),this.outputQueue=new Zg,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class $A extends cx{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=si(e.value),r=this.transform(e.value),s=si(r);this.outputQueue.pushAll(r);for(const a of t)td(a,s)||a.dispose();return!0}}class Mk extends cs{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){const r=await this.moreIterators.next();if(r.done)return{value:null,done:!0};this.iterator=r.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var uc;
88(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(uc||(uc={}));class AA extends cs{constructor(e,t=uc.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,r=0;const s=await Rk(this.iterators,function(a){return a instanceof cs?{value:a.next().then(i=>(t++,i.done&&r++,i.value)),recurse:!1}:{value:null,recurse:!0}});if(t===r)return{value:null,done:!0};if(r>0)switch(this.mismatchMode){case uc.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case uc.SHORTEST:return{value:null,done:!0};case uc.LONGEST:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class Ok extends cs{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new _k(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class RA extends Ok{constructor(e,t,r){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=zd.alea(r||Fn().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class Qd{constructor(){this.size=null}batch(e,t=!0){const r=this;let s;return A(e>0,()=>`batchSize needs to be positive, but it is
89      ${e}`),s=this.size===1/0||this.size==null?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),$a(async()=>(await r.iterator()).columnMajorBatch(e,t,FA),s)}concatenate(e){const t=this;let r;return r=this.size===1/0||e.size===1/0?1/0:this.size!=null&&e.size!=null?this.size+e.size:null,$a(async()=>(await t.iterator()).concatenate(await e.iterator()),r)}filter(e){const t=this;let r;return r=this.size===1/0?1/0:null,$a(async()=>(await t.iterator()).filter(s=>be(()=>e(s))),r)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return $a(async()=>(await t.iterator()).map(r=>be(()=>e(r))),this.size)}mapAsync(e){const t=this;return $a(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return $a(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let r;return r=this.size!=null&&e>0?this.size*e:e===0?0:this.size!=null&&(e===void 0||e<0)?1/0:null,$a(async()=>{return s=lx(async()=>({value:await t.iterator(),done:!1})).take(e),new Mk(s,a);var s,a},r)}skip(e){const t=this;let r;return r=this.size!=null&&e>=0&&this.size>=e?this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?0:null,$a(async()=>(await t.iterator()).skip(e),r)}shuffle(e,t,r=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,a=zd.alea(t||Fn().toString());return $a(async()=>{let i=a.int32();return r&&(i+=a.int32()),(await s.iterator()).shuffle(e,i.toString())},this.size)}take(e){const t=this;let r;return r=this.size!=null&&this.size>e?e:this.size!=null&&this.size<=e?this.size:null,$a(async()=>(await t.iterator()).take(e),r)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function $a(n,e=null){return new class extends Qd{constructor(){super(...arguments),this.size=e}async iterator(){return n()}}}function _A(n){return $a(async()=>Dk(n),n.length)}function DA(n){if(!Zd(n))throw new Error("The argument to zip() must be an object or array.");let e;if(Array.isArray(n))for(let t=0;t<n.length;t++)e=e==null?n[t].size:Math.min(e,n[t].size);else if(n instanceof Object)for(const t in n)e=e==null?n[t].size:Math.min(e,n[t].size);return $a(async()=>function(t,r=uc.FAIL){return new AA(t,r)}(await Rk(n,t=>{if(t instanceof Qd)return{value:t.iterator(),recurse:!1};if(Zd(t))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")}),uc.SHORTEST),e)}function FA(n){if(n===null)return null;return(e=n[0])==null||(t=e)===null||typeof t!="object"&&typeof t!="function"||Array.isArray(e)||typeof e=="object"&&e instanceof Sn||lr(e)?{value:function(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Sn?Hs(r):Bs(r)}(n),recurse:!1}:{value:null,recurse:!0};var e,t}Qd.MAX_BUFFER_SIZE=1e4;class Lk extends Qd{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
90`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}}const Qg='"',Df=Symbol("out"),zk=Symbol("field"),Jg=Symbol("quote"),hx=Symbol("quoteafterquote"),Pk=Symbol("quoteinquote");class Bk extends Qd{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&A(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,a)=>(s[a]=s[a]+1||1,s),{}),r=Object.keys(t).filter(s=>t[s]>1);if(A(r.length===0,()=>"Duplicate column names found: "+r.toString()),this.columnConfigs){for(const s of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(s)===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const r=t.value;return this.parseRow(r,!1)}return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new Lk(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(A(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),r={},s={};for(let a=0;a<this.fullColumnNames.length;a++){const i=this.fullColumnNames[a],o=this.columnConfigs?this.columnConfigs[i]:null;if(!this.configuredColumnsOnly||o){const l=t[a];let p=null;if(l==="")if(o&&o.default!==void 0)p=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${i} is empty in this line: ${e}`);p=void 0}else{const c=Number(l);if(isNaN(c))p=o&&o.dtype==="bool"?this.getBoolean(l):l;else if(o&&o.dtype)switch(o.dtype){case"float32":default:p=c;break;case"int32":p=Math.floor(c);break;case"bool":p=this.getBoolean(l)}else p=c}o&&o.isLabel?s[i]=p:r[i]=p}}return Object.keys(s).length===0?r:{xs:r,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const r=[];let s=0;const a=e.length;let i=Df;for(let o=0;o<a;o++)switch(i){case Df:switch(e.charAt(o)){case Qg:s=o+1,i=Jg;break;case this.delimiter:if(s=o+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),i=Df;break;default:i=zk,s=o}break;case zk:e.charAt(o)===this.delimiter&&(r.push(e.substring(s,o)),i=Df,s=o+1);break;case Jg:e.charAt(o)===Qg&&(i=hx);break;case hx:switch(e.charAt(o)){case this.delimiter:r.push(e.substring(s,o-1)),i=Df,s=o+1;break;case Qg:i=Jg;break;default:i=Pk}break;case Pk:e.charAt(o)===Qg&&(i=Jg)}if(i===hx?r.push(e.substring(s,a-1)):r.push(e.substring(s)),t&&r.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${r}`);return r}}class dx extends cs{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);
90if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!xe().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new dx(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null||this.audioTrackConstraints,video:!1})}catch(r){throw new Error(`Error thrown while initializing video stream: ${r.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const r=await this.getAudioData();if(this.includeSpectrogram){const s=this.flattenQueue(r.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const s=this.flattenQueue(r.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let r=0;return new Promise(s=>{const a=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++r===this.numFrames&&(clearInterval(a),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,r=new Float32Array(e.length*t);return e.forEach((s,a)=>r.set(s,a*t)),r}getTensorFromAudioDataArray(e,t){const r=new Float32Array(j(t));return r.set(e,r.length-e.length),Bs(r,t)}}class px extends cs{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=vs([0],"int32"),this.webcamConfig.centerCrop){const r=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,s=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,a=(1-r)/2,i=(1-s)/2,o=a+r,l=s+i;this.cropBox=Ql([i,a,l,o],[1,4])}else this.cropBox=Ql([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!xe().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const r=new px(e,t);return await r.start(),r}async start(){this.webcamConfig.facingMode&&A(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream
90: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Gp(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return be(()=>{const t=ws(gt(e,"float32"),0);let r;r=hi.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=r.shape;return he(r,s.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class Vk{}class Uk extends cs{split(e){return new MA(this,e)}}class MA extends Uk{constructor(e,t){super(),this.upstream=e,this.impl=new OA(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class OA extends cx{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return this.carryover!==""&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const r of t.slice(0,-1))this.outputQueue.push(r);return this.carryover=t[t.length-1],!0}}class LA extends cs{decodeUTF8(){return new zA(this)}}class zA extends Uk{constructor(e){super(),this.upstream=e,this.impl=new PA(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class PA extends cx{constructor(e){if(super(),this.upstream=e,xe().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=Z(530);this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,r;return!e.done&&(t=e.value,r=xe().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(r),!0)}}class Wk extends LA{constructor(e,t={}){super(),this.file=e,this.options=t,A(e instanceof Uint8Array||!!xe().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,r)=>{const s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{const a=new FileReader;a.onload=o=>{let l=a.result;if(l instanceof ArrayBuffer&&(l=new Uint8Array(l)),!(l instanceof Uint8Array))return r(new TypeError("FileReader returned unknown type."));t(l)},a.onabort=o=>r(new Error("Aborted")),a.onerror=o=>r(new Error(o.type));const i=this.file.slice(this.offset,s);a.readAsArrayBuffer(i)}this.offset=s}),done:!1}}}function Gk(n){return typeof n=="string"&&n.slice(0,7)==="file://"}class Hk extends Vk{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(Gk(this.input)&&xe().get("IS_NODE")){const e=Z(108);this.input=e.readFileSync(this.input.slice(7))}return new Wk(this.input,this.options)}}class jk extends Vk{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return Gk(this.url)?new Hk(this.url,this.fileOptions).iterator():async function(e,t={},r){let s,a;var i;typeof e=="string"?s=e:(s=e.url,a={method:(i=e).method,headers:i.headers,body:i.body,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,referrer:i.referrer,integrity:i.integrity});const o=await Kn(s,a);if(o.ok){const l=new Uint8Array(await o.arrayBuffer());return new Wk(l,t)}throw new Error(o.statusText)}(this.url,this.fileOptions)}}function BA(n,e={}){return new Bk(new jk(n),e)}function VA(n){const e=lx(n);return $a(async()=>e)}function UA(n){return $a(async()=>{const e=await n();return lx(()=>e.next())})}async function WA(n,e){return px.create(n,e)}async function GA(n){return dx.create(n)}const Kk="4.22.0";
90function zt(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&A(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}const HA=eg;class Ff extends E{nextDataId(){return Ff.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new k(this,wa())}write(e,t,r){this.firstUse&&(this.firstUse=!1,xe().get("IS_NODE")&&In(`
91============================
92Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. 
93============================`));const s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:r,refCount:1}),s}makeTensorInfo(e,t,r){let s;if(t==="string"&&r!=null&&r.length>0&&Qn(r[0])){const a=r.map(i=>dn(i));s=this.write(a,e,t)}else s=this.write(r,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,r,s,a){this.data.set(e,{values:t,dtype:s,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:r}=this.data.get(e);return t==="complex64"?zu(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):Ph(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const r=t.map(s=>gr(s));return ln(e.shape,e.dtype,r)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return ln(e.shape,e.dtype,t)}makeOutput(e,t,r){return wa().makeTensorFromTensorInfo(this.makeTensorInfo(t,r,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:r}=this.data.get(e);r!=null&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Fn();return e(),{kernelMs:Fn()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){zt([e],"where");const t=this.readSync(e.dataId);return HA(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function qk(n){const e=new Float32Array(n.length);for(let t=0;t<n.length;++t)e[t]=Math.abs(n[t]);return e}Ff.nextDataId=0;const jA={kernelName:Yu,backendName:"cpu",kernelFunc:n=>{const{x:e}=n.inputs,t=n.backend;zt(e,"abs");let r=new Float32Array(j(e.shape));return r=qk(t.data.get(e.dataId).values),t.makeOutput(r,e.shape,e.dtype)}};function zr(n){return(e,t,r,s,a)=>{const i=Gt(e,t),o=i.length,l=Ge(i),p=_t(a,j(i)),c=e.length,h=t.length,d=Ge(e),m=Ge(t),g=ys(e,i),y=ys(t,i);if(g.length+y.length===0)for(let w=0;w<p.length;++w)p[w]=n(r[w%r.length],s[w%s.length]);else for(let w=0;w<p.length;++w){const v=Fs(w,o,l),N=v.slice(-c);g.forEach(L=>N[L]=0);const T=Qs(N,c,d),$=v.slice(-h);y.forEach(L=>$[L]=0);const _=Qs($,h,m);p[w]=n(r[T],s[_])}return[p,i]}}function Aa(n){const{inputs:e,backend:t}=n,{real:r,imag:s}=e,a=t.data.get(r.dataId).values,i=t.data.get(s.dataId).values,o=t.makeTensorInfo(r.shape,"complex64");return t.data.get(o.dataId).complexTensorInfos={real:t.makeTensorInfo(r.shape,"float32",a),imag:t.makeTensorInfo(s.shape,"float32",i)},o}const KA={kernelName:Wh,backendName:"cpu",kernelFunc:Aa};function ey(n,e,t="float32"){if(t==="complex64")return Aa({inputs:{real:ey(n,e,"float32"),imag:ey(n,e,"float32")},backend:n});const r=Er(j(e),t);return n.makeTensorInfo(e,t,r)}function Yo(n){const{inputs:e,backend:t}=n,{x:r}=e;return t.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const qA={kernelName:Ja,backendName:"cpu",kernelFunc:Yo};function Eh(n){const{inputs:e,backend:t}=n,{input:r}=e,s=t.data.get(r.dataId).complexTensorInfos.real,a=t.data.get(s.dataId).values;return t.makeTensorInfo(s.shape,s.dtype,a)}const XA={kernelName:xl,backendName:"cpu",kernelFunc:Eh};function Xk(n,e,t,r){if(r==="int32")return[e,"int32",Int32Array.from(n)];if(r==="bool"){const s=Ui([0],t),[a,i]=zr((o,l)=>o!==l?1:0)(e,[],n,s,"bool");return[i,"bool",a]}throw new Error(`Error in Cast: failed to cast ${t} to ${r}`)}function lc(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dtype:a}=r;
vendor: 25,845 bytes, line 93
93if(a==="complex64"){if(s.dtype==="complex64")return Yo({inputs:{x:s},backend:t});const c=ey(t,s.shape,s.dtype),h=lc({inputs:{x:s},backend:t,attrs:{dtype:"float32"}}),d=Aa({inputs:{real:h,imag:c},backend:t});return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),d}if(s.dtype==="complex64"){const c=Eh({inputs:{input:s},backend:t}),h=lc({inputs:{x:c},backend:t,attrs:{dtype:a}});return t.disposeIntermediateTensorInfo(c),h}if(!ve(s.dtype,a)){const c=Yo({inputs:{x:s},backend:t});return{dataId:c.dataId,shape:c.shape,dtype:a}}const i=t.data.get(s.dataId).values,[o,l,p]=Xk(i,s.shape,s.dtype,a);return t.makeTensorInfo(o,l,p)}const YA={kernelName:tl,backendName:"cpu",kernelFunc:lc};function Qr(n,e,t,r){return t==null?({inputs:s,backend:a})=>{const{a:i,b:o}=s,l=a;zt([i,o],n);const p=l.data.get(i.dataId).values,c=l.data.get(o.dataId).values,h=i.dtype==="string"?Pu(p):p,d=i.dtype==="string"?Pu(c):c,m=r||i.dtype,[g,y]=e(i.shape,o.shape,h,d,m);return l.makeTensorInfo(y,m,g)}:({inputs:s,backend:a})=>{const{a:i,b:o}=s,l=a;if(i.dtype==="complex64"||o.dtype==="complex64"){const p=lc({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(p.dataId),h=c.complexTensorInfos.real,d=c.complexTensorInfos.imag,m=l.data.get(h.dataId).values,g=l.data.get(d.dataId).values,y=lc({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),w=l.data.get(y.dataId),v=w.complexTensorInfos.real,N=w.complexTensorInfos.imag,T=l.data.get(v.dataId).values,$=l.data.get(N.dataId).values,[_,L,z]=t(i.shape,o.shape,m,g,T,$),O=l.makeTensorInfo(z,"float32",_),V=l.makeTensorInfo(z,"float32",L),U=Aa({inputs:{real:O,imag:V},backend:l});return l.disposeIntermediateTensorInfo(p),l.disposeIntermediateTensorInfo(y),l.disposeIntermediateTensorInfo(O),l.disposeIntermediateTensorInfo(V),U}{const p=l.data.get(i.dataId).values,c=l.data.get(o.dataId).values,h=r||i.dtype,[d,m]=e(i.shape,o.shape,p,c,h);return l.makeTensorInfo(m,h,d)}}}function fx(n){return(e,t,r,s,a,i)=>{const o=Gt(e,t),l=j(o),p=o.length,c=Ge(o),h=_t("float32",l),d=_t("float32",l),m=ys(e,o),g=ys(t,o),y=zu(r,s),w=zu(a,i),v=e.length,N=Ge(e),T=t.length,$=Ge(t);if(m.length+g.length===0)for(let _=0;_<h.length;_++){const L=_%y.length,z=_%w.length,O=n(y[2*L],y[2*L+1],w[2*z],w[2*z+1]);h[_]=O.real,d[_]=O.imag}else for(let _=0;_<h.length;_++){const L=Fs(_,p,c),z=L.slice(-v);m.forEach(ne=>z[ne]=0);const O=Qs(z,v,N),V=L.slice(-T);g.forEach(ne=>V[ne]=0);const U=Qs(V,T,$),X=n(y[2*O],y[2*O+1],w[2*U],w[2*U+1]);h[_]=X.real,d[_]=X.imag}return[h,d,o]}}const Yk=zr((n,e)=>n+e),ZA=fx((n,e,t,r)=>({real:n+t,imag:e+r})),Jd=Qr(bi,Yk,ZA),QA={kernelName:bi,backendName:"cpu",kernelFunc:Jd};function mx(n,e,t,r,s){const a=j(r),i=Er(s,t);for(let o=0;o<n.length;o++){const l=n[o];if(l<0)throw new Error("Input x must be non-negative!");l>=s||(i[l]+=a>0?e[o]:1)}return i}function Zk(n,e,t,r=!1){const s=n.shape[0],a=n.shape[1],i=ln([s,t],e.dtype);for(let o=0;o<s;o++)for(let l=0;l<a;l++){const p=n.get(o,l);if(p<0)throw new Error("Input x must be non-negative!");p>=t||(r?i.set(1,o,p):e.size>0?i.set(i.get(o,p)+e.get(o,l),o,p):i.set(i.get(o,p)+1,o,p))}return i}const Qk=zr((n,e)=>n&e),JA=Qr(ki,Qk),e4={kernelName:ki,backendName:"cpu",kernelFunc:JA};function Zo(n){return(e,t,r)=>{const s=Zt(t,e.length);for(let a=0;a<e.length;++a)s[a]=n(e[a],r);return s}}function Wn(n,e,t){return cc(n,Zo(e),t)}function cc(n,e,t){return({inputs:r,attrs:s,backend:a})=>{const{x:i}=r;zt(i,n);const o=a,l=o.data.get(i.dataId).values;let p;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");p=Pu(l)}else p=l;const c=t||i.dtype,h=e(p,c,s);return o.makeTensorInfo(i.shape,c,h)}}const Jk=Zo(n=>Math.ceil(n)),t4=cc(nl,Jk),n4={kernelName:nl,backendName:"cpu",kernelFunc:t4};function eN(n,e,t,r){const s=Zt(t,j(e));if(r&&t!=="string"){let a=0;n.forEach(i=>{const o=j(i.shape);s.set(i.vals,a),a+=o})}else{let a=0;n.forEach(i=>{const o=t==="string"?Pu(i.vals):i.vals;let l=0;for(let p=0;p<i.shape[0];++p){const c=p*e[1]+a;for(let h=0;h<i.shape[1];++h)s[c+h]=o[l++]}a+=i.shape[1]})}return s}const tN=zr((n,e)=>n===e?1:0),nN=Qr(ol,tN,null,"bool"),r4={kernelName:ol,backendName:"cpu",kernelFunc:nN},rN=Zo(n=>Math.exp(n)),sN=cc(Os,rN,"float32"),s4={kernelName:Os,backendName:"cpu",kernelFunc:sN},aN=Zo(n=>Math.expm1(n)),a4=cc(vo,aN),i4={kernelName:vo,backendName:"cpu",kernelFunc:a4},iN=Zo(n=>Math.floor(n)),o4=cc(ko,iN),u4={kernelName:ko,backendName:"cpu",kernelFunc:o4},oN=zr((n,e)=>Math.floor(n/e)),l4=Qr(No,oN,null,"int32"),c4={kernelName:No,backendName:"cpu",kernelFunc:l4};function uN(n,e,t,r,s,a,i,o,l){const p=ln([r,a],t);for(let c=0;c<r;c++){const h=[];let d=0;for(let m=0;m<s;m++){const g=n[c*s+m];d+=g*i[m],h.push(g)}if(d<0||d>=l/a)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let m=0;m<a;m++)p.values[c*a+m]=e.get(...e.indexToLoc(d*a+m))}return p}function lN(n,e,t){const r=ln(t,n.dtype);for(let s=0;s<r.size;++s){const a=r.indexToLoc(s).slice(),i=a[0],o=a[2],l=e.locToIndex([i,o]);a[2]=e.values[l];const p=n.locToIndex(a);0<=p&&p<n.values.length&&(r.values[s]=n.values[p])}return r}const cN=zr((n,e)=>n>e?1:0),h4=Qr(ea,cN,null,"bool"),d4={kernelName:ea,backendName:"cpu",kernelFunc:h4},hN=zr((n,e)=>n>=e?1:0),p4=Qr(Ht,hN,null,"bool"),f4={kernelName:Ht,backendName:"cpu",kernelFunc:p4},dN=zr((n,e)=>n<e?1:0),m4=Qr(Ls,dN,null,"bool"),g4={kernelName:Ls,backendName:"cpu",kernelFunc:m4},pN=zr((n,e)=>n<=e?1:0),y4=Qr($i,pN,null,"bool"),b4={kernelName:$i,backendName:"cpu",kernelFunc:y4};function fN(n,e,t){const r=(e-n)/(t-1),s=Er(t,"float32");s[0]=n;for(let a=1;a<s.length;a++)s[a]=s[a-1]+r;return s}const mN=Zo(n=>Math.log(n)),x4=cc(Ft,mN),w4={kernelName:Ft,backendName:"cpu",kernelFunc:x4};function gN(n,e,t,r){const s=_t(r,j(t));for(let a=0;a<s.length;++a){const i=a*e;let o=n[i];for(let l=0;l<e;++l){const p=n[i+l];(Number.isNaN(p)||p>o)&&(o=p)}s[a]=o}return s}const yN=zr((n,e)=>Math.max(n,e)),v4=Qr(To,yN),k4={kernelName:To,backendName:"cpu",kernelFunc:v4},bN=zr((n,e)=>Math.min(n,e)),N4=Qr(Ri,bN),I4={kernelName:Ri,backendName:"cpu",kernelFunc:N4},gx=zr((n,e)=>n*e),S4=fx((n,e,t,r)=>({real:n*t-e*r,imag:n*r+e*t})),ty=Qr(Di,gx,S4),T4={kernelName:Di,backendName:"cpu",kernelFunc:ty};function xN(n,e,t){const r=Bn(-1,t);return gx([],e,r,n,t)}const E4={kernelName:Co,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e;zt(r,"neg");const s=t.data.get(r.dataId).values,[a,i]=xN(s,r.shape,r.dtype);return t.makeTensorInfo(i,r.dtype,a)}},wN=zr((n,e)=>n!==e?1:0),C4=Qr($o,wN,null,"bool"),$4={kernelName:$o,backendName:"cpu",kernelFunc:C4};function yx(n,e,t,r,s){const a=e.length,i=j(e),o=Ge(e),l=Ge(s),p=_t(t,j(s));for(let c=0;c<i;++c){const h=Fs(c,a,o),d=new Array(h.length);for(let m=0;m<d.length;m++)d[m]=h[r[m]];p[Qs(d,a,l)]=n[c]}return p}function da(n){const{inputs:e,attrs:t,backend:r}=n,{x:s}=e,{perm:a}=t;zt(s,"transpose");const i=s.shape.length,o=new Array(i);for(let p=0;p<o.length;p++)o[p]=s.shape[a[p]];const l=yx(r.data.get(s.dataId).values,s.shape,s.dtype,a,o);return{dataId:r.write(l,o,s.dtype),shape:o,dtype:s.dtype}}const A4={kernelName:Oo,backendName:"cpu",kernelFunc:da};function vN(n,e,t,r){const[s,a]=us(n,r),i=Cs(e,"int32"),o=Er(j(s),i),l=j(a);for(let p=0;p<o.length;++p){const c=p*l;let h=1;for(let d=0;d<l;++d)h*=t[c+d];o[p]=h}return{outVals:o,outShape:s,outDtype:i}}const R4={kernelName:Fi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;zt(s,"prod");const o=s.shape.length,l=Oe(a,s.shape),p=Ir(l,o);let c=l,h=s;const d=[];p!=null&&(h=da({inputs:{x:s},backend:t,attrs:{perm:p}}),d.push(h),c=Or(c.length,o));const m=t.data.get(h.dataId).values,{outVals:g,outShape:y,outDtype:w}=vN(h.shape,h.dtype,m,c);let v=y;return i&&(v=Mr(y,l)),d.forEach(N=>t.disposeIntermediateTensorInfo(N)),t.makeTensorInfo(v,w,g)}};function kN(n,e){const t=n.slice(0,e);for(;t.length<e;)t.push(1);for(let r=e;r<n.length;r++)t[e-1]*=n[r];return t}function NN(n,e,t,r,s,a,i,o){if(n.length===0)throw new Error("paramsNestedSplits must be non empty");if(e[0].length===0)throw new Error("Split tensors must not be scalars");if(function(g,y,w){g.forEach((v,N)=>{if(v<0||v>=w){const T=Fs(N,y.length,Ge(y)).join(",");throw new Error(`indices[${T}] = ${v} is not in [0, ${w})`)}})}(a,i,e[0][0]-1),r.length===0)throw new Error("params.rank must be nonzero");const l=r[0],{outSplits:p,valueSlices:c,numValues:h}=function(g,y,w,v){const N=[];let T=0;const $=y.length-1+w.length,_=new Array($).fill(null).map(()=>[0]);(function(z,O){for(let V=0;V<z.length;++V){const U=z[V],X=V===z.length-1?O:z[V+1].length;if(U.length===0)throw new Error("Ragged splits may not be empty");if(U[0]<0)throw new Error("Ragged splits must be non-negative");if(U[U.length-1]>X)throw new Error("Ragged splits must not point past values");for(let ne=1;ne<U.length;++ne)if(U[ne-1]>U[ne])throw new Error("Ragged splits must be sorted in ascending order")}})(w,v);let L=1;for(let z=0;z<y.length-1;++z){L*=y[z];const O=y[z+1];for(let V=1;V<L+1;++V)_[z].push(V*O)}for(let z=0;z<g.length;++z){let O=g[z],V=g[z]+1;for(let U=0;U<w.length;++U){const X=w[U],ne=U+y.length-1;if(ne>=0){const ae=_[ne],Ie=ae[ae.length-1]-X[O];for(let me=O;me<V;++me)_[ne].push(X[me+1]+Ie)}O=X[O],V=X[V]}V!==O&&(N.push([O,V]),T+=V-O)}return{outSplits:_,valueSlices:N,numValues:T}}(a,i,n,l),d=function(g){const y=[];for(let w=0;w<g.length;++w){const v=Zt("int32",g[w].length);y.push(v),g[w].forEach((N,T)=>v[T]=N)}return y}(p),m=function(g,y,w,v,N){const T=y.slice();T[0]=N;const $=Zt(w,j(T)),_=g.length;return function(L,z,O,V,U,X){const ne=kN(z,2)[1],ae=kN(X,2)[1];let Ie=0;for(const me of O)for(let we=me[0];we<me[1];++we){for(let $e=0;$e<V;++$e)U[Ie*ae+$e]=L[we*ne+$e];++Ie}}(g,y,v,_===0?0:_/y[0],$,T),[$,T]}(t,r,s,c,h);return[d,m[0],m[1]]}const IN=2147483647;function SN(n,e,t,r,s,a,i){if(e.length>1)throw new Error("starts must be a scalar or vector");if(s.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");const o=e.length===0,l=s.length===0,p=i.length===0,c=[];o||c.push(e[0]),l||c.push(s[0]),p||c.push(i[0]);for(let y=1;y<c.length;++y)if(c[y]!==c[y-1])throw new Error("starts, limits, and deltas must have the same shape");const h=c.length===0?1:c[0],d=Zt("int32",h+1);d[0]=0;for(let y=0;y<h;++y){const w=o?n[0]:n[y],v=l?r[0]:r[y],N=p?a[0]:a[y];if(N===0)throw new Error("Requires delta != 0");let T;if(N>0&&v<w||N<0&&v>w)T=0;else if(T=Math.ceil(Math.abs((v-w)/N)),T>IN)throw new Error(`Requires ((limit - start) / delta) <= ${IN}`);d[y+1]=d[y]+T}const m=Zt(t,d[h]);let g=0;for(let y=0;y<h;++y){const w=d[y+1]-d[y];let v=o?n[0]:n[y];const N=p?a[0]:a[y];for(let T=0;T<w;++T)m[g++]=v,v+=N}return[d,m]}var gi=no;class ny{constructor(e,t,r,s,a,i,o,l,p,c){this.shape=e,this.shapeShape=t,this.values=r,this.valuesShape=s,this.valuesDType=a,this.defaultValue=i,this.defaultValueShape=o,this.rowPartitionValues=l,this.rowPartitionValuesShapes=p,this.rowPartitionTypes=a2(c),this.raggedRank=i2(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===gi.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===gi.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case gi.VALUE_ROWIDS:return ny.getMaxWidthValueRowID(t);case gi.ROW_SPLITS:return ny.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${gi[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(t===0||t===1)return 0;let r=0;for(let s=0;s<t-1;++s){const a=e[s+1]-e[s];a>r&&(r=a)}return r}static getMaxWidthValueRowID(e){const t=e.length;if(t===0)return 0;let r=0,s=e[0],a=0;for(let i=1;i<t;++i){const o=e[i];o!==s&&(s=o,a=Math.max(i-r,a),r=i)}return Math.max(t-r,a)}tensorShapeFromTensor(e,t,r=!0){if(t.length===0){if(e[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return EN(e,r)}calculateOutputSize(e){const t=this.valuesShape;o2(this.defaultValueShape,t);const r=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=s2(this.raggedRank,r,t);s[0]<0&&(s[0]=e);for(let a=1;a<=this.raggedRank;++a)s[a]<0&&(s[a]=this.getMaxWidth(a));return s}calculateFirstParentOutputIndex(e,t,r){const s=Math.min(e,r),a=[];let i=0;for(let o=0;o<s;++o,i+=t)a.push(i);for(let o=s;o<e;++o)a.push(-1);return A(a.length===e,()=>"Final length of result must be equal to firstDimension."),a}calculateOutputIndexRowSplit(e,t,r,s){const a=e.length,i=[];for(let o=0;o<a-1;++o){const l=e[o+1]-e[o];let p=Math.min(s,l),c=t[o];c===-1&&(p=0);for(let h=0;h<p;++h)i.push(c),c+=r;for(let h=0;h<l-p;++h)i.push(-1)}if(a>0&&i.length!==e[a-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(e,t,r,s){const a=e.length,i=[];if(a===0)return[];let o=0,l=e[0];if(l>=t.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${t.length}`);let p=t[l];i.push(p);for(let c=1;c<a;++c){const h=e[c];if(h===l)p>=0&&(++o,o<s?p+=r:p=-1);else{if(o=0,l=h,h>=t.length)throw new Error(`Got nextValueRowId=${h} which is not less than ${t.length}`);p=t[h]}i.push(p)}if(i.length!==e.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(e,t,r,s){const a=this.getRowPartitionTensor(e),i=this.getRowPartitionTypeByDimension(e);switch(i){case gi.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,r,s);case gi.ROW_SPLITS:if(a.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${a.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(a,t,r,s);default:throw new Error(`Unsupported partition type: ${gi[i]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case gi.FIRST_DIM_SIZE:return e[0];case gi.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case gi.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${gi[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),r=new Array(this.raggedRank+1);r[r.length-1]=1;for(let i=r.length-2;i>=0;--i)r[i]=r[i+1]*t[i+1];const s=EN(t,!1),a=Zt(this.valuesDType,j(s));if(r[0]*t[0]>0){let i=this.calculateFirstParentOutputIndex(e,r[0],t[0]);for(let o=1;o<=this.raggedRank;++o)i=this.calculateOutputIndex(o-1,i,r[o],t[o]);this.setOutput(this.raggedRank,i,a,s)}return[s,a]}setOutput(e,t,r,s){if(r.length===0)return;const a=this.values,i=r;let o=s.slice();o=o.slice(e+1);const l=j(o),p=t.length;let c=this.defaultValue;if(c.length!==l&&c.length!==1){const g=this.defaultValueShape;be(()=>{const y=he(c,g);c=ch(y,o).dataSync()})}let h=0,d=0,m=0;for(let g=0;g<=p;++g){let y=g<p?t[g]:-1;if(y!==m){if(d<m){const w=a.subarray(h*l);TN(i.subarray(d*l),w,(m-d)*l)}if(g>=p){const w=r.length;y=Math.floor(w/l)}if(y>m)if(this.defaultValue.length===1)i.subarray(m*l,y*l).fill(this.defaultValue[0]),m=y;else for(;y>m;)TN(i.slice(m*l),c,l),++m;y<0?(h=g+1,d=m):(h=g,d=m,m=d+1)}else++m}}}function TN(n,e,t){for(let r=0;r<t;r++)n[r]=e[r]}function EN(n,e){const t=[];for(let r of n){if(r<0){if(!e)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}t.push(r)}return t}function CN(n,e,t,r,s,a,i,o,l,p){return new ny(n,e,t,r,s,a,i,o,l,p).compute()}function $N(n,e,t,r){if(n===e||n<e&&t<0||e<n&&t>1)return Er(0,r);const s=Er(Math.abs(Math.ceil((e-n)/t)),r);e<n&&t===1&&(t=-1),s[0]=n;for(let a=1;a<s.length;a++)s[a]=s[a-1]+t;return s}const AN=Zo(n=>1/Math.sqrt(n)),_4=cc(lu,AN),D4={kernelName:lu,backendName:"cpu",kernelFunc:_4};function ep(n,e,t,r,s,a,i,o,l,p){const c=[r/s,s],h=n.values,d=e.values;if(r===0)return ln(t,e.dtype);const m=l instanceof kr?l:ln(c,e.dtype);typeof l=="string"||typeof l=="number"?m.values.fill(l):typeof l=="boolean"&&m.values.fill(+l);for(let g=0;g<a;g++){const y=[];let w=0;for(let v=0;v<i;v++){const N=h[g*i+v];y.push(N),w+=N*o[v]}if(w<0||w>=r/s)throw new Error(`Invalid indices: ${y} does not index into ${t}`);for(let v=0;v<s;v++)p?m.values[w*s+v]+=d[g*s+v]:m.values[w*s+v]=e.rank===0?d[0]:d[g*s+v]}return m}const F4=Zo(n=>1/(1+Math.exp(-n))),RN=Wn(du,n=>1/(1+Math.exp(-n))),M4={kernelName:du,backendName:"cpu",kernelFunc:RN};function _N(n,e,t,r,s){const a=qt(r,e,t),i=j(t),o=Ge(r);if(a){const c=un(e,o);return s==="string"?n.slice(c,c+i):n.subarray(c,c+i)}const l=ln(r,s,s==="string"?Pu(n):n),p=ln(t,s);for(let c=0;c<p.size;++c){const h=p.indexToLoc(c),d=h.map((m,g)=>m+e[g]);p.set(l.get(...d),...h)}return s==="string"?C2(p.values):p.values}function Ch(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,size:i}=r;zt(s,"slice");const[o,l]=rn(s,a,i);Ed(s,o,l);const p=_N(t.data.get(s.dataId).values,o,l,s.shape,s.dtype);return t.makeTensorInfo(l,s.dtype,p)}const O4={kernelName:Lc,backendName:"cpu",kernelFunc:Ch};function DN(n,e,t,r,s,a,i){const o=e[0],l=a[0],p=new Array(l),c=new Array(o),h=e[1];if(l===0){if(o!==0)throw new Error(g2(o));return[Zt(t,0),[0,h],Zt(s,0),p,c]}let d=!0,m=0;const g=new Array(l).fill(0);for(let w=0;w<o;++w){const v=n[w*h];if(v<0)throw new Error(y2(w,v));if(v>=l)throw new Error(b2(w,v,l));++g[v],d=d&&v>=m,m=v}let y=!0;for(let w=0;w<l;++w){const v=g[w]===0;p[w]=v,y=y&&!v,g[w]=Math.max(g[w],1),w>0&&(g[w]+=g[w-1])}if(y&&d){const w=n,v=r;for(let N=0;N<o;++N)c[N]=N;return[w,[o,h],v,p,c]}{const w=g[l-1],v=Zt(t,w*h),N=Zt(s,w),T=new Array(l).fill(0);for(let $=0;$<o;++$){const _=n[$*h],L=T[_],z=(_===0?0:g[_-1])+L;T[_]++;for(let O=0;O<h;++O)v[z*h+O]=n[$*h+O];N[z]=r[$],c[$]=z}for(let $=0;$<l;++$)if(T[$]===0){const _=$===0?0:g[$-1];v[_*h+0]=$;for(let L=1;L<h;++L)v[_*h+L]=0;N[_]=i}return[v,[w,h],N,p,c]}}function FN(n,e,t,r,s){const a=j(r),i=e[0],o=s.length,l=[];let p=1,c=-1;for(let y=0;y<o;++y){const w=s[y];if(w===-1){if(c!==-1)throw new Error(x2(c,y));c=y,l.push(1)}else{if(w<0)throw new Error(w2(y,w));p*=w,l.push(w)}}if(c!==-1){if(p<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const y=Math.trunc(a/p);if(p*y!==a)throw new Error(v2(r,l));l[c]=y}if(j(l)!==a)throw new Error(k2(r,l));const h=r.length,d=[];if(h>0){d[h-1]=1;for(let y=h-2;y>=0;--y)d[y]=d[y+1]*r[y+1]}const m=[];if(o>0){m[o-1]=1;for(let y=o-2;y>=0;--y)m[y]=m[y+1]*l[y+1]}const g=Zt(t,i*o);for(let y=0;y<i;++y){let w=0;for(let v=0;v<h;++v)w+=n[y*h+v]*d[v];for(let v=0;v<o;++v)g[y*o+v]=Math.trunc(w/m[v]),w%=m[v]}return[g,[i,o],l]}function bx(n,e,t,r,s,a=!1,i=0){const o=r.length,l=[e[0],n.length/e[0]],p=l[1],c=o>0?s[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=e.slice();h[0]=c;const d=Zt(t,h.reduce((v,N)=>v*N,1));if(o===0)return c>0&&d.fill(i),[d,h];if(c<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,y=0,w=s[m];for(;;){let v=0;if(g<o){if(v=s[g],w===v){++g;continue}if(w>=v)throw new Error(N2())}if(w<0||w>=c)throw new Error(I2(w,c));w>y&&d.fill(i,y*p,w*p);for(let N=m;N<g;++N){const T=r[N];if(T<0||T>=l[0])throw new Error(S2(N,r[N],l[0]));for(let $=0;$<p;$++)d[w*p+$]+=n[T*p+$]}if(a)for(let N=0;N<p;N++)d[w*p+N]/=g-m;if(m=g,++g,y=w+1,w=v,g>o)break}return y<c&&d.fill(i,y*p,c*p),[d,h]}const L4=Zo(n=>Math.sqrt(n)),z4=Wn(fu,n=>Math.sqrt(n)),P4={kernelName:fu,backendName:"cpu",kernelFunc:z4},MN=zr((n,e)=>{const t=n-e;return t*t}),B4=Qr(bu,MN),V4={kernelName:bu,backendName:"cpu",kernelFunc:B4},ON=Zo((n,e)=>{const{pattern:t,replaceGlobal:r,rewrite:s}=e;return n.replace(new RegExp(t,r?"g":""),s)}),U4=cc(Al,ON),W4={kernelName:Al,backendName:"cpu",kernelFunc:U4};function LN(n,e,t,r){const s=ln(n,e.dtype);for(let a=0;a<s.size;a++){const i=s.indexToLoc(a),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*t[l]+r[l];s.set(e.get(...o),...i)}return s}class G4{constructor(e,t,r,s,a,i){this.separator=dn(e),this.nGramWidths=t,this.leftPad=dn(r),this.rightPad=dn(s),this.padWidth=a,this.preserveShort=i}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const r=this.getPadWidth(t);return Math.max(0,e+2*r-t+1)}createNGrams(e,t,r,s,a,i){for(let o=0;o<a;++o){const l=this.getPadWidth(i),p=Math.max(0,l-o),c=Math.max(0,l-(a-(o+1))),h=i-(p+c),d=t+(p>0?0:o-l);let m=0;m+=p*this.leftPad.length;for(let v=0;v<h;++v)m+=e[d+v].length;m+=c*this.rightPad.length,m+=(p+c+h-1)*this.separator.length,r[s+o]=new Uint8Array(m);const g=r[s+o];let y=0;const w=v=>v.forEach(N=>g[y++]=N);for(let v=0;v<p;++v)w(this.leftPad),w(this.separator);for(let v=0;v<h-1;++v)w(e[d+v]),w(this.separator);if(h>0){w(e[d+h-1]);for(let v=0;v<c;++v)w(this.separator),w(this.rightPad)}else{for(let v=0;v<c-1;++v)w(this.rightPad),w(this.separator);w(this.rightPad)}}}compute(e,t){const r=e.length,s=t.length;if(s>0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let p=1;p<s;++p){let c=t[p]>=l;if(c=c&&t[p]<=r,!c)throw new Error(`Invalid split value ${t[p]}, must be in [${l}, ${r}]`);l=t[p]}if(l!==r)throw new Error(`Last split value must be data size. Expected ${r}, got ${l}`)}const a=s-1,i=Zt("int32",s);if(r===0||s===0){const l=new Array(r);for(let p=0;p<=a;++p)i[p]=0;return[l,i]}i[0]=0;for(let l=1;l<=a;++l){const p=t[l]-t[l-1];let c=0;this.nGramWidths.forEach(h=>{c+=this.getNumNGrams(p,h)}),this.preserveShort&&p>0&&c===0&&(c=1),i[l]=i[l-1]+c}const o=new Array(i[a]);for(let l=0;l<a;++l){const p=t[l];let c=i[l];if(this.nGramWidths.forEach(h=>{const d=t[l+1]-t[l],m=this.getNumNGrams(d,h);this.createNGrams(e,p,o,c,m,h),c+=m}),this.preserveShort&&c===i[l]){const h=t[l+1]-t[l];if(h===0)continue;const d=h+2*this.padWidth;this.createNGrams(e,p,o,c,1,d)}}return[o,i]}}function zN(n,e,t,r,s,a,i,o){return new G4(t,r,s,a,i,o).compute(n,e)}function H4(n,e,t,r){if(!n.length)return;if(e.length===0){for(let a=0;a<n.length;++a)r.push(n.subarray(a,a+1));return}if(e.length===1){const a=e[0];let i=n.indexOf(a);for(;i!==-1;){const o=n.subarray(0,i);t&&o.length===0||r.push(o),i=(n=n.subarray(i+1)).indexOf(a)}return void(t&&n.length===0||r.push(n))}let s=0;for(let a=0;a<n.length+1;a++)if(a===n.length||e.indexOf(n[a])!==-1){const i=n.subarray(s,a);t&&i.length===0||r.push(i),s=a+1}}function PN(n,e,t){const r=n.length,s=[];let a=0,i=0;const o=new Array(r);for(let d=0;d<r;++d){const m=s.length;H4(n[d],e,t,s);const g=s.length-m;o[d]=g,a+=g,i=Math.max(i,g)}const l=Zt("int32",2*a),p=new Array(a),c=[r,i];let h=0;for(let d=0;d<r;++d)for(let m=0;m<o[d];++m)l[2*h]=d,l[2*h+1]=m,p[h]=s[h],++h;return[l,p,c]}function BN(n,e){const t=Zt("int32",n.length);for(let r=0;r<n.length;++r)t[r]=Ps(n[r]).modulo(e).getLowBitsUnsigned();return t}const VN=zr((n,e)=>n-e),j4=fx((n,e,t,r)=>({real:n-t,imag:e-r})),xx=Qr(Rl,VN,j4),K4={kernelName:Rl,backendName:"cpu",kernelFunc:xx};function UN(n,e){const t=new Array(n.rank);for(let s=0;s<t.length;s++)t[s]=n.shape[s]*e[s];const r=ln(t,n.dtype);for(let s=0;s<r.values.length;++s){const a=r.indexToLoc(s),i=new Array(n.rank);for(let l=0;l<i.length;l++)i[l]=a[l]%n.shape[l];const o=n.locToIndex(i);r.values[s]=n.values[o]}return r}const Mf=(n,e)=>{const t=e.value-n.value;return t===0?n.index-e.index:t};function WN(n,e,t=0,r=n.length-1){for(;r>t;){if(r-t>600){const o=r-t+1,l=e-t+1,p=Math.log(o),c=.5*Math.exp(2*p/3),h=.5*Math.sqrt(p*c*(o-c)/o)*Math.sign(l-o/2);WN(n,e,Math.max(t,Math.floor(e-l*c/o+h)),Math.min(r,Math.floor(e+(o-l)*c/o+h)))}const s=n[e];let a=t,i=r;for(Ae(n,t,e),Mf(n[r],s)>0&&Ae(n,t,r);a<i;){for(Ae(n,a,i),a++,i--;Mf(n[a],s)<0;)a+=1;for(;Mf(n[i],s)>0;)i-=1}Mf(n[t],s)===0?Ae(n,t,i):(i+=1,Ae(n,i,r)),i<=e&&(t=i+1),e<=i&&(r=i-1)}}function GN(n,e,t,r,s){const a=e[e.length-1],[i,o]=[n.length/a,a],l=_t(t,i*r),p=_t("int32",i*r);for(let h=0;h<i;h++){const d=h*o,m=n.subarray(d,d+o);let g=new Array(m.length);m.forEach((N,T)=>g[T]={value:N,index:T}),r<g.length&&(WN(g,r),g=g.slice(0,r)),s&&g.sort(Mf);const y=h*r,w=l.subarray(y,y+r),v=p.subarray(y,y+r);for(let N=0;N<r;N++)w[N]=g[N].value,v[N]=g[N].index}const c=e.slice();return c[c.length-1]=r,[ln(c,t,l),ln(c,"int32",p)]}function HN(n,e,t,r){const s=Oe(e,t)[0],a=[1,t[0],1];for(let g=0;g<s;g++)a[0]*=t[g];a[1]=t[s];for(let g=s+1;g<t.length;g++)a[2]*=t[g];const i=new Map,o=new Int32Array(t[s]),l=new kr(a,r,n),p=[],c=a[0]===1&&a[2]===1;for(let g=0;g<t[s];g++){let y;if(c)y=n[g].toString();else{const v=[];for(let N=0;N<a[0];N++)for(let T=0;T<a[2];T++)v.push(l.get(N,g,T));y=v.join(",")}const w=i.get(y);if(w!=null)o[g]=w;else{const v=i.size;i.set(y,v),o[g]=v,p.push(g)}}const h=a.slice();h[1]=i.size;const d=new kr(h,r);p.forEach((g,y)=>{for(let w=0;w<a[0];w++)for(let v=0;v<a[2];v++)d.set(l.get(w,g,v),w,y,v)});const m=t.slice();return m[s]=h[1],{outputValues:d.values,outputShape:m,indices:o}}const jN="4.22.0";Tp("cpu",()=>new Ff,1);const KN=Wn(fa,n=>n>=0?n:Math.exp(n)-1),q4={kernelName:fa,backendName:"cpu",kernelFunc:KN};function qN(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{alpha:a}=r;zt([s],"leakyRelu");const i=j(s.shape),o=t.data.get(s.dataId).values,l=_t("float32",i);for(let p=0;p<o.length;p++)l[p]=o[p]<0?a*o[p]:o[p];return t.makeTensorInfo(s.shape,"float32",l)}const X4={kernelName:rr,backendName:"cpu",kernelFunc:qN},Y4=zr((n,e)=>n<0?e*n:n);function XN(n){const{inputs:e,backend:t}=n,{x:r,alpha:s}=e;zt([r,s],"prelu");const a=t.data.get(r.dataId).values,i=t.data.get(s.dataId).values,[o,l]=Y4(r.shape,s.shape,a,i,"float32");return t.makeTensorInfo(l,"float32",o)}const Z4={kernelName:ti,backendName:"cpu",kernelFunc:XN},YN=Wn(Oi,n=>Math.max(0,n)),Q4={kernelName:Oi,backendName:"cpu",kernelFunc:YN},ZN=Wn(Do,n=>Math.min(Math.max(0,n),6)),J4={kernelName:Do,backendName:"cpu",kernelFunc:ZN};
93function ry(n,e,t,r,s){if(t==="linear")return Yo({inputs:{x:e},backend:n});if(t==="relu")return YN({inputs:{x:e},backend:n});if(t==="elu")return KN({inputs:{x:e},backend:n});if(t==="relu6")return ZN({inputs:{x:e},backend:n});if(t==="prelu")return XN({inputs:{x:e,alpha:r},backend:n});if(t==="leakyrelu")return qN({inputs:{x:e},backend:n,attrs:{alpha:s}});if(t==="sigmoid")return RN({inputs:{x:e},backend:n});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}function or(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{shape:a}=r,i=j(s.shape),o=Le(a,i),l=j(o);A(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),t.incRef(s.dataId);const p=t.data.get(s.dataId);if(p.complexTensorInfos!=null){const c=p.complexTensorInfos.real,h=p.complexTensorInfos.imag;c.shape=o,h.shape=o}return{dataId:s.dataId,shape:o,dtype:s.dtype}}const eR={kernelName:_o,backendName:"cpu",kernelFunc:or};function QN(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a}=e,{transposeA:i,transposeB:o}=r;zt([s,a],"matMul");const l=s.shape.length,p=a.shape.length,c=i?s.shape[l-2]:s.shape[l-1],h=o?a.shape[p-1]:a.shape[p-2],d=i?s.shape[l-1]:s.shape[l-2],m=o?a.shape[p-2]:a.shape[p-1],g=s.shape.slice(0,-2),y=a.shape.slice(0,-2),w=j(g),v=j(y),N=Gt(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,m]);A(c===h,()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`);const T=o?[v,m,h]:[v,h,m],$=or({inputs:{x:s},backend:t,attrs:{shape:i?[w,c,d]:[w,d,c]}}),_=or({inputs:{x:a},backend:t,attrs:{shape:T}}),L=i?$.shape[1]:$.shape[2],z=i?$.shape[2]:$.shape[1],O=o?_.shape[1]:_.shape[2],V=Math.max(w,v),U=t.data.get($.dataId).values,X=t.data.get(_.dataId).values,ne=Ge($.shape),ae=Ge(_.shape),[Ie,me,we]=i?[ne[0],1,ne[1]]:[ne[0],ne[1],1],[$e,ze,We]=o?[1,ae[1],ae[0]]:[ae[1],1,ae[0]],Je=z*O,nt=ln([V,z,O],$.dtype),lt=nt.values,dt=t.blockSize;for(let yt=0;yt<V;yt++){const xt=yt%w,Ct=yt%v;for(let Rt=0;Rt<z;Rt+=dt){const tn=Math.min(Rt+dt,z);for(let nn=0;nn<O;nn+=dt){const pn=Math.min(nn+dt,O);for(let Xt=0;Xt<L;Xt+=dt){const vn=Math.min(Xt+dt,L);for(let kn=Rt;kn<tn;kn++)for(let Ln=nn;Ln<pn;Ln++){let Nn=0;for(let wn=Xt;wn<vn;wn++)Nn+=U[xt*Ie+kn*me+wn*we]*X[wn*$e+Ln*ze+Ct*We];lt[yt*Je+(kn*O+Ln)]+=Nn}}}}}return t.disposeIntermediateTensorInfo($),t.disposeIntermediateTensorInfo(_),t.makeTensorInfo(N,nt.dtype,nt.values)}const tR={kernelName:yo,backendName:"cpu",kernelFunc:QN},nR={kernelName:Jn,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a,bias:i,preluActivationWeights:o}=e,{transposeA:l,transposeB:p,activation:c,leakyreluAlpha:h}=r;let d,m,g;const y=[];d=QN({inputs:{a:s,b:a},attrs:{transposeA:l,transposeB:p},backend:t}),i&&(m=Jd({inputs:{a:d,b:i},backend:t}),y.push(d),d=m),c&&(g=ry(t,d,c,o,h),y.push(d),d=g);for(const w of y)t.disposeIntermediateTensorInfo(w);return d}},rR=Wn(Da,n=>Math.acos(n)),sR={kernelName:Da,backendName:"cpu",kernelFunc:rR},aR=Wn(Js,n=>Math.acosh(n)),iR={kernelName:Js,backendName:"cpu",kernelFunc:aR},oR={kernelName:yc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,r=e;zt(e,"addN");const s=r.map(o=>t.data.get(o.dataId).values),a=ln(r[0].shape,r[0].dtype),i=a.values;for(let o=0;o<r.length;o++){const l=s[o];for(let p=0;p<i.length;p++)i[p]+=l[p]}return t.makeTensorInfo(a.shape,a.dtype,a.values)}},uR={kernelName:bc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;zt(s,"all");const o=Oe(a,s.shape);let l=o;const p=Ir(l,s.shape.length);let c=s;p!=null&&(c=da({inputs:{x:s},backend:t,attrs:{perm:p}}),l=Or(l.length,s.shape.length)),xs("all",l,c.shape.length);const[h,d]=us(c.shape,l),m=j(d),g=Er(j(h),c.dtype),y=t.data.get(c.dataId).values;for(let v=0;v<g.length;++v){const N=v*m;let T=y[N];for(let $=0;$<m;++$){const _=y[N+$];T=T&&_}g[v]=T}p!=null&&t.disposeIntermediateTensorInfo(c);const w=t.makeTensorInfo(h,c.dtype,g);if(i){const v=or({inputs:{x:w},backend:t,attrs:{shape:Mr(h,o)}});return t.disposeIntermediateTensorInfo(w),v}return w}},lR={kernelName:xi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;zt(s,"any");const o=Oe(a,s.shape);let l=o;const p=Ir(l,s.shape.length);let c=s;p!=null&&(c=da({inputs:{x:s},backend:t,attrs:{perm:p}}),l=Or(l.length,s.shape.length)),xs("any",l,c.shape.length);const[h,d]=us(c.shape,l),m=j(d),g=Er(j(h),c.dtype),y=t.data.get(c.dataId).values;for(let v=0;v<g.length;++v){const N=v*m;let T=y[N];for(let $=0;$<m;++$){const _=y[N+$];T=T||_}g[v]=T}
93p!=null&&t.disposeIntermediateTensorInfo(c);const w=t.makeTensorInfo(h,c.dtype,g);if(i){const v=or({inputs:{x:w},backend:t,attrs:{shape:Mr(h,o)}});return t.disposeIntermediateTensorInfo(w),v}return w}},cR={kernelName:Zu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;zt(s,"argMax");let i=Oe(a,s.shape);const o=Ir(i,s.shape.length);let l=s;const p=[];o!=null&&(l=da({inputs:{x:s},backend:t,attrs:{perm:o}}),p.push(l),i=Or(i.length,l.shape.length)),i=[i[0]],xs("argMax",i,l.shape.length);const[c,h]=us(l.shape,i),d=Er(j(c),"int32"),m=j(h),g=t.data.get(l.dataId).values;for(let y=0;y<d.length;++y){const w=y*m;let v=g[w],N=0;for(let T=0;T<m;++T){const $=g[w+T];$>v&&(v=$,N=T)}d[y]=N}return p.forEach(y=>t.disposeIntermediateTensorInfo(y)),t.makeTensorInfo(c,"int32",d)}},hR={kernelName:wi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;zt(s,"argMin");let i=Oe(a,s.shape);const o=Ir(i,s.shape.length);let l=s;const p=[];o!=null&&(l=da({inputs:{x:s},backend:t,attrs:{perm:o}}),p.push(l),i=Or(i.length,l.shape.length)),i=[i[0]],xs("argMin",i,l.shape.length);const[c,h]=us(l.shape,i),d=Er(j(c),"int32"),m=j(h),g=t.data.get(l.dataId).values;for(let y=0;y<d.length;++y){const w=y*m;let v=g[w],N=0;for(let T=0;T<m;++T){const $=g[w+T];$<v&&(v=$,N=T)}d[y]=N}return p.forEach(y=>t.disposeIntermediateTensorInfo(y)),t.makeTensorInfo(c,"int32",d)}},dR=Wn(pa,n=>Math.asin(n)),pR={kernelName:pa,backendName:"cpu",kernelFunc:dR},fR=Wn(go,n=>Math.asinh(n)),mR={kernelName:go,backendName:"cpu",kernelFunc:fR},gR=Wn(Za,n=>Math.atan(n)),yR={kernelName:Za,backendName:"cpu",kernelFunc:gR},bR=zr((n,e)=>Math.atan2(n,e)),xR=Qr(Jo,bR),wR={kernelName:Jo,backendName:"cpu",kernelFunc:xR},vR=Wn(vi,n=>Math.atanh(n)),kR={kernelName:vi,backendName:"cpu",kernelFunc:vR};function wx(n,e,t,r,s,a){const i=s.strideHeight,o=s.strideWidth,l=s.dilationHeight,p=s.dilationWidth,c=s.effectiveFilterHeight,h=s.effectiveFilterWidth,d=s.padInfo.top,m=s.padInfo.left,g=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,y=ln(s.outShape,t),w=y.values,v=s.outShape[1]*s.outShape[2]*s.outShape[3],N=s.outShape[2]*s.outShape[3],T=s.outShape[3];for(let $=0;$<s.batchSize;++$){const _=$*v,L=$*r[0];for(let z=0;z<s.inChannels;++z)for(let O=0;O<s.outHeight;++O){const V=O*i-d,U=Math.max(0,V),X=Math.min(s.inHeight,c+V),ne=_+O*N;for(let ae=0;ae<s.outWidth;++ae){const Ie=ae*o-m,me=Math.max(0,Ie),we=Math.min(s.inWidth,h+Ie);let $e=g,ze=0,We=0;for(let Je=U;Je<X;Je+=l){const nt=L+Je*r[1];for(let lt=me;lt<we;lt+=p){const dt=n[nt+lt*r[2]+z];a==="max"&&dt>$e?$e=dt:a==="avg"&&(ze+=dt,We++)}if(isNaN($e))break}w[ne+ae*T+z]=a==="avg"?ze/We:$e}}}return y}function JN(n,e,t,r,s=!1,a=!1){const i=ln(r.outShape,"int32"),o=r.strideHeight,l=r.strideWidth,p=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterHeight,d=r.effectiveFilterWidth,m=r.padInfo.top,g=r.padInfo.left,y=ln(e,t,n);for(let w=0;w<r.batchSize;++w)for(let v=0;v<r.inChannels;++v)for(let N=0;N<r.outHeight;++N){const T=N*o-m;let $=T;for(;$<0;)$+=p;const _=Math.min(r.inHeight,h+T);for(let L=0;L<r.outWidth;++L){const z=L*l-g;let O=z;for(;O<0;)O+=c;const V=Math.min(r.inWidth,d+z);let U=Number.NEGATIVE_INFINITY,X=-1;for(let ne=$;ne<_;ne+=p){const ae=ne-T;for(let Ie=O;Ie<V;Ie+=c){const me=Ie-z,we=y.get(w,ne,Ie,v);we>U&&(U=we,X=s?a?((w*r.inHeight+ne)*r.inWidth+Ie)*r.inChannels+v:(ne*r.inWidth+Ie)*r.inChannels+v:ae*d+me)}}i.set(X,w,N,L,v)}}return i}function eI(n,e,t,r,s,a){const i=s.strideDepth,o=s.strideHeight,l=s.strideWidth,p=s.dilationDepth,c=s.dilationHeight,h=s.dilationWidth,d=s.effectiveFilterDepth,m=s.effectiveFilterHeight,g=s.effectiveFilterWidth,y=s.padInfo.front,w=s.padInfo.top,v=s.padInfo.left,N=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,T=ln(s.outShape,t),$=T.values,_=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],L=s.outShape[2]*s.outShape[3]*s.outShape[4],z=s.outShape[3]*s.outShape[4],O=s.outShape[4];for(let V=0;V<s.batchSize;++V){const U=V*_,X=V*r[0];for(let ne=0;ne<s.inChannels;++ne)for(let ae=0;ae<s.outDepth;++ae){const Ie=ae*i-y;let me=Ie;for(;me<0;)me+=p;const we=Math.min(s.inDepth,d+Ie),$e=U+ae*L;for(let ze=0;ze<s.outHeight;++ze){const We=ze*o-w;let Je=We;for(;Je<0;)Je+=c;const nt=Math.min(s.inHeight,m+We),lt=$e+ze*z;for(let dt=0;dt<s.outWidth;++dt){const yt=dt*l-v;let xt=yt;
93for(;xt<0;)xt+=h;const Ct=Math.min(s.inWidth,g+yt),Rt=lt+dt*O;let tn=N,nn=0,pn=0;for(let Xt=me;Xt<we;Xt+=p){const vn=X+Xt*r[1];for(let kn=Je;kn<nt;kn+=c){const Ln=vn+kn*r[2];for(let Nn=xt;Nn<Ct;Nn+=h){const wn=n[Ln+Nn*r[3]+ne];if(a==="max"&&wn>tn?tn=wn:a==="avg"&&(nn+=wn,pn++),isNaN(tn))break}if(isNaN(tn))break}if(isNaN(tn))break}$[Rt+ne]=a==="avg"?nn/Math.max(pn,1):tn}}}}return T}const NR={kernelName:xc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e;zt(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;A(bs(i,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`);const p=li(s.shape,a,i,1,o,l);let c;if(p.filterWidth===1&&p.filterHeight===1&&le(p.inShape,p.outShape))c=Yo({inputs:{x:s},backend:t});else{const h=t.data.get(s.dataId).values,d=Ge(s.shape),m=wx(h,s.shape,s.dtype,d,p,"avg");c=t.makeTensorInfo(p.outShape,s.dtype,m.values)}return c}},IR={kernelName:Qu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=r;zt(s,"avgPool3d");const c=_u(s.shape,a,i,1,o,l,p),h=eI(t.data.get(s.dataId).values,s.shape,s.dtype,Ge(s.shape),c,"avg");return t.makeTensorInfo(h.shape,"float32",h.values)}},SR={kernelName:Ju,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=r;zt([s,a],"avgPool3DGrad");const c=_u(a.shape,i,o,1,l,p),h=c.strideDepth,d=c.strideHeight,m=c.strideWidth,g=c.filterDepth,y=c.filterHeight,w=c.filterWidth,v=c.dilationDepth,N=c.dilationHeight,T=c.dilationWidth,$=c.effectiveFilterDepth,_=c.effectiveFilterHeight,L=c.effectiveFilterWidth,z=$-1-c.padInfo.front,O=L-1-c.padInfo.left,V=_-1-c.padInfo.top,U=ln(a.shape,"float32"),X=1/(g*y*w),ne=t.bufferSync(s);for(let ae=0;ae<c.batchSize;++ae)for(let Ie=0;Ie<c.inChannels;++Ie)for(let me=0;me<c.inDepth;++me)for(let we=0;we<c.inHeight;++we)for(let $e=0;$e<c.inWidth;++$e){const ze=me-z,We=we-V,Je=$e-O;let nt=0;for(let lt=0;lt<$;lt+=v){const dt=(ze+lt)/h;if(!(dt<0||dt>=c.outDepth||Math.floor(dt)!==dt))for(let yt=0;yt<_;yt+=N){const xt=(We+yt)/d;if(!(xt<0||xt>=c.outHeight||Math.floor(xt)!==xt))for(let Ct=0;Ct<L;Ct+=T){const Rt=(Je+Ct)/m;Rt<0||Rt>=c.outWidth||Math.floor(Rt)!==Rt||(nt+=ne.get(ae,dt,xt,Rt,Ie))}}}U.set(nt*X,ae,me,we,$e,Ie)}return t.makeTensorInfo(U.shape,U.dtype,U.values)}},TR={kernelName:wc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,i=a;zt([s,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:p}=r,c=li(i.shape,o,l,1,p),h=c.strideHeight,d=c.strideWidth,m=c.filterHeight,g=c.filterWidth,y=c.dilationHeight,w=c.dilationWidth,v=c.effectiveFilterHeight,N=c.effectiveFilterWidth,T=N-1-c.padInfo.left,$=v-1-c.padInfo.top,_=ln(i.shape,"float32"),L=1/(m*g),z=t.data.get(s.dataId).values,O=ln(s.shape,"float32",z);for(let V=0;V<c.batchSize;++V)for(let U=0;U<c.inChannels;++U)for(let X=0;X<c.inHeight;++X)for(let ne=0;ne<c.inWidth;++ne){const ae=X-$,Ie=ne-T;let me=0;for(let we=0;we<v;we+=y){const $e=(ae+we)/h;if(!($e<0||$e>=c.outHeight||Math.floor($e)!==$e))for(let ze=0;ze<N;ze+=w){const We=(Ie+ze)/d;We<0||We>=c.outWidth||Math.floor(We)!==We||(me+=O.get(V,$e,We,U))}}_.set(me*L,V,X,ne,U)}return t.makeTensorInfo(_.shape,_.dtype,_.values)}},ER={kernelName:hl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,scale:a,offset:i,mean:o,variance:l}=e;A(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),zt([s,o,l,a,i],"batchNorm");let{varianceEpsilon:p}=r;p==null&&(p=.001);const c=t.data.get(s.dataId).values,h=t.data.get(o.dataId).values,d=t.data.get(l.dataId).values,m=a?t.data.get(a.dataId).values:new Float32Array([1]),g=i?t.data.get(i.dataId).values:new Float32Array([0]),y=new Float32Array(c.length),w=g.length,v=m.length,N=d.length,T=h.length;let $=0,_=0,L=0,z=0;for(let O=0;O<c.length;++O)y[O]=g[$++]+(c[O]-h[_++])*m[L++]/Math.sqrt(d[z++]+p),$>=w&&($=0),_>=T&&(_=0),L>=v&&(L=0),z>=N&&(z=0);return t.makeTensorInfo(s.shape,s.dtype,y)}},CR={kernelName:el,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}
93=e,{blockShape:a,crops:i}=r;zt([s],"batchToSpaceND");const o=a.reduce((v,N)=>v*N),l=pf(s.shape,a,o),p=ff(l.length,a.length),c=mf(s.shape,a,o),h=U0(i,a.length),d=W0(c,i,a.length),m=or({inputs:{x:s},backend:t,attrs:{shape:l}}),g=da({inputs:{x:m},backend:t,attrs:{perm:p}}),y=or({inputs:{x:g},backend:t,attrs:{shape:c}}),w=Ch({inputs:{x:y},backend:t,attrs:{begin:h,size:d}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),w}},$R={kernelName:eu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:i}=r,o=mx(t.data.get(s.dataId).values,t.data.get(a.dataId).values,a.dtype,a.shape,i);return t.makeTensorInfo([i],a.dtype,o)}},AR={kernelName:vc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{s0:r,s1:s}=e,a=t.data.get(r.dataId).values,i=t.data.get(s.dataId).values,o=Gt(Array.from(a),Array.from(i));return t.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},RR=Wn(bo,(n,e)=>{const t=e;return n>t.clipValueMax?t.clipValueMax:n<t.clipValueMin?t.clipValueMin:n}),_R={kernelName:bo,backendName:"cpu",kernelFunc:RR},DR={kernelName:rl,backendName:"cpu",kernelFunc:n=>{const{x:e}=n.inputs,t=n.backend,r=new Float32Array(j(e.shape)),s=t.data.get(e.dataId),a=s.complexTensorInfos.real,i=s.complexTensorInfos.imag,o=t.data.get(a.dataId).values,l=t.data.get(i.dataId).values;for(let p=0;p<o.length;p++){const c=o[p],h=l[p];r[p]=Math.hypot(c,h)}return t.makeOutput(r,e.shape,"float32")}};function tp(n){const{inputs:e,backend:t}=n,{input:r}=e,s=t.data.get(r.dataId).complexTensorInfos.imag,a=t.data.get(s.dataId).values;return t.makeTensorInfo(s.shape,s.dtype,a)}const FR={kernelName:Ei,backendName:"cpu",kernelFunc:tp};function np(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r,a=Oe(s,e[0].shape)[0];P0(e.map(g=>g.shape),a);let i=jo(e.map(g=>g.shape),a);if(j(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);const o=e.filter(g=>j(g.shape)>0);if(o.length===1)return Yo({inputs:{x:o[0]},backend:t});if(o[0].dtype==="complex64"){const g=o.map(T=>Eh({inputs:{input:T},backend:t})),y=o.map(T=>tp({inputs:{input:T},backend:t})),w=np({inputs:g,backend:t,attrs:{axis:a}}),v=np({inputs:y,backend:t,attrs:{axis:a}}),N=Aa({inputs:{real:w,imag:v},backend:t});return g.forEach(T=>t.disposeIntermediateTensorInfo(T)),y.forEach(T=>t.disposeIntermediateTensorInfo(T)),t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(v),N}const l=o.map(g=>{const y=j(g.shape.slice(a));return or({inputs:{x:g},backend:t,attrs:{shape:[-1,y]}})}),p=l.map(g=>({vals:t.data.get(g.dataId).values,shape:g.shape}));i=jo(l.map(g=>g.shape),1);const c=l[0].shape[0]===1,h=eN(p,i,e[0].dtype,c),d=jo(o.map(g=>g.shape),a),m=t.makeTensorInfo(d,e[0].dtype,h);return l.forEach(g=>t.disposeIntermediateTensorInfo(g)),m}const MR={kernelName:tu,backendName:"cpu",kernelFunc:np};function tI(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dataFormat:l,dilations:p,dimRoundingMode:c}=r;zt([s,a],"conv2d");const h=Du(l),d=is(s.shape,a.shape,i,p,o,c,!1,h),m=d.filterHeight,g=d.filterWidth,y=d.dilationHeight,w=d.dilationWidth,v=d.padInfo.left,N=d.padInfo.top,T=d.dataFormat==="channelsLast",$=new kr(d.outShape,s.dtype),_=Ge(s.shape),L=Ge(a.shape),z=_[0],O=T?_[1]:_[2],V=T?_[2]:1,U=T?1:_[1],X=$.strides[0],ne=T?$.strides[1]:$.strides[2],ae=T?$.strides[2]:1,Ie=T?1:$.strides[1],me=t.data.get(s.dataId).values,we=t.data.get(a.dataId).values,$e=$.values;for(let ze=0;ze<d.batchSize;++ze){const We=ze*z,Je=ze*X;for(let nt=0;nt<d.outHeight;++nt){const lt=Je+nt*ne,dt=nt*d.strideHeight-N;for(let yt=0;yt<m;++yt){const xt=dt+yt*y;if(xt<0||xt>=d.inHeight)continue;const Ct=yt*L[0],Rt=We+xt*O;for(let tn=0;tn<d.outWidth;++tn){const nn=lt+tn*ae,pn=tn*d.strideWidth-v;for(let Xt=0;Xt<g;++Xt){const vn=pn+Xt*w;if(vn<0||vn>=d.inWidth)continue;const kn=Rt+vn*V;let Ln=Ct+Xt*L[1];for(let Nn=0;Nn<d.inChannels;++Nn){const wn=me[kn+Nn*U];for(let Gn=0;Gn<d.outChannels;++Gn)$e[nn+Gn*Ie]+=wn*we[Ln+Gn];Ln+=d.outChannels}}}}}}return t.makeTensorInfo($.shape,$.dtype,$e)}const OR={kernelName:ds,backendName:"cpu",kernelFunc:tI},LR={kernelName:Gh,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,pad:o,dataFormat:l,dimRoundingMode:p,filterShape:c}=r;zt([s,a],"conv2dBackpropFilter");const h=Du(l),d=is(s.shape,c,i,1,o,p,!1,h),{strideHeight:m,strideWidth:g,filterHeight:y,filterWidth:w}=d,v=d.dataFormat==="channelsLast",N=new kr(d.filterShape,"float32"),T=d.padInfo.left,$=d.padInfo.top,_=t.data.get(s.dataId).values,L=t.data.get(a.dataId).values,z=new kr(s.shape,s.dtype,_),O=new kr(a.shape,a.dtype,L);for(let V=0;V<y;++V){const U=Math.max(0,Math.ceil(($-V)/m)),X=Math.min(d.outHeight,(d.inHeight+$-V)/m);for(let ne=0;ne<w;++ne){const ae=Math.max(0,Math.ceil((T-ne)/g)),Ie=Math.min(d.outWidth,(d.inWidth+T-ne)/g);for(let me=0;me<d.inChannels;++me)for(let we=0;we<d.outChannels;++we){let $e=0;for(let ze=0;ze<d.batchSize;++ze)for(let We=U;We<X;++We){const Je=V+We*m-$;for(let nt=ae;nt<Ie;++nt){const lt=ne+nt*g-T;$e+=v?z.get(ze,Je,lt,me)*O.get(ze,We,nt,we):z.get(ze,me,Je,lt)*O.get(ze,we,We,nt)}}N.set($e,V,ne,me,we)}}}return t.makeTensorInfo(N.shape,N.dtype,N.values)}},zR={kernelName:sl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{inputShape:i,strides:o,pad:l,dataFormat:p,dimRoundingMode:c}=r;zt([s,a],"conv2dBackpropInput");const h=Ge(a.shape),d=Ge(s.shape);let m=Du(p);const g=is(i,a.shape,o,1,l,c,!1,m),y=new kr(g.inShape,"float32"),w=y.values,v=t.data.get(s.dataId).values,N=t.data.get(a.dataId).values,[T,$,_]=h,{batchSize:L,filterHeight:z,filterWidth:O,
vendor: 14,139 bytes, line 93
93inChannels:V,inHeight:U,inWidth:X,outChannels:ne,outHeight:ae,outWidth:Ie,strideHeight:me,strideWidth:we}=g;m=g.dataFormat;const $e=z-1-g.padInfo.top,ze=O-1-g.padInfo.left,We=m==="channelsLast",Je=y.strides[0],nt=We?y.strides[1]:y.strides[2],lt=We?y.strides[2]:1,dt=We?1:y.strides[1],yt=d[0],xt=We?d[1]:d[2],Ct=We?d[2]:1,Rt=We?1:d[1];for(let tn=0;tn<L;++tn)for(let nn=0;nn<V;++nn)for(let pn=0;pn<U;++pn){const Xt=pn-$e,vn=Math.max(0,Math.ceil(Xt/me)),kn=Math.min(ae,(z+Xt)/me);for(let Ln=0;Ln<X;++Ln){const Nn=Ln-ze,wn=Math.max(0,Math.ceil(Nn/we)),Gn=Math.min(Ie,(O+Nn)/we);let hs=0;for(let Pr=vn;Pr<kn;++Pr){const Ys=Pr*me-Xt;for(let Jr=wn;Jr<Gn;++Jr){const zh=yt*tn+xt*Pr+Ct*Jr,Xa=T*(z-1-Ys)+$*(O-1-(Jr*we-Nn))+_*nn;for(let po=0;po<ne;++po)hs+=v[zh+Rt*po]*N[Xa+po]}}w[Je*tn+nt*pn+lt*Ln+dt*nn]=hs}}return t.makeTensorInfo(y.shape,y.dtype,y.values)}},PR={kernelName:kc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dilations:l}=r;zt([s,a],"conv3d");const p=Gl(s.shape,a.shape,i,l,o),{filterDepth:c,filterHeight:h,filterWidth:d,dilationDepth:m,dilationHeight:g,dilationWidth:y,padInfo:w}=p,v=w.front,N=w.left,T=w.top,$=new kr(p.outShape,s.dtype),_=t.data.get(s.dataId).values,L=t.data.get(a.dataId).values,z=$.values,O=Ge(s.shape),V=Ge(a.shape);for(let U=0;U<p.batchSize;++U){const X=U*O[0],ne=U*$.strides[0];for(let ae=0;ae<p.outDepth;++ae){const Ie=ne+ae*$.strides[1],me=ae*p.strideDepth-v;for(let we=0;we<c;++we){const $e=me+we*m;if($e<0||$e>=p.inDepth)continue;const ze=we*V[0],We=X+$e*O[1];for(let Je=0;Je<p.outHeight;++Je){const nt=Ie+Je*$.strides[2],lt=Je*p.strideHeight-T;for(let dt=0;dt<h;++dt){const yt=lt+dt*g;if(yt<0||yt>=p.inHeight)continue;const xt=ze+dt*V[1],Ct=We+yt*O[2];for(let Rt=0;Rt<p.outWidth;++Rt){const tn=nt+Rt*p.outChannels,nn=Rt*p.strideWidth-N;for(let pn=0;pn<d;++pn){const Xt=nn+pn*y;if(Xt<0||Xt>=p.inWidth)continue;const vn=xt+pn*V[2],kn=Ct+Xt*p.inChannels;let Ln=vn;for(let Nn=0;Nn<p.inChannels;++Nn){const wn=_[kn+Nn];for(let Gn=0;Gn<p.outChannels;++Gn)z[tn+Gn]+=wn*L[Ln+Gn];Ln+=p.outChannels}}}}}}}}return t.makeTensorInfo($.shape,$.dtype,$.values)}},BR={kernelName:Hh,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,pad:o,filterShape:l}=r;zt([s,a],"conv3dBackpropFilterV2");const p=Ge(s.shape),c=Ge(a.shape),h=Gl(s.shape,l,i,1,o),d=h.strideDepth,m=h.strideHeight,g=h.strideWidth,y=h.filterDepth,w=h.filterHeight,v=h.filterWidth,N=new kr(h.filterShape,"float32"),T=N.values,[$,_,L,z]=N.strides,O=t.data.get(a.dataId).values,[V,U,X,ne]=c,ae=t.data.get(s.dataId).values,[Ie,me,we,$e]=p,ze=h.padInfo.front,We=h.padInfo.left,Je=h.padInfo.top;for(let nt=0;nt<y;++nt){const lt=Math.max(0,Math.ceil((ze-nt)/d)),dt=Math.min(h.outDepth,(h.inDepth+ze-nt)/d),yt=nt*$;for(let xt=0;xt<w;++xt){const Ct=Math.max(0,Math.ceil((Je-xt)/m)),Rt=Math.min(h.outHeight,(h.inHeight+Je-xt)/m),tn=xt*_+yt;for(let nn=0;nn<v;++nn){const pn=Math.max(0,Math.ceil((We-nn)/g)),Xt=Math.min(h.outWidth,(h.inWidth+We-nn)/g),vn=nn*L+tn;for(let kn=0;kn<h.inChannels;++kn){const Ln=kn*z+vn;for(let Nn=0;Nn<h.outChannels;++Nn){let wn=0;for(let Gn=0;Gn<h.batchSize;++Gn){const hs=Gn*Ie,Pr=Gn*V;for(let Ys=lt;Ys<dt;++Ys){const Jr=(nt+Ys*d-ze)*me+hs,zh=Ys*U+Pr;for(let Xa=Ct;Xa<Rt;++Xa){const po=(xt+Xa*m-Je)*we+Jr,fo=Xa*X+zh;for(let fc=pn;fc<Xt;++fc){const ju=fc*ne+fo;wn+=ae[(nn+fc*g-We)*$e+po+kn]*O[ju+Nn]}}}}T[Ln+Nn]=wn}}}}}return t.makeTensorInfo(N.shape,N.dtype,N.values)}},VR={kernelName:Nc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{pad:i,strides:o,inputShape:l}=r;zt([s],"conv3dBackpropInputV2");const p=Ge(s.shape),c=Ge(a.shape),h=Gl(l,a.shape,o,1,i),d=new kr(h.inShape,"float32"),m=d.values,[g,y,w,v]=d.strides,N=t.data.get(s.dataId).values,[T,$,_,L]=p,z=t.data.get(a.dataId).values,[O,V,U,X]=c,{batchSize:ne,filterDepth:ae,filterHeight:Ie,filterWidth:me,inChannels:we,inDepth:$e,inHeight:ze,inWidth:We,outChannels:Je,outDepth:nt,outHeight:lt,outWidth:dt,strideDepth:yt,strideHeight:xt,strideWidth:Ct}=h,Rt=ae-1-h.padInfo.front,tn=Ie-1-h.padInfo.top,nn=me-1-h.padInfo.left;for(let pn=0;pn<ne;++pn)for(let Xt=0;Xt<we;++Xt)for(let vn=0;vn<$e;++vn){const kn=vn-Rt,Ln=Math.max(0,Math.ceil(kn/yt)),Nn=Math.min(nt,(ae+kn)/yt);for(let wn=0;wn<ze;++wn){const Gn=wn-tn,hs=Math.max(0,Math.ceil(Gn/xt)),Pr=Math.min(lt,(Ie+Gn)/xt);for(let Ys=0;Ys<We;++Ys){const Jr=Ys-nn,zh=Math.max(0,Math.ceil(Jr/Ct)),Xa=Math.min(dt,(me+Jr)/Ct);let po=0;for(let fo=Ln;fo<Nn;++fo){const fc=fo*yt-kn;for(let ju=hs;ju<Pr;++ju){const u6=ju*xt-Gn;for(let ky=zh;ky<Xa;++ky){const l6=T*pn+$*fo+_*ju+L*ky,c6=O*(ae-1-fc)+V*(Ie-1-u6)+U*(me-1-(ky*Ct-Jr))+X*Xt;for(let Ny=0;Ny<Je;++Ny)po+=N[l6+Ny]*z[c6+Ny]}}}m[g*pn+y*vn+w*wn+v*Ys+Xt]=po}}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}},UR=Wn(xo,n=>Math.cos(n)),WR={kernelName:xo,backendName:"cpu",kernelFunc:UR},GR=Wn(Ii,n=>Math.cosh(n)),HR={kernelName:Ii,backendName:"cpu",kernelFunc:GR},jR={kernelName:al,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{image:s,boxes:a,boxInd:i}=e,{cropSize:o,method:l,extrapolationValue:p}=r,[c,h,d,m]=s.shape,g=a.shape[0],[y,w]=o,v=ln([g,y,w,m],"float32"),N=t.data.get(a.dataId).values,T=t.data.get(i.dataId).values,$=t.data.get(s.dataId).values,_=Ge(s.shape),L=Ge(v.shape);for(let z=0;z<g;z++){const O=4*z,V=N[O],U=N[O+1],X=N[O+2],ne=N[O+3],ae=T[z];if(ae>=c)continue;const Ie=y>1?(X-V)*(h-1)/(y-1):0,me=w>1?(ne-U)*(d-1)/(w-1):0;for(let we=0;we<y;we++){const $e=y>1?V*(h-1)+we*Ie:.5*(V+X)*(h-1);if($e<0||$e>h-1)for(let ze=0;ze<w;ze++)for(let We=0;We<m;We++){const Je=We+ze*L[2]+we*L[1]+z*L[0];v.values[Je]=p}else if(l==="bilinear"){const ze=Math.floor($e),We=Math.ceil($e),Je=$e-ze;for(let nt=0;nt<w;nt++){const lt=w>1?U*(d-1)+nt*me:.5*(U+ne)*(d-1);if(lt<0||lt>d-1){for(let Ct=0;Ct<m;Ct++){const Rt=Ct+nt*L[2]+we*L[1]+z*L[0];v.values[Rt]=p}continue}const dt=Math.floor(lt),yt=Math.ceil(lt),xt=lt-dt;for(let Ct=0;Ct<m;Ct++){let Rt=Ct+dt*_[2]+ze*_[1]+ae*_[0];const tn=$[Rt];Rt=Ct+yt*_[2]+ze*_[1]+ae*_[0];const nn=$[Rt];Rt=Ct+dt*_[2]+We*_[1]+ae*_[0];const pn=$[Rt];Rt=Ct+yt*_[2]+We*_[1]+ae*_[0];const Xt=tn+(nn-tn)*xt,vn=pn+($[Rt]-pn)*xt;Rt=Ct+nt*L[2]+we*L[1]+z*L[0],v.values[Rt]=Xt+(vn-Xt)*Je}}}else for(let ze=0;ze<w;++ze){const We=w>1?U*(d-1)+ze*me:.5*(U+ne)*(d-1);if(We<0||We>d-1){for(let lt=0;lt<m;lt++){const dt=lt+ze*L[2]+we*L[1]+z*L[0];v.values[dt]=p}continue}const Je=Math.round(We),nt=Math.round($e);for(let lt=0;lt<m;lt++){const dt=lt+Je*_[2]+nt*_[1]+ae*_[0],yt=lt+ze*L[2]+we*L[1]+z*L[0];v.values[yt]=$[dt]}}}}return t.makeTensorInfo(v.shape,v.dtype,v.values)}},KR={kernelName:jh,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:i,reverse:o}=r;zt(s,"cumprod");const l=Ir([a],s.shape.length);let p=s;l!=null&&(p=da({inputs:{x:s},backend:t,attrs:{perm:l}}));const c=Or(1,s.shape.length)[0];if(c!==p.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${p.shape.length-1} but got axis=${c}`);const h=Cs(p.dtype,"int32"),d=Ku(j(p.shape),h),m=t.data.get(p.dataId).values,g=p.shape[p.shape.length-1],y=o?(v,N)=>v+g-N-1:(v,N)=>v+N;for(let v=0;v<m.length;v+=g)for(let N=0;N<g;N++){const T=y(v,N);if(N===0)d[T]=i?1:m[T];else{const $=y(v,N-1);d[T]=i?m[$]*d[$]:m[T]*d[$]}}const w=t.makeTensorInfo(p.shape,h,d);if(l!=null){const v=da({inputs:{x:w},backend:t,attrs:{perm:Kl(l)}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(p),v}return w}},qR={kernelName:nu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:i,reverse:o}=r;zt(s,"cumsum");const l=Ir([a],s.shape.length);let p=s;l!=null&&(p=da({inputs:{x:s},backend:t,attrs:{perm:l}}));const c=Or(1,s.shape.length)[0];if(c!==p.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${p.shape.length-1} but got axis=${c}`);const h=Cs(p.dtype,"int32"),d=Er(j(p.shape),h),m=t.data.get(p.dataId).values,g=p.shape[p.shape.length-1],y=o?(v,N)=>v+g-N-1:(v,N)=>v+N;for(let v=0;v<m.length;v+=g)for(let N=0;N<g;N++){const T=y(v,N);if(N===0)d[T]=i?0:m[T];else{const $=y(v,N-1);d[T]=i?m[$]+d[$]:m[T]+d[$]}}const w=t.makeTensorInfo(p.shape,h,d);if(l!=null){const v=da({inputs:{x:w},backend:t,attrs:{perm:Kl(l)}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(p),v}return w}},XR={kernelName:il,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:i,binaryOutput:o}=r;if(s.shape.length===1){const l=mx(t.data.get(s.dataId).values,t.data.get(a.dataId).values,a.dtype,a.shape,i);return t.makeTensorInfo([i],a.dtype,l)}if(s.shape.length===2){const l=Zk(t.bufferSync(s),t.bufferSync(a),i,o);return t.makeTensorInfo(l.shape,a.dtype,l.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}},YR={kernelName:Ic,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockSize:a,dataFormat:i}=r;A(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);const o=s.shape[0],l=s.shape[1],p=s.shape[2],c=s.shape[3],h=l*a,d=p*a,m=c/(a*a),g=t.data.get(s.dataId).values,y=new Float32Array(o*h*d*m);let w=0;for(let v=0;v<o;++v)for(let N=0;N<h;++N){const T=Math.floor(N/a),$=N%a;for(let _=0;_<d;++_){const L=Math.floor(_/a),z=($*a+_%a)*m;for(let O=0;O<m;++O){const V=O+z+c*(L+p*(T+l*v));y[w++]=g[V]}}}return t.makeTensorInfo([o,h,d,m],s.dtype,y)}};function nI(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dilations:l,dimRoundingMode:p}=r;zt([s,a],"depthwiseConv2DNative");const c=Ge(s.shape),h=Ge(a.shape);let d=l;d==null&&(d=[1,1]),A(bs(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);const m=is(s.shape,a.shape,i,d,o,p,!0),{filterHeight:g,filterWidth:y,dilationHeight:w,dilationWidth:v,padInfo:N}=m,T=N.left,$=N.top,_=m.outChannels/m.inChannels,L=new kr(m.outShape,s.dtype),z=t.data.get(s.dataId).values,O=t.data.get(a.dataId).values,V=L.values;for(let U=0;U<m.batchSize;++U){const X=U*c[0],ne=U*L.strides[0];for(let ae=0;ae<m.outHeight;++ae){const Ie=ne+ae*L.strides[1],me=ae*m.strideHeight-$;for(let we=0;we<g;++we){const $e=me+we*w;if($e<0||$e>=m.inHeight)continue;const ze=we*h[0],We=X+$e*c[1];for(let Je=0;Je<m.outWidth;++Je){const nt=Ie+Je*L.strides[2],lt=Je*m.strideWidth-T;for(let dt=0;dt<y;++dt){const yt=lt+dt*v;if(yt<0||yt>=m.inWidth)continue;const xt=ze+dt*h[1],Ct=We+yt*m.inChannels;let Rt=nt,tn=xt;for(let nn=0;nn<m.inChannels;++nn){const pn=z[Ct+nn];for(let Xt=0;Xt<_;++Xt)V[Rt+Xt]+=pn*O[tn+Xt];Rt+=_,tn+=_}}}}}}return t.makeTensorInfo(L.shape,L.dtype,L.values)}const ZR={kernelName:wo,backendName:"cpu",kernelFunc:nI},QR={kernelName:Sc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,dilations:o,pad:l,dimRoundingMode:p,filterShape:c}=r;zt([s,a],"depthwiseConv2dNativeBackpropFilter");const h=is(s.shape,c,i,o,l,p,!0),{strideHeight:d,strideWidth:m,filterHeight:g,filterWidth:y}=h,w=new kr(h.filterShape,"float32"),v=h.padInfo.left,N=h.padInfo.top,T=h.outChannels/h.inChannels,$=t.data.get(s.dataId).values,_=new kr(s.shape,s.dtype,$),L=t.data.get(a.dataId).values,z=new kr(a.shape,a.dtype,L);for(let O=0;O<g;++O){const V=Math.max(0,Math.ceil((N-O)/d)),U=Math.min(h.outHeight,(h.inHeight+N-O)/d);for(let X=0;X<y;++X){const ne=Math.max(0,Math.ceil((v-X)/m)),ae=Math.min(h.outWidth,(h.inWidth+v-X)/m);for(let Ie=0;Ie<h.outChannels;++Ie){const me=Math.trunc(Ie/T),we=Ie%T;let $e=0;for(let ze=0;ze<h.batchSize;++ze)for(let We=V;We<U;++We){const Je=O+We*d-N;for(let nt=ne;nt<ae;++nt){const lt=X+nt*m-v;$e+=_.get(ze,Je,lt,me)*z.get(ze,We,nt,Ie)}}w.set($e,O,X,me,we)}}}return t.makeTensorInfo(w.shape,w.dtype,w.values)}},JR={kernelName:Fa,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{strides:i,dilations:o,pad:l,dimRoundingMode:p,inputShape:c}=r;zt([s,a],"depthwiseConv2DNativeBackpropInput");const h=Ge(s.shape),d=Ge(a.shape),m=is(c,a.shape,i,o,l,p,!0),g=new kr(m.inShape,"float32"),y=g.values,[w,v,N]=g.strides,T=t.data.get(s.dataId).values,[$,_,L]=h,z=t.data.get(a.dataId).values,[O,V,U]=d,{batchSize:X,filterHeight:ne,filterWidth:ae,inChannels:Ie,inHeight:me,inWidth:we,outChannels:$e,outHeight:ze,outWidth:We,strideHeight:Je,strideWidth:nt}=m,lt=ne-1-m.padInfo.top,dt=ae-1-m.padInfo.left,yt=$e/Ie;for(let xt=0;xt<X;++xt)for(let Ct=0;Ct<Ie;++Ct)for(let Rt=0;Rt<me;++Rt){const tn=Rt-lt,nn=Math.max(0,Math.ceil(tn/Je)),pn=Math.min(ze,(ne+tn)/Je);for(let Xt=0;Xt<we;++Xt){const vn=Xt-dt,kn=Math.max(0,Math.ceil(vn/nt)),Ln=Math.min(We,(ae+vn)/nt);let Nn=0;for(let wn=nn;wn<pn;++wn){const Gn=wn*Je-tn;for(let hs=kn;hs<Ln;++hs){const Pr=$*xt+_*wn+L*hs,Ys=O*(ne-1-Gn)+V*(ae-1-(hs*nt-vn))+U*Ct;for(let Jr=0;Jr<yt;++Jr)Nn+=T[Pr+(Ct*yt+Jr)]*z[Ys+Jr]}}y[w*xt+v*Rt+N*Xt+Ct]=Nn}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}},e_={kernelName:Tc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e,s=j(r.shape),a=t.data.get(r.dataId).values,i=ln([s,s],r.dtype),o=i.values;for(let p=0;p<a.length;p++)o[p*s+p]=a[p];const l=[...r.shape,...r.shape];return t.makeTensorInfo(l,i.dtype,i.values)}},t_={kernelName:Ms,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:r,filter:s}=n,{strides:a,pad:i,dilations:o}=t,l=e,p=l.data.get(r.dataId).values,c=r.shape.length,h=l.data.get(s.dataId).values,d=s.shape.length,{batchSize:m,inHeight:g,inWidth:y,inChannels:w,outHeight:v,outWidth:N,padInfo:T,strideHeight:$,strideWidth:_,filterHeight:L,filterWidth:z,dilationHeight:O,dilationWidth:V,outShape:U}=jp(r.shape,s.shape,a,i,"NHWC",o),X=j(U),ne=U.length,ae=Zt(r.dtype,X);for(let Ie=0;Ie<m;++Ie)for(let me=0;me<v;++me){const we=me*$-T.top;for(let $e=0;$e<N;++$e){const ze=$e*_-T.left;for(let We=0;We<w;++We){let Je=Number.MIN_SAFE_INTEGER;for(let nt=0;nt<L;++nt){const lt=we+nt*O;if(lt>=0&&lt<g)for(let dt=0;dt<z;++dt){const yt=ze+dt*V;if(yt>=0&&yt<y){const xt=Qs([Ie,lt,yt,We],c,Ge(r.shape)),Ct=Qs([nt,dt,We],d,Ge(s.shape)),Rt=p[xt]+h[Ct];Rt>Je&&(Je=Rt)}}}
93ae[Qs([Ie,me,$e,We],ne,Ge(U))]=Je}}}return{dataId:l.write(Ui(ae,r.dtype),U,r.dtype),shape:U,dtype:r.dtype}}},n_={kernelName:jn,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:r,filter:s,dy:a}=n,{strides:i,pad:o,dilations:l}=t,p=e,c=Ss(r.shape,p.data.get(r.dataId).values),h=Ss(s.shape,p.data.get(s.dataId).values),{batchSize:d,inHeight:m,inWidth:g,inChannels:y,outHeight:w,outWidth:v,padInfo:N,strideHeight:T,strideWidth:$,filterHeight:_,filterWidth:L,dilationHeight:z,dilationWidth:O,outShape:V}=jp(r.shape,s.shape,i,o,"NHWC",l);A(a.rank===V.length,()=>`Error in ${jn}, dy must have the same rank as output ${V.length}, but got ${a.rank}`);const U=Ss(V,p.data.get(a.dataId).values),X=Bh(s.shape,s.dtype);for(let ne=0;ne<d;++ne)for(let ae=0;ae<w;++ae){const Ie=ae*T-N.top;for(let me=0;me<v;++me){const we=me*$-N.left;for(let $e=0;$e<y;++$e){let ze=Number.MIN_SAFE_INTEGER,We=0,Je=0;for(let nt=0;nt<_;++nt){const lt=Ie+nt*z;if(lt>=0&&lt<m)for(let dt=0;dt<L;++dt){const yt=we+dt*O;if(yt>=0&&yt<g){const xt=c[ne][lt][yt][$e]+h[nt][dt][$e];xt>ze&&(ze=xt,We=nt,Je=dt)}}}X[We][Je][$e]+=U[ne][ae][me][$e]}}}return{dataId:p.write(Ui(X,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},r_={kernelName:On,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:r,filter:s,dy:a}=n,{strides:i,pad:o,dilations:l}=t,p=e,c=Ss(r.shape,p.data.get(r.dataId).values),h=Ss(s.shape,p.data.get(s.dataId).values),{batchSize:d,inHeight:m,inWidth:g,inChannels:y,outHeight:w,outWidth:v,padInfo:N,strideHeight:T,strideWidth:$,filterHeight:_,filterWidth:L,dilationHeight:z,dilationWidth:O,outShape:V}=jp(r.shape,s.shape,i,o,"NHWC",l);A(a.rank===V.length,()=>`Error in ${On}, dy must have the same rank as output ${V.length}, but got ${a.rank}`);const U=Ss(V,p.data.get(a.dataId).values),X=Bh(r.shape,r.dtype);for(let ne=0;ne<d;++ne)for(let ae=0;ae<w;++ae){const Ie=ae*T-N.top;for(let me=0;me<v;++me){const we=me*$-N.left;for(let $e=0;$e<y;++$e){let ze=Number.MIN_SAFE_INTEGER,We=Ie<0?0:Ie,Je=we<0?0:we;for(let nt=0;nt<_;++nt){const lt=Ie+nt*z;if(lt>=0&&lt<m)for(let dt=0;dt<L;++dt){const yt=we+dt*O;if(yt>=0&&yt<g){const xt=c[ne][lt][yt][$e]+h[nt][dt][$e];xt>ze&&(ze=xt,We=lt,Je=yt)}}}X[ne][We][Je][$e]+=U[ne][ae][me][$e]}}}return{dataId:p.write(Ui(X,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},s_={kernelName:Si,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{image:s}=e,{canvas:a,options:i}=r,{contextOptions:o,imageOptions:l}=i||{},p=l?.alpha||1,c=o?.contextType||"2d";if(c!=="2d")throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=a.getContext(c,o?.contextAttributes||{});if(h==null)throw new Error(`Could not get the context with ${c} type.`);const[d,m]=s.shape.slice(0,2),g=s.shape.length===2?1:s.shape[2],y=t.data.get(s.dataId).values,w=s.dtype==="float32"?255:1,v=new Uint8ClampedArray(m*d*4);for(let T=0;T<d*m;++T){const $=[0,0,0,255*p];for(let L=0;L<g;L++){const z=y[T*g+L];if(s.dtype==="float32"){if(z<0||z>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${z}.`)}else if(s.dtype==="int32"&&(z<0||z>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${z}.`);g===1?($[0]=z*w,$[1]=z*w,$[2]=z*w):$[L]=z*w}const _=4*T;v[_+0]=Math.round($[0]),v[_+1]=Math.round($[1]),v[_+2]=Math.round($[2]),v[_+3]=Math.round($[3])}a.width=m,a.height=d;const N=new ImageData(v,m,d);return h.putImageData(N,0,0),s}};function Of(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;let o;zt(s,"sum"),o=s.dtype==="bool"?lc({inputs:{x:s},backend:t,attrs:{dtype:"int32"}}):Yo({inputs:{x:s},backend:t});const l=o.shape.length,p=Oe(a,o.shape),c=Ir(p,l);let h=p,d=o;c!=null&&(d=da({inputs:{x:o},backend:t,attrs:{perm:c}}),h=Or(h.length,l)),xs("sum",h,d.shape.length);const[m,g]=us(d.shape,h);let y=ey(t,m,Cs(d.dtype,"int32"));const w=j(g),v=t.data.get(y.dataId).values,N=t.data.get(d.dataId).values;for(let T=0;T<v.length;++T){const $=T*w;let _=0;for(let L=0;L<w;++L)_+=N[$+L];v[T]=_}if(i){const T=y;y=or({inputs:{x:y},backend:t,attrs:{shape:Mr(y.shape,p)}}
93),t.disposeIntermediateTensorInfo(T)}return t.disposeIntermediateTensorInfo(o),c!=null&&t.disposeIntermediateTensorInfo(d),y}const a_={kernelName:La,backendName:"cpu",kernelFunc:Of},i_={kernelName:Ec,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{equation:s}=r,a=e,{allDims:i,summedDims:o,idDims:l}=Q0(s,a.length);e1(i.length,l,a);const{path:p,steps:c}=t1(o,l),h=c.length;let d=null,m=i.length;const g=[];for(let y=0;y<h;++y){for(const w of c[y]){const{permutationIndices:v,expandDims:N}=J0(m,l[w]);let T;n1(v)?T=a[w]:(T=da({inputs:{x:a[w]},backend:t,attrs:{perm:v}}),g.push(T));const $=T.shape.slice();for(let _=0;_<N.length;++_)$.splice(N[_],0,1);le(T.shape,$)||(T=or({inputs:{x:T},backend:t,attrs:{shape:$}}),g.push(T)),d===null?d=T:(d=ty({inputs:{a:T,b:d},backend:t}),g.push(d))}y<h-1&&(p[y]>=0&&(d=Of({inputs:{x:d},backend:t,attrs:{axis:p[y]-(i.length-m),keepDims:!1}}),g.push(d)),m--)}for(const y of g)y!==d&&t.disposeIntermediateTensorInfo(y);return d}},o_={kernelName:Qa,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{dy:r,y:s}=e;zt([r,s],"eluGrad");const a=new Float32Array(j(s.shape)),i=t.data.get(s.dataId).values,o=t.data.get(r.dataId).values;for(let l=0;l<i.length;++l){const p=i[l];a[l]=p>=0?o[l]:o[l]*(p+1)}return t.makeTensorInfo(s.shape,"float32",a)}},u_=G0,l_=H0,c_=j0,h_=K0,d_=q0,p_=X0,f_=Wn(ru,n=>{const e=Math.sign(n),t=Math.abs(n),r=1/(1+u_*t);return e*(1-((((p_*r+d_)*r+h_)*r+c_)*r+l_)*r*Math.exp(-t*t))}),m_={kernelName:ru,backendName:"cpu",kernelFunc:f_};function sy(n){const{inputs:e,backend:t,attrs:r}=n,{input:s}=e,{dim:a}=r,i=s.shape.length,o=s.shape.slice();let l=a;return a<0&&(A(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),or({inputs:{x:s},backend:t,attrs:{shape:o}})}const g_={kernelName:ul,backendName:"cpu",kernelFunc:sy},y_=zr((n,e)=>n/e),vx=Qr(Ti,y_),kx={kernelName:Ti,backendName:"cpu",kernelFunc:vx};function rI(n,e,t){const r=n.shape,s=r[0],a=r[1],i=t.data.get(n.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,p=[s,a],c=j(p),h=_t("float32",c),d=_t("float32",c);for(let w=0;w<s;w++){const v=Ch({inputs:{x:o},backend:t,attrs:{begin:[w,0],size:[1,a]}}),N=Ch({inputs:{x:l},backend:t,attrs:{begin:[w,0],size:[1,a]}}),T=Aa({inputs:{real:v,imag:N},backend:t}),{real:$,imag:_}=b_(T,e,t),L=zu($,_);for(let z=0;z<a;z++){const O=Y0(L,z);h[w*a+z]=O.real,d[w*a+z]=O.imag}t.disposeIntermediateTensorInfo(v),t.disposeIntermediateTensorInfo(N),t.disposeIntermediateTensorInfo(T)}const m=t.makeTensorInfo(p,"float32",h),g=t.makeTensorInfo(p,"float32",d),y=Aa({inputs:{real:m,imag:g},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),y}function b_(n,e,t){const r=j(n.shape),s=t.data.get(n.dataId),a=t.data.get(s.complexTensorInfos.real.dataId).values,i=t.data.get(s.complexTensorInfos.imag.dataId).values;if((o=r)&o-1){const l=function(p,c,h){const d=new Float32Array(2*c);for(let m=0;m<c;m++){let g=0,y=0;for(let w=0;w<c;w++){const v=p2(m*w,c,h),N=Y0(p,w);g+=N.real*v.real-N.imag*v.imag,y+=N.real*v.imag+N.imag*v.real}h&&(g/=c,y/=c),h2(d,g,y,m)}return d}(zu(a,i),r,e);return u2(l)}{const l=Nx(a,i,r,e,t),p=[n.shape[0],n.shape[1]];if(e){const c=t.makeTensorInfo(p,"float32",l.real),h=t.makeTensorInfo(p,"float32",l.imag),d=t.makeTensorInfo([],"float32",Bn(r,"float32")),m=Yo({inputs:{x:d},backend:t}),g=kx.kernelFunc({inputs:{a:c,b:d},backend:t}),y=kx.kernelFunc({inputs:{a:h,b:m},backend:t}),w=t.data.get(g.dataId).values,v=t.data.get(y.dataId).values;return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),{real:w,imag:v}}return l}var o}function Nx(n,e,t,r,s){if(t===1)return{real:n,imag:e};const a=zu(n,e),i=t/2,o=l2(a),l=o.real,p=o.imag,c=[l.length],h=s.makeTensorInfo(c,"float32",l),d=s.makeTensorInfo(c,"float32",p),m=Aa({inputs:{real:h,imag:d},backend:s}),g=c2(a),y=g.real,w=g.imag,v=[y.length],N=s.makeTensorInfo(v,"float32",y),T=s.makeTensorInfo(v,"float32",w),$=Aa({input
93s:{real:N,imag:T},backend:s}),_=Nx(l,p,i,r,s),L=_.real,z=_.imag,O=[L.length],V=s.makeTensorInfo(O,"float32",L),U=s.makeTensorInfo(O,"float32",z),X=Aa({inputs:{real:V,imag:U},backend:s}),ne=Nx(y,w,i,r,s),ae=ne.real,Ie=ne.imag,me=[ae.length],we=s.makeTensorInfo(me,"float32",ae),$e=s.makeTensorInfo(me,"float32",Ie),ze=Aa({inputs:{real:we,imag:$e},backend:s}),We=d2(t,r),Je=[We.real.length],nt=s.makeTensorInfo(Je,"float32",We.real),lt=s.makeTensorInfo(Je,"float32",We.imag),dt=Aa({inputs:{real:nt,imag:lt},backend:s}),yt=ty({inputs:{a:dt,b:ze},backend:s}),xt=Jd({inputs:{a:X,b:yt},backend:s}),Ct=xx({inputs:{a:X,b:yt},backend:s}),Rt=Eh({inputs:{input:xt},backend:s}),tn=Eh({inputs:{input:Ct},backend:s}),nn=tp({inputs:{input:xt},backend:s}),pn=tp({inputs:{input:Ct},backend:s}),Xt=np({inputs:[Rt,tn],backend:s,attrs:{axis:0}}),vn=np({inputs:[nn,pn],backend:s,attrs:{axis:0}}),kn=s.data.get(Xt.dataId).values,Ln=s.data.get(vn.dataId).values;return s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(m),s.disposeIntermediateTensorInfo(N),s.disposeIntermediateTensorInfo(T),s.disposeIntermediateTensorInfo($),s.disposeIntermediateTensorInfo(V),s.disposeIntermediateTensorInfo(U),s.disposeIntermediateTensorInfo(X),s.disposeIntermediateTensorInfo(we),s.disposeIntermediateTensorInfo($e),s.disposeIntermediateTensorInfo(ze),s.disposeIntermediateTensorInfo(nt),s.disposeIntermediateTensorInfo(lt),s.disposeIntermediateTensorInfo(dt),s.disposeIntermediateTensorInfo(yt),s.disposeIntermediateTensorInfo(xt),s.disposeIntermediateTensorInfo(Ct),s.disposeIntermediateTensorInfo(Rt),s.disposeIntermediateTensorInfo(nn),s.disposeIntermediateTensorInfo(tn),s.disposeIntermediateTensorInfo(pn),s.disposeIntermediateTensorInfo(Xt),s.disposeIntermediateTensorInfo(vn),{real:kn,imag:Ln}}const x_={kernelName:ll,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{input:r}=e,s=j(r.shape),a=r.shape[r.shape.length-1],i=or({inputs:{x:r},backend:t,attrs:{shape:[s/a,a]}}),o=rI(i,!1,t),l=or({inputs:{x:o},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),l}};function Ix(n){const{backend:e,attrs:t}=n,{shape:r,value:s,dtype:a}=t,i=a||St(s),o=Zt(i,j(r));return function(l,p){l.fill(p)}(o,s),e.makeTensorInfo(r,i,o)}const w_={kernelName:cl,backendName:"cpu",kernelFunc:Ix},v_={kernelName:Cc,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:r}=n,s=t,a=_t(r.dtype,j(r.shape)),[i,o,l,p]=r.shape,c=s.data.get(r.dataId).values;for(let h=0;h<i;h++){const d=h*l*o*p;for(let m=0;m<o;m++){const g=m*(l*p);for(let y=0;y<l;y++){const w=y*p;for(let v=0;v<p;v++){const N=Math.round(l-y-1),T=d+g+w+v;let $=c[T];N>=0&&N<l&&($=c[d+g+N*p+v]),a[T]=$}}}}return{dataId:s.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},k_={kernelName:Lo,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:i,preluActivationWeights:o}=e,{strides:l,pad:p,dataFormat:c,dilations:h,dimRoundingMode:d,activation:m,leakyreluAlpha:g}=r;let y=tI({inputs:{x:s,filter:a},backend:t,attrs:{strides:l,pad:p,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const w=y;if(c==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){const v=or({inputs:{x:i},backend:t,attrs:{shape:[i.shape[0],1,1]}});y=Jd({inputs:{a:y,b:v},backend:t}),t.disposeIntermediateTensorInfo(v)}
93else y=Jd({inputs:{a:y,b:i},backend:t});t.disposeIntermediateTensorInfo(w)}if(m){const w=y;if(c==="NCHW"&&m==="prelu"&&o.shape.length===1&&o.shape[0]!==1){const v=or({inputs:{x:o},backend:t,attrs:{shape:[o.shape[0],1,1]}});y=ry(t,y,m,v,g),t.disposeIntermediateTensorInfo(v)}else y=ry(t,y,m,o,g);t.disposeIntermediateTensorInfo(w)}return y}},N_={kernelName:ni,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:i,preluActivationWeights:o}=e,{strides:l,pad:p,dataFormat:c,dilations:h,dimRoundingMode:d,activation:m,leakyreluAlpha:g}=r;let y=nI({inputs:{x:s,filter:a},backend:t,attrs:{strides:l,pad:p,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const w=y;y=Jd({inputs:{a:y,b:i},backend:t}),t.disposeIntermediateTensorInfo(w)}if(m){const w=y;y=ry(t,y,m,o,g),t.disposeIntermediateTensorInfo(w)}return y}},I_={kernelName:$c,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{params:r,indices:s}=e,a=j(r.shape),i=s.shape,o=i[i.length-1],[l,p,c,h]=Wl(r,s);if(p===0)return t.makeTensorInfo(l,r.dtype,[]);const d=uN(t.data.get(s.dataId).values,t.bufferSync(r),r.dtype,p,o,c,h,r.shape,a);return t.makeTensorInfo(l,r.dtype,d.values)}},S_={kernelName:xn,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,indices:a}=e,{axis:i,batchDims:o}=r;zt([s,a],"gatherV2");const l=Oe(i,s.shape)[0],p=t.data.get(a.dataId).values,c=s.shape[l];for(let T=0;T<p.length;++T){const $=p[T];A($<=c-1&&$>=0,()=>`GatherV2: the index value ${$} is not in [0, ${c-1}]`)}let h=o;o==null&&(h=0);const d=j(a.shape),m=s1(s,a,l,h),g=or({inputs:{x:s},backend:t,attrs:{shape:[m.batchSize,m.outerSize,m.dimSize,m.sliceSize]}}),y=or({inputs:{x:a},backend:t,attrs:{shape:[m.batchSize,d/m.batchSize]}}),w=[m.batchSize,m.outerSize,d/m.batchSize,m.sliceSize],v=t.bufferSync(y),N=lN(t.bufferSync(g),v,w);return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),t.makeTensorInfo(m.outputShape,N.dtype,N.values)}},T_={kernelName:ei,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{input:r}=e,s=j(r.shape),a=r.shape[r.shape.length-1],i=or({inputs:{x:r},backend:t,attrs:{shape:[s/a,a]}}),o=rI(i,!0,t),l=or({inputs:{x:o},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),l}},E_=Wn(Ci,n=>Number.isFinite(n)?1:0,"bool"),C_={kernelName:Ci,backendName:"cpu",kernelFunc:E_},$_=Wn(ps,n=>Math.abs(n)===1/0?1:0,"bool"),A_={kernelName:ps,backendName:"cpu",kernelFunc:$_},R_=Wn(ns,n=>Number.isNaN(n)?1:0,"bool"),__={kernelName:ns,backendName:"cpu",kernelFunc:R_},D_={kernelName:ta,backendName:"cpu",kernelFunc:function(n){const{backend:e,attrs:t}=n,{start:r,stop:s,num:a}=t,i=fN(r,s,a);return e.makeTensorInfo([i.length],"float32",i)}},F_=Wn(Ai,n=>Math.log1p(n)),M_={kernelName:Ai,backendName:"cpu",kernelFunc:F_},O_=zr((n,e)=>n&&e),L_=Qr(Io,O_,null,"bool"),z_={kernelName:Io,backendName:"cpu",kernelFunc:L_},P_=Wn(dl,n=>n?0:1,"bool"),B_={kernelName:dl,backendName:"cpu",kernelFunc:P_},V_=zr((n,e)=>n||e),U_=Qr(su,V_,null,"bool"),W_={kernelName:su,backendName:"cpu",kernelFunc:U_},G_={kernelName:au,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{depthRadius:a,bias:i,alpha:o,beta:l}=r;zt(s,"LRN");const p=s.shape[3],c=p-1,h=t.data.get(s.dataId).values,d=j(s.shape),m=new Float32Array(d);function g(y){const w=y%p;let v=y-w+Math.max(0,w-a);
vendor: 5,409 bytes, line 93
93const N=y-w+Math.min(w+a,c);let T=0;for(;v<=N;v++){const $=h[v];T+=$*$}return T}for(let y=0;y<d;y++){const w=g(y),v=h[y]*Math.pow(i+o*w,-l);m[y]=v}return t.makeTensorInfo(s.shape,s.dtype,m)}},H_={kernelName:Ma,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,y:a,dy:i}=e,{depthRadius:o,bias:l,alpha:p,beta:c}=r;zt(i,"LRNGrad");const h=j(i.shape),d=i.shape[3],m=t.data.get(i.dataId).values,g=t.data.get(s.dataId).values,y=t.data.get(a.dataId).values,w=new Float32Array(h),v=h;for(let N=0;N<v;N++){const T=N%d,$=N-T+Math.max(0,T-o),_=N-T+Math.min(d,T+o+1);let L=0;for(let z=$;z<_;z++)L+=Math.pow(g[z],2);L=p*L+l;for(let z=$;z<_;z++){let O=-2*p*c*g[z]*y[N]/L;N===z&&(O+=Math.pow(L,-c)),O*=m[N],w[z]+=O}}return t.makeTensorInfo(i.shape,s.dtype,w)}};function sI(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{reductionIndices:a,keepDims:i}=r,o=t;let l=s.shape;const p=l.length,c=Oe(a,l);let h=c;const d=Ir(h,p);let m=o.data.get(s.dataId).values;if(d!=null){const T=new Array(p);for(let $=0;$<T.length;$++)T[$]=l[d[$]];m=yx(m,l,s.dtype,d,T),h=Or(h.length,p),l=T}zt(s,"max"),xs("max",h,p);const[g,y]=us(l,h),w=gN(m,j(y),g,s.dtype),v=o.write(w,g,s.dtype);let N=g;return i&&(N=Mr(g,c)),{dataId:v,shape:N,dtype:s.dtype}}const j_={kernelName:iu,backendName:"cpu",kernelFunc:sI},K_={kernelName:Ac,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e;zt(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;A(bs(i,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`);const p=li(s.shape,a,i,1,o,l);let c;if(p.filterWidth===1&&p.filterHeight===1&&le(p.inShape,p.outShape))c=Yo({inputs:{x:s},backend:t});else{const h=t.data.get(s.dataId).values,d=Ge(s.shape),m=wx(h,s.shape,s.dtype,d,p,"max");c=t.makeTensorInfo(p.outShape,s.dtype,m.values)}return c}},q_={kernelName:Oa,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=r;zt(s,"maxPool3d");const c=_u(s.shape,a,i,1,o,l,p),h=eI(t.data.get(s.dataId).values,s.shape,s.dtype,Ge(s.shape),c,"max");return t.makeTensorInfo(h.shape,"float32",h.values)}},X_={kernelName:Rc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=r;zt([s,a],"maxPool3DGrad");const c=_u(a.shape,i,o,1,l,p),h=function(U,X){const ne=ln(X.outShape,"int32"),ae=X.strideDepth,Ie=X.strideHeight,me=X.strideWidth,we=X.dilationDepth,$e=X.dilationHeight,ze=X.dilationWidth,We=X.effectiveFilterDepth,Je=X.effectiveFilterHeight,nt=X.effectiveFilterWidth,lt=X.padInfo.front,dt=X.padInfo.top,yt=X.padInfo.left;for(let xt=0;xt<X.batchSize;++xt)for(let Ct=0;Ct<X.inChannels;++Ct)for(let Rt=0;Rt<X.outDepth;++Rt){const tn=Rt*ae-lt;let nn=tn;for(;nn<0;)nn+=we;const pn=Math.min(X.inDepth,We+tn);for(let Xt=0;Xt<X.outHeight;++Xt){const vn=Xt*Ie-dt;let kn=vn;for(;kn<0;)kn+=$e;const Ln=Math.min(X.inHeight,Je+vn);for(let Nn=0;Nn<X.outWidth;++Nn){const wn=Nn*me-yt;let Gn=wn;for(;Gn<0;)Gn+=ze;const hs=Math.min(X.inWidth,nt+wn);let Pr=Number.NEGATIVE_INFINITY,Ys=-1;for(let Jr=nn;Jr<pn;Jr+=we){const zh=Jr-tn;for(let Xa=kn;Xa<Ln;Xa+=$e){const po=Xa-vn;for(let fo=Gn;fo<hs;fo+=ze){const fc=fo-wn,ju=U.get(xt,Jr,Xa,fo,Ct);ju>=Pr&&(Pr=ju,Ys=zh*Je*nt+po*Je+fc)}}}ne.set(Ys,xt,Rt,Xt,Nn,Ct)}}}return ne}(t.bufferSync(a),c),d=c.strideDepth,m=c.strideHeight,g=c.strideWidth,y=c.dilationDepth,w=c.dilationHeight,v=c.dilationWidth,N=c.effectiveFilterDepth,T=c.effectiveFilterHeight,$=c.effectiveFilterWidth,_=N-1-c.padInfo.front,L=$-1-c.padInfo.left,z=T-1-c.padInfo.top,O=ln(a.shape,"float32"),V=t.bufferSync(s);for(let U=0;U<c.batchSize;++U)for(let X=0;X<c.inChannels;++X)for(let ne=0;ne<c.inDepth;++ne)for(let ae=0;ae<c.inHeight;++ae)for(let Ie=0;Ie<c.inWidth;++Ie){const me=ne-_,we=ae-z,$e=Ie-L;let ze=0;for(let We=0;We<N;We+=y){const Je=(me+We)/d;if(!(Je<0||Je>=c.outDepth||Math.floor(Je)!==Je))for(let nt=0;nt<T;nt+=w){const lt=(we+nt)/m;if(!(lt<0||lt>=c.outHeight||Math.floor(lt)!==lt))for(let dt=0;dt<$;dt+=v){const yt=($e+dt)/g;if(yt<0||yt>=c.outWidth||Math.floor(yt)!==yt)continue;const xt=N*T*$-1-h.get(U,Je,lt,yt,X)===We*T*$+nt*$+dt?1:0;xt!==0&&(ze+=V.get(U,Je,lt,yt,X)*xt)}}}O.set(ze,U,ne,ae,Ie,X)}return t.makeTensorInfo(O.shape,O.dtype,O.values)}},Y_={kernelName:pl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a,output:i}=e,o=a;zt([a,i],"maxPoolGrad");const{filterSize:l,strides:p,pad:c,dimRoundingMode:h}=r,d=li(o.shape,l,p,1,c,h),m=t.data.get(o.dataId).values,g=ln(d.outShape,o.dtype,JN(m,o.shape,o.dtype,d).values),y=d.strideHeight,w=d.strideWidth,v=d.dilationHeight,N=d.dilationWidth,T=d.effectiveFilterHeight,$=d.effectiveFilterWidth,_=$-1-d.padInfo.left,L=T-1-d.padInfo.top,z=ln(o.shape,"float32"),O=t.data.get(s.dataId).values,V=ln(s.shape,"float32",O);for(let U=0;U<d.batchSize;++U)for(let X=0;X<d.inChannels;++X)for(let ne=0;ne<d.inHeight;++ne)for(let ae=0;ae<d.inWidth;++ae){const Ie=ne-L,me=ae-_;let we=0;for(let $e=0;$e<T;$e+=v){const ze=(Ie+$e)/y;if(!(ze<0||ze>=d.outHeight||Math.floor(ze)!==ze))for(let We=0;We<$;We+=N){const Je=(me+We)/w;if(Je<0||Je>=d.outWidth||Math.floor(Je)!==Je)continue;const nt=T*$-1-g.get(U,ze,Je,X)===$e*$+We?1:0;nt!==0&&(we+=V.get(U,ze,Je,X)*nt)}}z.set(we,U,ne,ae,X)}return t.makeTensorInfo(z.shape,z.dtype,z.values)}}
93,Z_={kernelName:_c,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:r}=n,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=e,l=t;zt(r,"MaxPoolWithArgmax");const p=l.data.get(r.dataId).values,c=li(r.shape,s,a,[1,1],i),[h,d]=function(y,w,v,N,T){const $=wx(y,0,v,Ge(w),T,"max"),_=JN(y,w,v,T,!0,N);return[$.values,_.values]}(p,r.shape,r.dtype,o,c),m=l.write(h,c.outShape,r.dtype),g=l.write(d,c.outShape,r.dtype);return[{dataId:m,shape:c.outShape,dtype:r.dtype},{dataId:g,shape:c.outShape,dtype:"int32"}]}},Q_={kernelName:fl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r,o=Oe(a,s.shape),l=j(us(s.shape,o)[1]),p=[],c=t.makeTensorInfo([],"float32",new Float32Array([l]));p.push(c);const h=lc({inputs:{x:s},backend:t,attrs:{dtype:"float32"}});p.push(h);const d=vx({inputs:{a:h,b:c},backend:t});p.push(d);const m=Of({inputs:{x:d},backend:t,attrs:{axis:a,keepDims:i}});return p.forEach(g=>t.disposeIntermediateTensorInfo(g)),m}},J_={kernelName:ml,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;zt(s,"min");const o=Oe(a,s.shape);let l=o;const p=Ir(l,s.shape.length);let c=s;p!=null&&(c=da({inputs:{x:s},backend:t,attrs:{perm:p}}),l=Or(l.length,s.shape.length)),xs("min",l,c.shape.length);const[h,d]=us(c.shape,l),m=j(d),g=Er(j(h),c.dtype),y=t.data.get(c.dataId).values;for(let v=0;v<g.length;++v){const N=v*m;let T=y[N];for(let $=0;$<m;++$){const _=y[N+$];(Number.isNaN(_)||_<T)&&(T=_)}g[v]=T}p!=null&&t.disposeIntermediateTensorInfo(c);const w=t.makeTensorInfo(h,c.dtype,g);if(i){const v=or({inputs:{x:w},backend:t,attrs:{shape:Mr(h,o)}});return t.disposeIntermediateTensorInfo(w),v}return w}},eD={kernelName:_i,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{paddings:a,mode:i}=r;zt(s,"mirrorPad");const o=a.map((N,T)=>N[0]+s.shape[T]+N[1]),l=a.map(N=>N[0]),p=a.map((N,T)=>N[0]+s.shape[T]),c=i==="reflect"?0:1,h=t.data.get(s.dataId).values,d=s.shape.length,m=Ge(s.shape),g=j(o),y=o.length,w=Ge(o),v=_t(s.dtype,g);for(let N=0;N<g;N++){let T=Fs(N,y,w);for(let _=0;_<y;_++)T[_]<l[_]?T[_]=2*l[_]-T[_]-c:T[_]>=p[_]&&(T[_]=2*(p[_]-1)-T[_]+c);T=T.map((_,L)=>_-l[L]);const $=Qs(T,d,m);v[N]=h[$]}return{dataId:t.write(v,o,s.dtype),shape:o,dtype:s.dtype}}},tD=zr((n,e)=>{const t=n%e;return n<0&&e<0||n>=0&&e>=0?t:(t+e)%e}),nD=Qr(Eo,tD),rD={kernelName:Eo,backendName:"cpu",kernelFunc:nD};function aI(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{dim:a}=r,i=s.shape.length;let o=a;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const l=Oe([o],s.shape),p=sI({inputs:{x:s},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=Mr(p.shape,l),h=or({inputs:{x:p},backend:t,attrs:{shape:c}}),d=xx({inputs:{a:s,b:h},backend:t}),m=sN({inputs:{x:d},backend:t}),g=Of({inputs:{x:m},backend:t,attrs:{axis:l,keepDims:!1}}),y=or({inputs:{x:g},backend:t,attrs:{shape:c}}),w=vx({inputs:{a:m,b:y},backend:t});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),w}const sD={kernelName:mu,backendName:"cpu",kernelFunc:aI},aD={kernelName:Dc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{numSamples:a,seed:i,normalized:o}=r;zt(s,"multinomial");const l=o?s:aI({inputs:{logits:s},backend:t,attrs:{dim:-1}}),p=l.shape[0],c=l.shape[1],h=t.data.get(l.dataId).values,d=[p,a],m=Er(j(d),"int32");for(let g=0;g<p;++g){const y=g*c,w=new Float32Array(c-1);w[0]=h[y];for(let T=1;T<w.length;++T)w[T]=w[T-1]+h[y+T];const v=zd.alea(i.toString()),N=g*a;for(let T=0;T<a;++T){const $=v();m[N+T]=w.length;for(let _=0;_<w.length;_++)if($<w[_]){m[N+T]=_;break}}}return o||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(d,"int32",m)}},iD=ig,oD={kernelName:zs,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=r;zt(s,"NonMaxSuppression");const p=t.data.get(s.dataId).values,c=t.data.get(a.dataId).values,{selectedIndices:h}=iD(p,c,i,o,l);return t.makeTensorInfo([h.length],"int32",new Int32Array(h))}},uD=og,lD={kernelName:Mt,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:p}=r;zt(s,"NonMaxSuppressionPadded");const c=t.data.get(s.dataId).values,h=t.data.get(a.dataId).values,{selectedIndices:d,validOutputs:m}=uD(c,h,i,o,l,p);return[t.makeTensorInfo([d.length],"int32",new Int32Array(d)),t.makeTensorInfo([],"int32",new Int32Array([m]))]}},cD=ug,hD={kernelName:Fc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:p}=r;zt(s,"NonMaxSuppressionWithScore");const c=t.data.get(s.dataId).values,h=t.data.get(a.dataId).values,d=i,m=o,g=l,y=p,{selectedIndices:w,selectedScores:v}=cD(c,h,d,m,g,y);return[t.makeTensorInfo([w.length],"int32",new Int32Array(w)),t.makeTensorInfo([v.length],"float32",new Float32Array(v))]}},dD={kernelName:ou,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s}=e,{dtype:a,depth:i,onValue:o,offValue:l}=r;zt(s,"oneHot");const p=j(s.shape),c=new Float32Array(p*i);c.fill(l);const h=t.data.get(s.dataId).values;for(let d=0;d<p;++d)h[d]>=0&&h[d]<i&&(c[d*i+h[d]]=o);return t.makeTensorInfo([...s.shape,i],a,c)}};function ay(n){const{inputs:e,backend:t}=n,{x:r}=e;if(r.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(r.dtype==="complex64"){const s=Eh({inputs:{input:r},backend:t}
93),a=ay({inputs:{x:s},backend:t}),i=tp({inputs:{input:r},backend:t}),o=ay({inputs:{x:i},backend:t}),l=Aa({inputs:{real:a,imag:o},backend:t});return t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),l}return Ix({backend:t,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const pD={kernelName:ku,backendName:"cpu",kernelFunc:ay},fD={kernelName:gl,backendName:"cpu",kernelFunc:function n(e){const{inputs:t,backend:r}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(s.dtype==="complex64"){const a=Eh({inputs:{input:s},backend:r}),i=n({inputs:{x:a},backend:r}),o=tp({inputs:{input:s},backend:r}),l=ay({inputs:{x:o},backend:r}),p=Aa({inputs:{real:i,imag:l},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),p}return Ix({backend:r,attrs:{shape:s.shape,value:1,dtype:s.dtype}})}};function iI(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r;if(e.length===1)return sy({inputs:{input:e[0]},backend:t,attrs:{dim:s}});const a=e[0].shape,i=e[0].dtype;e.forEach(p=>{ge(a,p.shape,"All tensors passed to stack must have matching shapes"),A(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],l=np({inputs:e.map(p=>{const c=sy({inputs:{input:p},backend:t,attrs:{dim:s}});return o.push(c),c}),backend:t,attrs:{axis:s}});return o.forEach(p=>t.disposeIntermediateTensorInfo(p)),l}const mD={kernelName:Mc,backendName:"cpu",kernelFunc:iI},oI={kernelName:yl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{paddings:a,constantValue:i}=r;zt(s,"pad");const o=a.map((v,N)=>v[0]+s.shape[N]+v[1]),l=a.map(v=>v[0]),p=t.data.get(s.dataId).values,c=j(s.shape),h=s.shape.length,d=Ge(s.shape),m=j(o),g=o.length,y=Ge(o),w=_t(s.dtype,m);i!==0&&w.fill(i);for(let v=0;v<c;v++)w[Qs(Fs(v,h,d).map((N,T)=>N+l[T]),g,y)]=p[v];return{dataId:t.write(w,o,s.dtype),shape:o,dtype:s.dtype}}},gD=zr((n,e)=>Math.pow(n,e)),yD=Qr(bl,gD),bD={kernelName:bl,backendName:"cpu",kernelFunc:yD},xD={kernelName:uu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=e,{outputRaggedRank:o}=r,l=s.map(v=>t.data.get(v.dataId).values),p=s.map(v=>v.shape),c=t.data.get(a.dataId).values,h=t.data.get(i.dataId).values,[d,m,g]=NN(l,p,c,a.shape,a.dtype,h,i.shape),y=d.map(v=>t.makeTensorInfo([v.length],"int32",v)),w=t.makeTensorInfo(g,a.dtype,m);return y.concat([w])}},wD={kernelName:Ao,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{starts:r,limits:s,deltas:a}=e,i=t.data.get(r.dataId).values,o=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values,[p,c]=SN(i,r.shape,r.dtype,o,s.shape,l,a.shape);return[t.makeTensorInfo([p.length],"int32",p),t.makeTensorInfo([c.length],r.dtype,c)]}},vD={kernelName:Mi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=e,{rowPartitionTypes:l}=r,p=t.data.get(s.dataId).values,c=t.data.get(a.dataId).values,h=t.data.get(i.dataId).values,d=o.map(w=>t.data.get(w.dataId).values),m=o.map(w=>w.shape),[g,y]=CN(p,s.shape,c,a.shape,a.dtype,h,i.shape,d,m,l);return t.makeTensorInfo(g,a.dtype,y)}},kD={kernelName:Ts,backendName:"cpu",kernelFunc:function(n){const{backend:e,attrs:t}=n,{start:r,stop:s,dtype:a,step:i}=t,o=$N(r,s,i,a);return e.makeTensorInfo([o.length],a,o)}},ND=Wn(Ro,n=>1/n),ID={kernelName:Ro,backendName:"cpu",kernelFunc:ND},SD={kernelName:vl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,halfPixelCenters:i,size:o}=r;zt(s,"resizeBilinear");const l=Ge(s.shape),[p,c]=o,[h,d,m,g]=s.shape,y=t.data.get(s.dataId).values,w=new Float32Array(j([h,p,c,g])),v=[a&&p>1?d-1:d,a&&c>1?m-1:m],N=[a&&p>1?p-1:p,a&&c>1?c-1:c];let T=0;const $=v[0]/N[0],_=v[1]/N[1];for(let L=0;L<h;L++)for(let z=0;z<p;z++){let O;O=i?$*(z+.5)-.5:$*z;const V=Math.max(0,Math.floor(O)),U=O-V,X=Math.min(d-1,Math.ceil(O)),ne=L*l[0]+V*l[1],ae=L*l[0]+X*l[1];for(let Ie=0;Ie<c;Ie++){let me;me=i?_*(Ie+.5)-.5:_*Ie;const we=Math.max(0,Math.floor(me)),$e=me-we,ze=Math.min(m-1,Math.ceil(me)),We=ne+we*l[2],Je=ae+we*l[2],nt=ne+ze*l[2],lt=ae+ze*l[2];for(let dt=0;dt<g;dt++){const yt=y[We+dt],xt=y[Je+dt],Ct=yt+(y[nt+dt]-yt)*$e,Rt=Ct+(xt+(y[lt+dt]-xt)*$e-Ct)*U;w[T++]=Rt}}}return t.makeTensorInfo([h,p,c,g],"float32",w)}},TD={kernelName:kl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:i}=r;zt([a,s],"resizeBilinearGrad");const o=Ge(s.shape),[l,p,c,h]=s.shape,[,d,m]=a.shape,g=new Float32Array(l*p*c*h),y=[i&&d>1?p-1:p,i&&m>1?c-1:c],w=[i&&d>1?d-1:d,i&&m>1?m-1:m],v=y[0]/w[0],N=y[1]/w[1],T=t.data.get(a.dataId).values;let $=0;for(let _=0;_<l;_++){const L=_*o[0];for(let z=0;z<d;z++){const O=z*v,V=Math.floor(O),U=Math.min(Math.ceil(O),p-1),X=L+V*o[1],ne=L+U*o[1],ae=O-V,Ie=1-ae;for(let me=0;me<m;me++){const we=me*N,$e=Math.floor(we),ze=Math.min(Math.ceil(we),c-1),We=we-$e,Je=1-We,nt=X+$e*o[2],lt=X+ze*o[2],dt=ne+$e*o[2],yt=ne+ze*o[2],xt=Ie*Je,Ct=Ie*We,Rt=ae*Je,tn=ae*We;for(let nn=0;nn<h;nn++){const pn=T[$++];g[nt+nn]+=pn*xt,g[lt+nn]+=pn*Ct,g[dt+nn]+=pn*Rt,g[yt+nn]+=pn*tn}}}}return t.makeTensorInfo([l,c,p,h],"float32",g)}},ED={kernelName:Es,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,halfPixelCenters:i,size:o}=r;zt(s,"resizeNearestNeighbor");const l=Ge(s.shape),[p,c]=o,[h,d,m,g]=s.shape,y=t.data.get(s.dataId).values,w=new Float32Array(h*p*c*g),v=[a&&p>1?d-1:d,a&&c>1?m-1:m],N=[a&&p>1?p-1:p,a&&c>1?c-1:c],T=v[0]/N[0],$=v[1]/N[1];let _=0;for(let L=0;L<h;L++){const z=L*l[0];for(let O=0;O<p;O++){const V=i?T*(O+.5):T*O;let U=Math.min(d-1,a?Math.round(V):Math.floor(V));i&&(U=Math.max(0,U));const X=z+U*l[1];for(let ne=0;ne<c;ne++){const ae=i?$*(ne+.5):$*ne;let Ie=Math.min(m-1,a?Math.round(ae):Math.floor(ae));i&&(Ie=Math.max(0,Ie));const me=X+Ie*l[2];for(let we=0;we<g;we++){const $e=y[me+we];w[_++]=$e}}}}return t.makeTensorInfo([h,p,c,g],s.dtype,w)}},CD={kernelName:wl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:i}=r;zt([a,s],"resizeNearestNeighborGrad");const o=Ge(s.shape),l=Ge(a.shape),[p,c,h,d]=s.shape,[,m,g]=a.shape,y=new Float32Array(p*c*h*d),w=t.data.get(a.dataId).values,v=[i&&m>1?c-1:c,i&&g>1?h-1:h],N=[i&&m>1?m-1:m,i&&g>1?g-1:g],T=v[0]/N[0],$=v[1]/N[1],_=1/T,L=1/$,z=2*Math.ceil(_)+2,O=2*Math.ceil(L)+2;for(let V=0;V<p;V++){const U=V*o[0];for(let X=0;X<c;X++){const ne=U+X*o[1],ae=Math.floor(X*_),Ie=Math.floor(ae-z/2);for(let me=0;me<h;me++){const we=ne+me*o[2],$e=Math.floor(me*L),ze=Math.floor($e-O/2);for(let We=0;We<d;We++){let Je=0;for(let nt=0;nt<z;nt++){const lt=nt+Ie;if(lt<0||lt>=m)continue;const dt=U+lt*l[1],yt=lt*T;if(X===Math.min(c-1,i?Math.round(yt):Math.floor(yt)))for(let xt=0;xt<O;xt++){const Ct=xt+ze;if(Ct<0||Ct>=g)continue;const Rt=dt+Ct*l[2],tn=Ct*$;me===Math.min(h-1,i?Math.round(tn):Math.floor(tn))&&(Je+=w[Rt+We])}}y[we+We]=Je}}}}return t.makeTensorInfo(s.shape,s.dtype,y)}},$D={kernelName:Nl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dims:a}=r;zt(s,"reverse");const i=s.shape.length,o=Oe(a,s.shape);
93if(i===0)return Yo({inputs:{x:s},backend:t});const l=new kr(s.shape,s.dtype),p=t.bufferSync(s);for(let c=0;c<l.size;c++){const h=l.indexToLoc(c),d=h.slice();o.forEach(m=>d[m]=s.shape[m]-1-d[m]),l.set(p.get(...d),...h)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}},AD={kernelName:Xh,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:r}=n,{radians:s,fillValue:a,center:i}=e,o=t,l=_t(r.dtype,j(r.shape)),[p,c,h,d]=r.shape,[m,g]=V0(i,c,h),y=Math.sin(s),w=Math.cos(s),v=o.data.get(r.dataId).values;for(let N=0;N<p;N++){const T=N*h*c*d;for(let $=0;$<c;$++){const _=$*(h*d);for(let L=0;L<h;L++){const z=L*d;for(let O=0;O<d;O++){const V=[p,$,L,O],U=V[2],X=V[1];let ne=(U-m)*w-(X-g)*y,ae=(U-m)*y+(X-g)*w;ne=Math.round(ne+m),ae=Math.round(ae+g);let Ie=a;typeof a!="number"&&(Ie=O===3?255:a[O]),ne>=0&&ne<h&&ae>=0&&ae<c&&(Ie=v[T+ae*(h*d)+ne*d+O]),l[T+_+z+O]=Ie}}}}return{dataId:o.write(l,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},RD=Wn(Fo,n=>{const e=Math.floor(n);return n-e<.5?Math.floor(n):n-e>.5?Math.ceil(n):e%2==0?e:e+1}),_D={kernelName:Fo,backendName:"cpu",kernelFunc:RD},DD={kernelName:Oc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s,updates:a}=e,{shape:i}=r,{sliceRank:o,numUpdates:l,sliceSize:p,strides:c,outputSize:h}=Dr(0,s,i),d=ep(t.bufferSync(s),t.bufferSync(a),i,h,p,l,o,c,0,!0);return t.makeTensorInfo(i,d.dtype,d.values)}};function FD(n,e){let t=0,r=n.length,s=0;for(;t<r;)s=Math.floor((t+r)/2),n[s]<e?t=s+1:r=s;return r}function MD(n,e){let t=0,r=n.length,s=0;for(;t<r;)s=Math.floor((t+r)/2),n[s]<=e?t=s+1:r=s;return r}const OD={kernelName:cu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{sortedSequence:s,values:a}=e,{side:i}=r,o=function(l,p,c,h,d,m){const g=Zt("int32",c*d);for(let y=0;y<c;++y){const w=l.slice(y*h,(y+1)*h),v=y*d;for(let N=0;N<d;++N)g[v+N]=m==="left"?FD(w,p[N+v]):MD(w,p[N+v])}return g}(t.data.get(s.dataId).values,t.data.get(a.dataId).values,s.shape[0],s.shape[1],a.shape[1],i);return t.makeTensorInfo(a.shape,"int32",o)}},LD={kernelName:Il,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{condition:r,t:s,e:a}=e;zt([r,s,a],"select");const i=r.shape.length,o=t.data.get(r.dataId).values,l=t.data.get(s.dataId).values,p=t.data.get(a.dataId).values,c=Cs(s.dtype,a.dtype),h=Er(j(s.shape),c);let d=0;const m=i===0||i>1||s.shape.length===1?1:j(s.shape.slice(1));for(let g=0;g<o.length;g++)for(let y=0;y<m;y++)o[g]===1?h[d++]=l[g]:h[d++]=p[g];return t.makeTensorInfo(s.shape,c,h)}},zD=cg,PD=hg,BD=Wn(Sl,n=>n>=0?PD*n:zD*(Math.exp(n)-1)),VD={kernelName:Sl,backendName:"cpu",kernelFunc:BD},UD=Wn(hu,n=>n<0?-1:n>0?1:0),WD={kernelName:hu,backendName:"cpu",kernelFunc:UD},GD=Wn(zi,n=>Math.sin(n)),HD={kernelName:zi,backendName:"cpu",kernelFunc:GD},jD=Wn(Mo,n=>Math.sinh(n)),KD={kernelName:Mo,backendName:"cpu",kernelFunc:jD},uI=Math.log(11920928955078125e-23)+2,qD=Wn(pu,n=>{const e=n>-uI,t=n<uI,r=Math.exp(n);let s;return s=t?r:e?n:Math.log(1+r),s}),XD={kernelName:pu,backendName:"cpu",kernelFunc:qD},YD={kernelName:Tl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,paddings:i}=r;zt([s],"spaceToBatchND");const o=j(a),l=[[0,0]];l.push(...i);for(let w=1+a.length;w<s.shape.length;++w)l.push([0,0]);const p=oI.kernelFunc({inputs:{x:s},backend:t,attrs:{paddings:l,constantValue:0}}),c=pf(p.shape,a,o,!1),h=ff(c.length,a.length,!1),d=mf(p.shape,a,o,!1),m=or({inputs:{x:p},backend:t,attrs:{shape:c}}),g=da({inputs:{x:m},backend:t,attrs:{perm:h}}),y=or({inputs:{x:g},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),y}},ZD={kernelName:Cl,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{indices:r,values:s,denseShape:a,defaultValue:i}=e;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
94        ${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
95        ${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
96        ${s.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
97        ${i.shape}`);const o=t.data.get(r.dataId).values,l=t.data.get(s.dataId).values,p=t.data.get(a.dataId).values,c=t.data.get(i.dataId).values[0],[h,d,m,g,y]=DN(o,r.shape,r.dtype,l,s.dtype,p,c);return[t.makeTensorInfo(d,r.dtype,h),t.makeTensorInfo([d[0]],s.dtype,m),t.makeTensorInfo([g.length],"bool",new Uint8Array(g.map(w=>Number(w)))),t.makeTensorInfo([y.length],r.dtype,new Int32Array(y))]}},QD={kernelName:$l,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{inputIndices:r,inputShape:s,newShape:a}=e;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
98        ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
99        ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(t.data.get(s.dataId).values),o=t.data.get(r.dataId).values,l=Array.from(t.data.get(a.dataId).values),[p,c,h]=FN(o,r.shape,r.dtype,i,l);return[t.makeTensorInfo(c,r.dtype,p),t.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},JD={kernelName:qh,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");
vendor: 8,350 bytes, lines 99-103
99if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
100          ${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
101          ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=t.data.get(r.dataId).values,o=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values,[p,c]=bx(i,r.shape,r.dtype,o,l,!0);return t.makeTensorInfo(c,r.dtype,p)}},eF={kernelName:gu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
102         ${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
103         ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=t.data.get(r.dataId).values,o=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values,[p,c]=bx(i,r.shape,r.dtype,o,l);return t.makeTensorInfo(c,r.dtype,p)}},tF={kernelName:yu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{sparseIndices:s,sparseValues:a,defaultValue:i}=e,{outputShape:o}=r,{sliceRank:l,numUpdates:p,sliceSize:c,strides:h,outputSize:d}=Dr(0,s,o),m=!1,g=t.bufferSync(s);let y;switch(a.dtype){case"bool":y=ep(g,t.bufferSync(a),o,d,c,p,l,h,!!t.data.get(i.dataId).values[0],m);break;case"float32":case"int32":y=ep(g,t.bufferSync(a),o,d,c,p,l,h,t.data.get(i.dataId).values[0],m);break;case"string":y=ep(g,t.bufferSync(a),o,d,c,p,l,h,gr(t.data.get(i.dataId).values[0]),m);break;default:throw new Error(`Unsupported type ${a.dtype}`)}return t.makeTensorInfo(o,y.dtype,y.values)}},nF={kernelName:El,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{numOrSizeSplits:a,axis:i}=r,o=Oe(i,s.shape)[0],l=r1(s,a,o),p=new Array(s.shape.length).fill(0),c=s.shape.slice();return l.map(h=>{const d=[...c];d[o]=h;const m=Ch({inputs:{x:s},backend:t,attrs:{begin:p,size:d}});return p[o]+=h,m})}},rF={kernelName:zc,backendName:"cpu",kernelFunc:({inputs:n,backend:e})=>{const{x:t}=n,r=e;zt(t,"square");const s=r.data.get(t.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){const o=s[i];a[i]=o*o}return{dataId:r.write(a,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}},sF=Wn(ra,(n,e)=>{const t=e;return isNaN(n)?NaN:n>0?1:t.alpha}),aF={kernelName:ra,backendName:"cpu",kernelFunc:sF},iF={kernelName:Pi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,end:i,strides:o,beginMask:l,endMask:p,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=r;zt(s,"stridedSlice");const{finalShapeSparse:m,finalShape:g,isIdentity:y,sliceDim0:w,isSimpleSlice:v,begin:N,end:T,strides:$}=pr(s.shape,a,i,o,l,p,c,h,d);let _;if(y)_=or({inputs:{x:s},backend:t,attrs:{shape:g}});else if(w||v){A(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const L=u(N,T,$),z=Ch({inputs:{x:s},backend:t,attrs:{begin:N,size:L}});_=or({inputs:{x:z},backend:t,attrs:{shape:g}}),t.disposeIntermediateTensorInfo(z)}else{const L=LN(m,t.bufferSync(s),$,N);_=t.makeTensorInfo(g,L.dtype,L.values)}return _}},oF={kernelName:rs,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:p}=r,{data:c,dataSplits:h}=e,d=t.data.get(c.dataId).values,m=t.data.get(h.dataId).values,[g,y]=zN(d,m,s,a,i,o,l,p);return[t.makeTensorInfo([g.length],"string",g),t.makeTensorInfo(h.shape,"int32",y)]}},uF={kernelName:Bi,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{skipEmpty:s}=r,{input:a,delimiter:i}=e;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=t.data.get(a.dataId).values,l=t.data.get(i.dataId).values[0],[p,c,h]=PN(o,l,s),d=c.length;return[t.makeTensorInfo([d,2],"int32",p),t.makeTensorInfo([d],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(h))]}},lF={kernelName:ss,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{numBuckets:s}=r,{input:a}=e;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=BN(t.data.get(a.dataId).values,s);return t.makeTensorInfo(a.shape,"int32",i)}},cF=Wn(xu,n=>Math.tan(n)),hF={kernelName:xu,backendName:"cpu",kernelFunc:cF},dF=Wn(wu,n=>Math.tanh(n)),pF={kernelName:Li,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t}=n,{tensor:r,indices:s,updates:a}=e,{sliceRank:i,numUpdates:o,sliceSize:l,strides:p,outputSize:c}=Dr(0,s,r.shape),h=t.bufferSync(s),d=t.bufferSync(a),m=t.bufferSync(r),g=ep(h,d,r.shape,c,l,o,i,p,m,!1);return t.makeTensorInfo(r.shape,g.dtype,g.values)}},fF={kernelName:vu,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{reps:a}=r;zt(s,"tile");const i=UN(t.bufferSync(s),a);return t.makeTensorInfo(i.shape,i.dtype,i.values)}},mF={kernelName:Pc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{k:a,sorted:i}=r;zt(s,"topk");const o=t.data.get(s.dataId).values,[l,p]=GN(o,s.shape,s.dtype,a,i);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(p.shape,p.dtype,p.values)]}},gF={kernelName:Bc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,attrs:t,backend:r}=n,{image:s,transforms:a}=e,{interpolation:i,fillMode:o,fillValue:l,outputShape:p}=t,[c,h,d,m]=s.shape,[g,y]=p??[h,d],w=[c,g,y,m],v=Ge(s.shape),N=v[0],T=v[1],$=v[2],_=Ge(w),L=_[0],z=_[1],O=_[2],V=_t(s.dtype,j(w));V.fill(l);const U=r.data.get(s.dataId).values,X=r.data.get(a.dataId).values;for(let ne=0;ne<c;++ne){const ae=a.shape[0]===1?X:X.subarray(8*ne,8*ne+8);for(let Ie=0;Ie<g;++Ie)for(let me=0;me<y;++me)for(let we=0;we<m;++we){let $e;const ze=ae[6]*me+ae[7]*Ie+1;if(ze===0)continue;const We=(ae[0]*me+ae[1]*Ie+ae[2])/ze,Je=(ae[3]*me+ae[4]*Ie+ae[5])/ze,nt=lI(We,d,o),lt=lI(Je,h,o);switch(i){case"nearest":$e=yF(U,h,d,N,T,$,ne,lt,nt,we,l);break;case"bilinear":$e=bF(U,h,d,N,T,$,ne,lt,nt,we,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}V[ne*L+Ie*z+me*O+we]=$e}return r.makeTensorInfo(w,s.dtype,V)}return{dataId:r.write(V,w,s.dtype),shape:s.shape,dtype:s.dtype}}};function lI(n,e,t){switch(t){case"reflect":return function(r,s){let a=r;if(a<0)if(s<=1)a=0;else{const i=2*s;a<i&&(a=i*Math.trunc(-a/i)+a),a=a<-s?a+i:-a-1}else if(a>s-1)if(s<=1)a=0;else{const i=2*s;a-=i*Math.trunc(a/i),a>=s&&(a=i-a-1)}return te(0,a,s-1)}(n,e);case"wrap":return function(r,s){let a=r;if(a<0)if(s<=1)a=0;else{const i=s-1;a+=s*(Math.trunc(-a/i)+1)}else if(a>s-1)if(s<=1)a=0;else{const i=s-1;a-=s*Math.trunc(a/i)}return te(0,a,s-1)}(n,e);case"nearest":return function(r,s){return te(0,r,s-1)}(n,e);default:return n}}function Lf(n,e,t,r,s,a,i,o,l,p,c){return 0<=o&&o<e&&0<=l&&l<t?n[i*r+o*s+l*a+p]:c}function yF(n,e,t,r,s,a,i,o,l,p,c){return Lf(n,e,t,r,s,a,i,Math.round(o),Math.round(l),p,c)}function bF(n,e,t,r,s,a,i,o,l,p,c){const h=Math.floor(o),d=Math.floor(l),m=h+1,g=d+1;return(m-o)*((g-l)*Lf(n,e,t,r,s,a,i,h,d,p,c)+(l-d)*Lf(n,e,t,r,s,a,i,h,g,p,c))+(o-h)*((g-l)*Lf(n,e,t,r,s,a,i,m,d,p,c)+(l-d)*Lf(n,e,t,r,s,a,i,m,g,p,c))}const xF={kernelName:Vc,backendName:"cpu",kernelFunc:function(n){const{inputs:e,attrs:t,backend:r}=n,{axis:s}=t,{x:a}=e;zt(a,"unique");const i=r.data.get(a.dataId).values,{outputValues:o,outputShape:l,indices:p}=HN(i,s,a.shape,a.dtype);return[r.makeTensorInfo(l,a.dtype,o),r.makeTensorInfo([p.length],"int32",p)]}},wF={kernelName:na,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{value:s}=e;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s.shape.length,o=s.shape[a],l=new Array(i-1);let p=0;for(let m=0;m<i;m++)m!==a&&(l[p++]=s.shape[m]);const c=new Array(i).fill(0),h=s.shape.slice();h[a]=1;const d=new Array(o);for(let m=0;m<d.length;m++){c[a]=m;const g=Ch({inputs:{x:s},backend:t,attrs:{begin:c,size:h}});d[m]=or({inputs:{x:g},backend:t,attrs:{shape:l}}
103),t.disposeIntermediateTensorInfo(g)}return d}},vF={kernelName:mr,backendName:"cpu",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,segmentIds:a}=e,{numSegments:i}=r;zt(s,"unsortedSegmentSum");const o=[],l=[],p=s.shape.length-a.shape.length;let c=a;for(let d=0;d<p;++d){const m=sy({inputs:{input:c},backend:t,attrs:{dim:d+1}});c=m,l.push(m)}for(let d=0;d<i;++d){const m=Bn(d,"int32"),g=t.makeTensorInfo([],"int32",m),y=nN({inputs:{a:g,b:c},backend:t}),w=lc({inputs:{x:y},backend:t,attrs:{dtype:"float32"}}),v=ty({inputs:{a:w,b:s},backend:t}),N=Of({inputs:{x:v},backend:t,attrs:{axis:0,keepDims:!1}});o.push(N),l.push(g),l.push(y),l.push(w),l.push(v),l.push(N)}const h=iI({inputs:o,backend:t,attrs:{axis:0}});return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),h}},kF=[nR,jA,sR,iR,QA,oR,uR,lR,cR,hR,pR,mR,yR,wR,kR,NR,IR,SR,TR,tR,ER,CR,$R,e4,AR,YA,n4,_R,KA,DR,MR,OR,LR,zR,PR,BR,VR,WR,HR,jR,KR,qR,XR,YR,ZR,QR,JR,e_,t_,n_,r_,s_,i_,q4,o_,r4,m_,s4,g_,i4,x_,w_,v_,u4,c4,k_,N_,I_,S_,d4,f4,qA,T_,FR,C_,A_,__,X4,g4,b4,D_,w4,M_,z_,B_,W_,G_,H_,j_,k4,K_,q_,X_,Y_,Z_,Q_,J_,I4,eD,rD,aD,T4,E4,oD,lD,hD,$4,dD,fD,mD,oI,bD,Z4,R4,xD,wD,vD,kD,XA,kx,ID,Q4,J4,eR,SD,TD,ED,CD,$D,AD,_D,D4,DD,OD,LD,VD,M4,WD,HD,KD,O4,sD,XD,YD,ZD,QD,JD,eF,tF,nF,P4,rF,V4,W4,aF,iF,oF,uF,lF,K4,a_,hF,{kernelName:wu,backendName:"cpu",kernelFunc:dF},pF,fF,mF,gF,A4,xF,wF,vF,pD];for(const n of kF)Wc(n);const $h={},iy={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function cI(n,e){$h[n]=e}function ho(n,e){if(!(n in $h)||e!=null){const r=function(s,a){if(s!==1&&s!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const i=a??function(o){if(xe().getBool("IS_SAFARI")||typeof OffscreenCanvas>"u"||o!==2){if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(s);return i.addEventListener("webglcontextlost",o=>{o.preventDefault(),delete $h[s]},!1),xe().getBool("SOFTWARE_WEBGL_ENABLED")&&(iy.failIfMajorPerformanceCaveat=!1),s===1?i.getContext("webgl",iy)||i.getContext("experimental-webgl",iy):i.getContext("webgl2",iy)}(n,e);if(r===null)return console.log("Could not get context for WebGL version",n),null;$h[n]=r}const t=$h[n];return t==null||t.isContextLost()?(delete $h[n],ho(n)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),$h[n])}var zf,Ka,Ns;function Pf(n,e){return[e,n]}function oy(n){const e=j(n);return Me(Math.ceil(e/4))}function rp(n,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(n/2))]}function Sx(n,e){const t=n;let r,s,a,i,o,l,p,c,h,d;return xe().getNumber("WEBGL_VERSION")===2?(r=t.R32F,s=t.R16F,a=t.RGBA16F,i=t.RGBA32F,o=t.RED,p=4,c=1,h=t.HALF_FLOAT,d=t.FLOAT,l=t.RGBA8):(r=n.RGBA,s=n.RGBA,a=n.RGBA,i=t.RGBA,o=n.RGBA,p=4,c=4,h=e!=null?e.HALF_FLOAT_OES:null,d=n.FLOAT,l=n.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:p,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:d}}function kt(n,e){const t=e();return xe().getBool("DEBUG")&&function(r){const s=r.getError();if(s!==r.NO_ERROR)throw new Error("WebGL Error: "+dI(r,s))}(n),t}(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(zf||(zf={})),function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"}(Ka||(Ka={})),function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Ns||(Ns={}));const NF=596e-10,IF=65504;function hI(n){return!!(xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||NF<Math.abs(n)&&Math.abs(n)<IF)}function dI(n,e){switch(e){case n.NO_ERROR:return"NO_ERROR";case n.INVALID_ENUM:return"INVALID_ENUM";case n.INVALID_VALUE:return"INVALID_VALUE";case n.INVALID_OPERATION:return"INVALID_OPERATION";case n.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case n.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case n.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${e}`}}function Bf(n,e){return Hu(n,()=>n.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function pI(n,e){const t=Hu(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(kt(n,()=>n.shaderSource(t,e)),kt(n,()=>n.compileShader(t)),n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(t)),new Error("Failed to compile vertex shader.");return t}function fI(n,e){const t=Hu(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(kt(n,()=>n.shaderSource(t,e)),kt(n,()=>n.compileShader(t)),xe().get("ENGINE_COMPILE_ONLY"))return t;if(n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw Tx(e,n.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}const SF=/ERROR: [0-9]+:([0-9]+):/g;function Tx(n,e){const t=SF.exec(e);if(t==null)return console.log(`Couldn't parse line number in error: ${e}`),void console.log(n);const r=+t[1],s=n.split(`
104`),a=s.length.toString().length+2,i=s.map((h,d)=>jt((d+1).toString(),a)+h);let o=0;for(let h=0;h<i.length;h++)o=Math.max(i[h].length,o);const l=i.slice(0,r-1),p=i.slice(r-1,r),c=i.slice(r);console.log(l.join(`
105`)),console.log(e.split(`
106`)[0]),console.log(`%c ${jt(p[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
107`))}function mI(n){return Hu(n,()=>n.createProgram(),"Unable to create WebGLProgram.")}function gI(n,e){if(kt(n,()=>n.linkProgram(e)),!xe().get("ENGINE_COMPILE_ONLY")&&n.getProgramParameter(e,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function uy(n,e){if(kt(n,()=>n.validateProgram(e)),n.getProgramParameter(e,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function yI(n,e){const t=Hu(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return kt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),kt(n,()=>n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function bI(n,e){const t=Hu(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return kt(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t)),kt(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function TF(){return xe().getNumber("WEBGL_VERSION")===2?1:4}function xI(n){return Hu(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function wI(n,e){const t=xe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||e<=0)throw new Error(`Requested texture size [${n}x${e}] is invalid.`);if(n>t||e>t)throw new Error(`Requested texture size [${n}x${e}] greater than WebGL maximum on this browser / GPU [${t}x${t}].`)}function vI(n){return Hu(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Ex(n,e,t,r,s,a,i){const o=n.getAttribLocation(e,t);return o!==-1&&(kt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,r)),kt(n,()=>n.vertexAttribPointer(o,s,n.FLOAT,!1,a,i)),kt(n,()=>n.enableVertexAttribArray(o)),!0)}function kI(n,e,t){EI(n,t),kt(n,()=>n.activeTexture(n.TEXTURE0+t)),kt(n,()=>n.bindTexture(n.TEXTURE_2D,e))}function EF(n,e){EI(n,e),kt(n,()=>n.activeTexture(n.TEXTURE0+e)),kt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function NI(n,e,t){return Hu(n,()=>n.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function II(n,e,t){return n.getUniformLocation(e,t)}function SI(n,e,t,r){kt(n,()=>kI(n,e,r)),kt(n,()=>n.uniform1i(t,r))}function CF(n){kt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,null)),kt(n,()=>n.viewport(0,0,n.canvas.width,n.canvas.height)),kt(n,()=>n.scissor(0,0,n.canvas.width,n.canvas.height))}function ly(n,e,t){kt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),kt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0))}function Cx(n,e){kt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),kt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function Vf(n){const e=n.checkFramebufferStatus(n.FRAMEBUFFER);if(e!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+TI(n,e))}function TI(n,e){switch(e){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${e}`}}function Hu(n,e,t){const r=kt(n,()=>e());if(r==null)throw new Error(t);return r}function EI(n,e){const t=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+n.TEXTURE0;if(r<n.TEXTURE0||r>t)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${t}].`)}function Ah(n,e=2){return j(n.slice(0,n.length-e))}function Rh(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function Uf(n){let e=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(e=[Ah(n),...Rh(n)]),e}function CI(n,e=!1){let t=xe().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=xe().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");r===1/0&&xe().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=t/2),e&&(t*=2,r*=2,(n=n.map((o,l)=>l>=n.length-2?Ce(n[l]):n[l])).length===1&&(n=[2,n[0]])),n.length!==2&&(n=je(n).newShape);let s=j(n),a=null;n.length<=1&&s<=t?a=[1,s]:n.length===2&&n[0]<=t&&n[1]<=t?a=n:n.length===3&&n[0]
107*n[1]<=t&&n[2]<=t?a=[n[0]*n[1],n[2]]:n.length===3&&n[0]<=t&&n[1]*n[2]<=t?a=[n[0],n[1]*n[2]]:n.length===4&&n[0]*n[1]*n[2]<=t&&n[3]<=t?a=[n[0]*n[1]*n[2],n[3]]:n.length===4&&n[0]<=t&&n[1]*n[2]*n[3]<=t&&(a=[n[0],n[1]*n[2]*n[3]]);const i=a!=null&&Math.max(...a)>r&&Math.min(...a)<=(e?2:1)&&Math.min(...a)>0;if(a==null||i)if(e){const o=Ah(n);let l=2,p=2;n.length&&([l,p]=Rh(n)),s=o*(l/2)*(p/2),a=Me(s).map(c=>2*c)}else a=Me(s);return a}function cy(n){return n%2==0}function Wf(n,e){if(le(n=n.slice(-2),e=e.slice(-2))||!n.length||!e.length||n[0]===0||n[1]===0||e[0]===0||e[1]===0)return!0;if(n.length!==e.length){const t=n[n.length-1],r=e[e.length-1];if(t===r||cy(t)&&cy(r)&&(n[0]===1||e[0]===1))return!0}return n[1]===e[1]&&cy(n[0])&&cy(e[0])}let hy,dy;function $I(n){if(hy==null){const e=ho(n);hy=e.getParameter(e.MAX_TEXTURE_SIZE)}return hy}function $F(){hy=null}function AF(){dy=null}function AI(n){if(dy==null){const e=ho(n);dy=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,dy)}function RI(n){if(n===0)return 0;let e;const t=ho(n);return e=qa(t,"EXT_disjoint_timer_query_webgl2")&&n===2?2:qa(t,"EXT_disjoint_timer_query")?1:0,e}function qa(n,e){return n.getExtension(e)!=null}function $x(n){try{if(ho(n)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function _I(n){if(n===0)return!1;const e=ho(n);if(n===1){if(!qa(e,"OES_texture_float"))return!1}else if(!qa(e,"EXT_color_buffer_float"))return!1;return Ax(e)}function DI(n){if(n===0)return!1;const e=ho(n);if(n!==1){if(qa(e,"EXT_color_buffer_float"))return Ax(e);const t="EXT_color_buffer_half_float";if(qa(e,t)){const r=e.getExtension(t);return function(s,a){const i=Sx(s,a),o=s.createTexture();s.bindTexture(s.TEXTURE_2D,o),s.texImage2D(s.TEXTURE_2D,0,i.internalFormatHalfFloat,1,1,0,i.textureFormatFloat,i.textureTypeHalfFloat,null);const l=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,l),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,o,0);const p=s.checkFramebufferStatus(s.FRAMEBUFFER)===s.FRAMEBUFFER_COMPLETE;return s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.deleteTexture(o),s.deleteFramebuffer(l),p}(e,r)}return!1}return!!qa(e,"OES_texture_float")&&!!qa(e,"WEBGL_color_buffer_float")&&Ax(e)}function Ax(n){const e=Sx(n),t=n.createTexture();n.bindTexture(n.TEXTURE_2D,t),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);const r=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,r),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0);const s=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(t),n.deleteFramebuffer(r),s}function FI(n){return n===2&&ho(n).fenceSync!=null}function sp(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&A(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}const Bt=xe();function Ks(){let n,e,t,r,s,a,i,o,l,p;return xe().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",e="in",t="out",r="in",s="texture",a="outputColor",i="out vec4 outputColor;",o=xe().getBool("WEBGL2_ISNAN_CUSTOM")?`
108      bool isnan_custom(float val) {
109        uint floatToUint = floatBitsToUint(val);
110        return (floatToUint & 0x7fffffffu) > 0x7f800000u;
111      }
112
113      bvec4 isnan_custom(vec4 val) {
114        return bvec4(isnan_custom(val.x),
115          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
116      }
117
118      #define isnan(value) isnan_custom(value)
119    `:"",l="",p=`
120      #define round(value) newRound(value)
121      int newRound(float value) {
122        return int(floor(value + 0.5));
123      }
124
125      ivec4 newRound(vec4 value) {
126        return ivec4(floor(value + vec4(0.5)));
127      }
128    `):(n="",e="attribute",t="varying",r="varying",s="texture2D",a="gl_FragColor",i="",o=`
129      #define isnan(value) isnan_custom(value)
130      bool isnan_custom(float val) {
131        return (val > 0. || val < 1. || val == 0.) ? false : true;
132      }
133      bvec4 isnan_custom(vec4 val) {
134        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
135      }
136    `,l=`
137      uniform float INFINITY;
138
139      bool isinf(float val) {
140        return abs(val) == INFINITY;
141      }
142      bvec4 isinf(vec4 val) {
143        return equal(abs(val), vec4(INFINITY));
144      }
145    `,p=`
146      int round(float value) {
147        return int(floor(value + 0.5));
148      }
149
150      ivec4 round(vec4 value) {
151        return ivec4(floor(value + vec4(0.5)));
152      }
153    `),{version:n,attribute:e,varyingVs:t,varyingFs:r,texture2D:s,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:p}}function _h(n,e,t="index"){const r=Ge(e);return r.map((s,a)=>`int ${n[a]} = ${t} / ${s}; ${a===r.length-1?`int ${n[a+1]} = ${t} - ${n[a]} * ${s}`:`index -= ${n[a]} * ${s}`};`).join("")}function py(n,e,t="index"){const r=Ge(e);return r.map((s,a)=>`int ${n[a]} = ${t} / outShapeStrides[${a}]; ${a===r.length-1?`int ${n[a+1]} = ${t} - ${n[a]} * outShapeStrides[${a}]`:`index -= ${n[a]} * outShapeStrides[${a}]`};`).join("")}function Rx(n){const e=Ge(n).map(t=>t.toString());return`
154  int getFlatIndex(ivec3 coords) {
155    return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
156  }
157`}
vendor: 5,208 bytes, lines 157-196
157Bt.registerFlag("HAS_WEBGL",()=>Bt.getNumber("WEBGL_VERSION")>0),Bt.registerFlag("WEBGL_VERSION",()=>$x(2)?2:$x(1)?1:0),Bt.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Bt.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Bt.get("WEBGL_VERSION")===2),Bt.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Bt.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Bt.registerFlag("WEBGL_PACK",()=>Bt.getBool("HAS_WEBGL")),Bt.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_CLIP",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_REDUCE",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_LAZILY_UNPACK",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_CONV_IM2COL",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>Bt.getBool("WEBGL_PACK")),Bt.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>$I(Bt.getNumber("WEBGL_VERSION"))),Bt.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>AI(Bt.getNumber("WEBGL_VERSION"))),Bt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=Bt.getNumber("WEBGL_VERSION");return n===0?0:RI(n)}),Bt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Bt.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!rd()),Bt.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>_I(Bt.getNumber("WEBGL_VERSION"))),Bt.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>!Bt.getBool("WEBGL_FORCE_F16_TEXTURES")&&Bt.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Bt.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>DI(Bt.getNumber("WEBGL_VERSION"))),Bt.registerFlag("WEBGL_FENCE_API_ENABLED",()=>FI(Bt.getNumber("WEBGL_VERSION"))),Bt.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Bt.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),Bt.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)}),Bt.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>rd()?1:-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)}),Bt.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),Bt.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),Bt.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),Bt.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),Bt.registerFlag("WEBGL_EXP_CONV",()=>!1),Bt.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>Bt.getBool("IS_TEST")),Bt.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),Bt.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),Bt.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),Bt.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);const MI=`
158  const float FLOAT_MAX = 1.70141184e38;
159  const float FLOAT_MIN = 1.17549435e-38;
160
161  lowp vec4 encode_float(highp float v) {
162    if (isnan(v)) {
163      return vec4(255, 255, 255, 255);
164    }
165
166    highp float av = abs(v);
167
168    if(av < FLOAT_MIN) {
169      return vec4(0.0, 0.0, 0.0, 0.0);
170    } else if(v > FLOAT_MAX) {
171      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
172    } else if(v < -FLOAT_MAX) {
173      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;
174    }
175
176    highp vec4 c = vec4(0,0,0,0);
177
178    highp float e = floor(log2(av));
179    highp float m = exp2(fract(log2(av))) - 1.0;
180
181    c[2] = floor(128.0 * m);
182    m -= c[2] / 128.0;
183    c[1] = floor(32768.0 * m);
184    m -= c[1] / 32768.0;
185    c[0] = floor(8388608.0 * m);
186
187    highp float ebias = e + 127.0;
188    c[3] = floor(ebias / 2.0);
189    ebias -= c[3] * 2.0;
190    c[2] += floor(ebias) * 128.0;
191
192    c[3] += 128.0 * step(0.0, -v);
193
194    return c / 255.0;
195  }
196`,{getBroadcastDims:OI}=de;function RF(n,e,t){const r=[];if(n.forEach(d=>{const m=j(d.shapeInfo.logicalShape);if(d.shapeInfo.isUniform?r.push(`uniform float ${d.name}${m>1?`[${m}]`:""};`):(r.push(`uniform sampler2D ${d.name};`),r.push(`uniform int offset${d.name};`)),t.enableShapeUniforms){const{uniformShape:g}=_x(t.packedInputs,d.shapeInfo.logicalShape,d.shapeInfo.texShape);switch(g.length){case 1:r.push(`uniform int ${d.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${d.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${d.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${d.name}Shape;`)}r.push(`uniform ivec2 ${d.name}TexShape;`)}}),t.enableShapeUniforms){switch(e.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}
196t.customUniforms&&t.customUniforms.forEach(d=>{r.push(`uniform ${d.type} ${d.name}${d.arrayIndex?`[${d.arrayIndex}]`:""};`)});const s=r.join(`
197`),a=n.map(d=>function(m,g,y=!1,w){let v="";v+=y?LI(m,w):ap(m,w);const N=m.shapeInfo.logicalShape,T=g.logicalShape;return N.length<=T.length&&(v+=y?function($,_){const L=$.name,z=L.charAt(0).toUpperCase()+L.slice(1),O="get"+z+"AtOutCoords",V=$.shapeInfo.logicalShape.length,U=_.logicalShape.length,X=OI($.shapeInfo.logicalShape,_.logicalShape),ne=Xn(U),ae=U-V;let Ie;const me=["x","y","z","w","u","v"];Ie=V===0?"":U<2&&X.length>=1?"coords = 0;":X.map(Je=>`coords.${me[Je+ae]} = 0;`).join(`
198`);let we="";we=U<2&&V>0?"coords":$.shapeInfo.logicalShape.map((Je,nt)=>`coords.${me[nt+ae]}`).join(", ");let $e="return outputValue;";const ze=j($.shapeInfo.logicalShape)===1,We=j(_.logicalShape)===1;if(V!==1||ze||We){if(ze&&!We)$e=U===1?`
199        return vec4(outputValue.x, outputValue.x, 0., 0.);
200      `:`
201        return vec4(outputValue.x);
202      `;else if(X.length){const Je=V-2,nt=V-1;X.indexOf(Je)>-1&&X.indexOf(nt)>-1?$e="return vec4(outputValue.x);":X.indexOf(Je)>-1?$e="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":X.indexOf(nt)>-1&&($e="return vec4(outputValue.xx, outputValue.zz);")}}else $e=`
203      return vec4(outputValue.xy, outputValue.xy);
204    `;return`
205    vec4 ${O}() {
206      ${ne} coords = getOutputCoords();
207      ${Ie}
208      vec4 outputValue = get${z}(${we});
209      ${$e}
210    }
211  `}(m,g):function($,_){const L=$.name,z=L.charAt(0).toUpperCase()+L.slice(1),O="get"+z+"AtOutCoords",V=_.texShape,U=$.shapeInfo.texShape,X=$.shapeInfo.logicalShape.length,ne=_.logicalShape.length;if(!$.shapeInfo.isUniform&&X===ne&&$.shapeInfo.flatOffset==null&&le(U,V))return`
212      float ${O}() {
213        return sampleTexture(${L}, resultUV);
214      }
215    `;const ae=Xn(ne),Ie=OI($.shapeInfo.logicalShape,_.logicalShape),me=ne-X;let we;const $e=["x","y","z","w","u","v"];we=X===0?"":ne<2&&Ie.length>=1?"coords = 0;":Ie.map(We=>`coords.${$e[We+me]} = 0;`).join(`
216`);let ze="";return ze=ne<2&&X>0?"coords":$.shapeInfo.logicalShape.map((We,Je)=>`coords.${$e[Je+me]}`).join(", "),`
217    float ${O}() {
218      ${ae} coords = getOutputCoords();
219      ${we}
220      return get${z}(${ze});
221    }
222  `}(m,g)),v}(d,e,t.packedInputs,t.enableShapeUniforms)).join(`
223`),i=e.texShape,o=Ks(),l=function(d){return`
224    float sampleTexture(sampler2D textureSampler, vec2 uv) {
225      return ${d.texture2D}(textureSampler, uv).r;
226    }
227  `}(o);let p,c,h=function(d){return`${d.version}
228    precision highp float;
229    precision highp int;
230    precision highp sampler2D;
231    ${d.varyingFs} vec2 resultUV;
232    ${d.defineOutput}
233    const vec2 halfCR = vec2(0.5, 0.5);
234
235    struct ivec5
236    {
237      int x;
238      int y;
239      int z;
240      int w;
241      int u;
242    };
243
244    struct ivec6
245    {
246      int x;
247      int y;
248      int z;
249      int w;
250      int u;
251      int v;
252    };
253
254    uniform float NAN;
255    ${d.defineSpecialNaN}
256    ${d.defineSpecialInf}
257    ${d.defineRound}
258
259    int imod(int x, int y) {
260      return x - y * (x / y);
261    }
262
263    int idiv(int a, int b, float sign) {
264      int res = a / b;
265      int mod = imod(a, b);
266      if (sign < 0. && mod != 0) {
267        res -= 1;
268      }
269      return res;
270    }
271
272    //Based on the work of Dave Hoskins
273    //https://www.shadertoy.com/view/4djSRW
274    #define HASHSCALE1 443.8975
275    float random(float seed){
276      vec2 p = resultUV * seed;
277      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);
278      p3 += dot(p3, p3.yzx + 19.19);
279      return fract((p3.x + p3.y) * p3.z);
280    }
281
282    ${_F}
283    ${DF}
284    ${FF}
285  `}(o);return e.isPacked?(p=function(d,m,g){switch(d.length){case 0:return`
286    int getOutputCoords() {
287      return 0;
288    }
289  `;case 1:return function(y,w,v){const N=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];return N[0]===1?v?`
290      int getOutputCoords() {
291        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
292      }
293    `:`
294      int getOutputCoords() {
295        return 2 * int(resultUV.x * ${N[1]}.0);
296      }
297    `:N[1]===1?v?`
298      int getOutputCoords() {
299        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
300      }
301    `:`
302      int getOutputCoords() {
303        return 2 * int(resultUV.y * ${N[0]}.0);
304      }
305    `:v?`
306    int getOutputCoords() {
307      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
308      ivec2 resTexRC = ivec2(resultUV.yx *
309                             vec2(packedTexShape[0], packedTexShape[1]));
310      return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
311    }
312  `:`
313    int getOutputCoords() {
314      ivec2 resTexRC = ivec2(resultUV.yx *
315                             vec2(${N[0]}, ${N[1]}));
316      return 2 * (resTexRC.x * ${N[1]} + resTexRC.y);
317    }
318  `}(0,m,g);case 2:return function(y,w,v){const N=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];if(le(y,w))return v?`
319      ivec2 getOutputCoords() {
320        ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
321        return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
322      }
323    `:`
324      ivec2 getOutputCoords() {
325        return 2 * ivec2(resultUV.yx * vec2(${N[0]}, ${N[1]}));
326      }
327    `;const T=Math.ceil(y[1]/2);return v?`
328    ivec2 getOutputCoords() {
329      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
330      int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
331      ivec2 resTexRC = ivec2(resultUV.yx *
332                             vec2(packedTexShape[0], packedTexShape[1]));
333
334      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
335      int r = 2 * (index / texelsInLogicalRow);
336      int c = imod(index, texelsInLogicalRow) * 2;
337
338      return ivec2(r, c);
339    }
340  `:`
341    ivec2 getOutputCoords() {
342      ivec2 resTexRC = ivec2(resultUV.yx *
343                             vec2(${N[0]}, ${N[1]}));
344
345      int index = resTexRC.x * ${N[1]} + resTexRC.y;
346      int r = 2 * (index / ${T});
347      int c = imod(index, ${T}) * 2;
348
349      return ivec2(r, c);
350    }
351  `}(d,m,g);case 3:return function(y,w,v){if(v)return`
352    ivec3 getOutputCoords() {
353      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
354      int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
355      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
356      ivec2 resTexRC = ivec2(resultUV.yx *
357                             vec2(packedTexShape[0], packedTexShape[1]));
358      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
359
360      int b = index / texelsInBatch;
361      index -= b * texelsInBatch;
362
363      int r = 2 * (index / texelsInLogicalRow);
364      int c = imod(index, texelsInLogicalRow) * 2;
365
366      return ivec3(b, r, c);
367    }
368  `;const N=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)],T=Math.ceil(y[2]/2),$=T*Math.ceil(y[1]/2);return`
369    ivec3 getOutputCoords() {
370      ivec2 resTexRC = ivec2(resultUV.yx *
371                             vec2(${N[0]}, ${N[1]}));
372      int index = resTexRC.x * ${N[1]} + resTexRC.y;
373
374      int b = index / ${$};
375      index -= b * ${$};
376
377      int r = 2 * (index / ${T});
378      int c = imod(index, ${T}) * 2;
379
380      return ivec3(b, r, c);
381    }
382  `}(d,m,g);default:return function(y,w,v){if(v)return`
383    ivec4 getOutputCoords() {
384      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
385      ivec2 resTexRC = ivec2(resultUV.yx *
386                             vec2(packedTexShape[0], packedTexShape[1]));
387      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
388
389      int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
390      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
391      int texelsInBatchN = texelsInBatch * outShape[1];
392
393      int b2 = index / texelsInBatchN;
394      index -= b2 * texelsInBatchN;
395
396      int b = index / texelsInBatch;
397      index -= b * texelsInBatch;
398
399      int r = 2 * (index / texelsInLogicalRow);
400      int c = imod(index, texelsInLogicalRow) * 2;
401
402      return ivec4(b2, b, r, c);
403    }
404  `;const N=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)],T=Math.ceil(y[y.length-1]/2),$=T*Math.ceil(y[y.length-2]/2);let _=$,L="",z="b, r, c";for(let O=2;O<y.length-1;O++)_*=y[y.length-O-1],L=`
405      int b${O} = index / ${_};
406      index -= b${O} * ${_};
407    `+L,z=`b${O}, `+z;return`
408    ivec${y.length} getOutputCoords() {
409      ivec2 resTexRC = ivec2(resultUV.yx *
410                             vec2(${N[0]}, ${N[1]}));
411      int index = resTexRC.x * ${N[1]} + resTexRC.y;
412
413      ${L}
414
415      int b = index / ${$};
416      index -= b * ${$};
417
418      int r = 2 * (index / ${T});
419      int c = imod(index, ${T}) * 2;
420
421      return ivec${y.length}(${z});
422    }
423  `}(d,m,g)}}(e.logicalShape,i,t.enableShapeUniforms),c=function(d){return`
424    void setOutput(vec4 val) {
425      ${d.output} = val;
426    }
427  `}(o)):(p=function(d,m,g){switch(d.length){case 0:return`
428    int getOutputCoords() {
429      return 0;
430    }
431  `;case 1:return function(y,w,v){return w[0]===1?v?`
432      int getOutputCoords() {
433        return int(resultUV.x * float(outTexShape[1]));
434      }
435    `:`
436      int getOutputCoords() {
437        return int(resultUV.x * ${w[1]}.0);
438      }
439    `:w[1]===1?v?`
440      int getOutputCoords() {
441        return int(resultUV.y * float(outTexShape[0]));
442      }
443    `:`
444      int getOutputCoords() {
445        return int(resultUV.y * ${w[0]}.0);
446      }
447    `:v?`
448    int getOutputCoords() {
449      ivec2 resTexRC = ivec2(resultUV.yx *
450                             vec2(outTexShape[0], outTexShape[1]));
451      return resTexRC.x * outTexShape[1] + resTexRC.y;
452    }
453  `:`
454    int getOutputCoords() {
455      ivec2 resTexRC = ivec2(resultUV.yx *
456                             vec2(${w[0]}, ${w[1]}));
457      return resTexRC.x * ${w[1]} + resTexRC.y;
458    }
459  `}(0,m,g);case 2:return function(y,w,v){return le(y,w)?v?`
460      ivec2 getOutputCoords() {
461        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
462      }
463    `:`
464      ivec2 getOutputCoords() {
465        return ivec2(resultUV.yx * vec2(${w[0]}, ${w[1]}));
466      }
467    `:y[1]===1?v?`
468      ivec2 getOutputCoords() {
469        ivec2 resTexRC = ivec2(resultUV.yx *
470                               vec2(outTexShape[0], outTexShape[1]));
471        int index = resTexRC.x * outTexShape[1] + resTexRC.y;
472        return ivec2(index, 0);
473      }
474    `:`
475      ivec2 getOutputCoords() {
476        ivec2 resTexRC = ivec2(resultUV.yx *
477                               vec2(${w[0]}, ${w[1]}));
478        int index = resTexRC.x * ${w[1]} + resTexRC.y;
479        return ivec2(index, 0);
480      }
481    `:y[0]===1?v?`
482      ivec2 getOutputCoords() {
483        ivec2 resTexRC = ivec2(resultUV.yx *
484                               vec2(outTexShape[0], outTexShape[1]));
485        int index = resTexRC.x * outTexShape[1] + resTexRC.y;
486        return ivec2(0, index);
487      }
488    `:`
489      ivec2 getOutputCoords() {
490        ivec2 resTexRC = ivec2(resultUV.yx *
491                               vec2(${w[0]}, ${w[1]}));
492        int index = resTexRC.x * ${w[1]} + resTexRC.y;
493        return ivec2(0, index);
494      }
495    `:v?`
496    ivec2 getOutputCoords() {
497      ivec2 resTexRC = ivec2(resultUV.yx *
498                             vec2(outTexShape[0], outTexShape[1]));
499      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
500      int r = index / outShape[1];
501      int c = index - r * outShape[1];
502      return ivec2(r, c);
503    }
504  `:`
505    ivec2 getOutputCoords() {
506      ivec2 resTexRC = ivec2(resultUV.yx *
507                             vec2(${w[0]}, ${w[1]}));
508      int index = resTexRC.x * ${w[1]} + resTexRC.y;
509      int r = index / ${y[1]};
510      int c = index - r * ${y[1]};
511      return ivec2(r, c);
512    }
513  `}(d,m,g);case 3:return function(y,w,v){if(v)return`
514  ivec3 getOutputCoords() {
515    ivec2 resTexRC = ivec2(resultUV.yx *
516                           vec2(outTexShape[0], outTexShape[1]));
517    int index = resTexRC.x * outTexShape[1] + resTexRC.y;
518    ${py(["r","c","d"],y)}
519    return ivec3(r, c, d);
520  }
521`;const N=_h(["r","c","d"],y);return`
522    ivec3 getOutputCoords() {
523      ivec2 resTexRC = ivec2(resultUV.yx *
524                             vec2(${w[0]}, ${w[1]}));
525      int index = resTexRC.x * ${w[1]} + resTexRC.y;
526      ${N}
527      return ivec3(r, c, d);
528    }
529  `}(d,m,g);case 4:return function(y,w,v){if(v)return`
530    ivec4 getOutputCoords() {
531      ivec2 resTexRC = ivec2(resultUV.yx *
532        vec2(outTexShape[0], outTexShape[1]));
533      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
534      ${py(["r","c","d","d2"],y)}
535      return ivec4(r, c, d, d2);
536    }
537  `;const N=_h(["r","c","d","d2"],y);return`
538    ivec4 getOutputCoords() {
539      ivec2 resTexRC = ivec2(resultUV.yx *
540        vec2(${w[0]}, ${w[1]}));
541      int index = resTexRC.x * ${w[1]} + resTexRC.y;
542      ${N}
543      return ivec4(r, c, d, d2);
544    }
545  `}(d,m,g);case 5:return function(y,w){const v=_h(["r","c","d","d2","d3"],y);return`
546    ivec5 getOutputCoords() {
547      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${w[0]},
548                             ${w[1]}));
549
550      int index = resTexRC.x * ${w[1]} + resTexRC.y;
551
552      ${v}
553
554      ivec5 outShape = ivec5(r, c, d, d2, d3);
555      return outShape;
556    }
557  `}(d,m);case 6:return function(y,w){const v=_h(["r","c","d","d2","d3","d4"],y);return`
558    ivec6 getOutputCoords() {
559      ivec2 resTexRC = ivec2(resultUV.yx *
560        vec2(${w[0]}, ${w[1]}));
561      int index = resTexRC.x * ${w[1]} + resTexRC.y;
562
563      ${v}
564
565      ivec6 result = ivec6(r, c, d, d2, d3, d4);
566      return result;
567    }
568  `}(d,m);default:throw new Error(`${d.length}-D output sampling is not yet supported`)}}(e.logicalShape,i,t.enableShapeUniforms),c=function(d){return`
569    void setOutput(float val) {
570      ${d.output} = vec4(val, 0, 0, 0);
571    }
572  `}(o)),t.packedInputs&&(h+=MF),[h,l,c,s,p,a,t.userCode].join(`
573`)}function ap(n,e=!1){const t=n.shapeInfo.logicalShape;switch(t.length){case 0:return function(r,s){const a=r.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1);if(r.shapeInfo.isUniform)return`float ${i}() {return ${a};}`;const[o,l]=r.shapeInfo.texShape;if(o===1&&l===1)return`
574      float ${i}() {
575        return sampleTexture(${a}, halfCR);
576      }
577    `;const p=Dh(a);if(s)return`
578    float ${i}() {
579      vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], ${p});
580      return sampleTexture(${a}, uv);
581    }
582  `;const[c,h]=r.shapeInfo.texShape;return`
583    float ${i}() {
584      vec2 uv = uvFromFlat(${c}, ${h}, ${p});
585      return sampleTexture(${a}, uv);
586    }
587  `}(n,e);case 1:return function(r,s){const a=r.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1);if(r.shapeInfo.isUniform)return`
588      float ${i}(int index) {
589        ${ip(r)}
590      }
591    `;const o=r.shapeInfo.texShape,l=o[0],p=o[1];if(p===1&&l===1)return`
592      float ${i}(int index) {
593        return sampleTexture(${a}, halfCR);
594      }
595    `;const c=Dh(a);return p===1?s?`
596      float ${i}(int index) {
597        vec2 uv = vec2(0.5, (float(index + ${c}) + 0.5) / float(${a}TexShape[0]));
598        return sampleTexture(${a}, uv);
599      }
600    `:`
601      float ${i}(int index) {
602        vec2 uv = vec2(0.5, (float(index + ${c}) + 0.5) / ${l}.0);
603        return sampleTexture(${a}, uv);
604      }
605    `:l===1?s?`
606      float ${i}(int index) {
607        vec2 uv = vec2((float(index + ${c}) + 0.5) / float(${a}TexShape[1]), 0.5);
608        return sampleTexture(${a}, uv);
609      }
610    `:`
611      float ${i}(int index) {
612        vec2 uv = vec2((float(index + ${c}) + 0.5) / ${p}.0, 0.5);
613        return sampleTexture(${a}, uv);
614      }
615    `:s?`
616    float ${i}(int index) {
617      vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index + ${c});
618      return sampleTexture(${a}, uv);
619    }
620  `:`
621    float ${i}(int index) {
622      vec2 uv = uvFromFlat(${l}, ${p}, index + ${c});
623      return sampleTexture(${a}, uv);
624    }
625  `}(n,e);case 2:return function(r,s){const a=r.shapeInfo.logicalShape,i=r.name,o="get"+i.charAt(0).toUpperCase()+i.slice(1),l=r.shapeInfo.texShape;if(l!=null&&le(a,l)){if(s)return`
626      float ${o}(int row, int col) {
627        vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}TexShape[1], ${i}TexShape[0]);
628        return sampleTexture(${i}, uv);
629      }
630    `;const y=l[0];return`
631    float ${o}(int row, int col) {
632      vec2 uv = (vec2(col, row) + halfCR) / vec2(${l[1]}.0, ${y}.0);
633      return sampleTexture(${i}, uv);
634    }
635  `}const{newShape:p,keptDims:c}=je(a),h=p;if(h.length<a.length){const y=["row","col"];return`
636      ${ap(op(r,h),s)}
637      float ${o}(int row, int col) {
638        return ${o}(${up(y,c)});
639      }
640    `}if(r.shapeInfo.isUniform)return`
641      float ${o}(int row, int col) {
642        int index = round(dot(vec2(row, col), vec2(${a[1]}, 1)));
643        ${ip(r)}
644      }
645    `;const d=l[0],m=l[1],g=Dh(i);return m===1?s?`
646      float ${o}(int row, int col) {
647        float index = dot(vec3(row, col, ${g}), vec3(${i}Shape[1], 1, 1));
648        vec2 uv = vec2(0.5, (index + 0.5) / float(${i}TexShape[0]));
649        return sampleTexture(${i}, uv);
650      }
651    `:`
652    float ${o}(int row, int col) {
653      float index = dot(vec3(row, col, ${g}), vec3(${a[1]}, 1, 1));
654      vec2 uv = vec2(0.5, (index + 0.5) / ${d}.0);
655      return sampleTexture(${i}, uv);
656    }
657  `:d===1?s?`
658      float ${o}(int row, int col) {
659        float index = dot(vec3(row, col, ${g}), vec3(${i}Shape[1], 1, 1));
660        vec2 uv = vec2((index + 0.5) / float(${i}TexShape[1]), 0.5);
661        return sampleTexture(${i}, uv);
662      }
663    `:`
664    float ${o}(int row, int col) {
665      float index = dot(vec3(row, col, ${g}), vec3(${a[1]}, 1, 1));
666      vec2 uv = vec2((index + 0.5) / ${m}.0, 0.5);
667      return sampleTexture(${i}, uv);
668    }
669  `:s?`
670      float ${o}(int row, int col) {
671        // Explicitly use integer operations as dot() only works on floats.
672        int index = row * ${i}Shape[1] + col + ${g};
673        vec2 uv = uvFromFlat(${i}TexShape[0], ${i}TexShape[1], index);
674        return sampleTexture(${i}, uv);
675      }
676    `:`
677  float ${o}(int row, int col) {
678    // Explicitly use integer operations as dot() only works on floats.
679    int index = row * ${a[1]} + col + ${g};
680    vec2 uv = uvFromFlat(${d}, ${m}, index);
681    return sampleTexture(${i}, uv);
682  }
683`}(n,e);case 3:return function(r,s){const a=r.shapeInfo.logicalShape,i=r.name,o="get"+i.charAt(0).toUpperCase()+i.slice(1),l=a[1]*a[2],p=a[2],{newShape:c,keptDims:h}=je(a),d=c;if(d.length<a.length){const N=["row","col","depth"];return`
684        ${ap(op(r,d),s)}
685        float ${o}(int row, int col, int depth) {
686          return ${o}(${up(N,h)});
687        }
688      `}if(r.shapeInfo.isUniform)return`
689      float ${o}(int row, int col, int depth) {
690        int index = round(dot(vec3(row, col, depth),
691                          vec3(${l}, ${p}, 1)));
692        ${ip(r)}
693      }
694    `;const m=r.shapeInfo.texShape,g=m[0],y=m[1],w=r.shapeInfo.flatOffset;if(y===l&&w==null)return s?`
695      float ${o}(int row, int col, int depth) {
696        int stride1 = ${i}Shape[2];
697        float texR = float(row);
698        float texC = dot(vec2(col, depth), vec2(stride1, 1));
699        vec2 uv = (vec2(texC, texR) + halfCR) /
700                   vec2(${i}TexShape[1], ${i}TexShape[0]);
701        return sampleTexture(${i}, uv);
702      }
703    `:`
704        float ${o}(int row, int col, int depth) {
705          float texR = float(row);
706          float texC = dot(vec2(col, depth), vec2(${p}, 1));
707          vec2 uv = (vec2(texC, texR) + halfCR) /
708                     vec2(${y}.0, ${g}.0);
709          return sampleTexture(${i}, uv);
710        }
711      `;if(y===p&&w==null)return s?`
712      float ${o}(int row, int col, int depth) {
713        float texR = dot(vec2(row, col), vec2(${i}Shape[1], 1));
714        float texC = float(depth);
715        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${i}TexShape[1], ${i}TexShape[0]);
716        return sampleTexture(${i}, uv);
717      }
718    `:`
719    float ${o}(int row, int col, int depth) {
720      float texR = dot(vec2(row, col), vec2(${a[1]}, 1));
721      float texC = float(depth);
722      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}.0, ${g}.0);
723      return sampleTexture(${i}, uv);
724    }
725  `;const v=Dh(i);return s?`
726    float ${o}(int row, int col, int depth) {
727      // Explicitly use integer operations as dot() only works on floats.
728      int stride0 = ${i}Shape[1] * ${i}Shape[2];
729      int stride1 = ${i}Shape[2];
730      int index = row * stride0 + col * stride1 + depth + ${v};
731      vec2 uv = uvFromFlat(${i}TexShape[0], ${i}TexShape[1], index);
732      return sampleTexture(${i}, uv);
733    }
734    `:`
735      float ${o}(int row, int col, int depth) {
736        // Explicitly use integer operations as dot() only works on floats.
737        int index = row * ${l} + col * ${p} + depth + ${v};
738        vec2 uv = uvFromFlat(${g}, ${y}, index);
739        return sampleTexture(${i}, uv);
740      }
741  `}(n,e);case 4:return function(r,s){const a=r.shapeInfo.logicalShape,i=r.name,o="get"+i.charAt(0).toUpperCase()+i.slice(1),l=a[3],p=a[2]*l,c=a[1]*p,{newShape:h,keptDims:d}=je(a);if(h.length<a.length){const _=["row","col","depth","depth2"];return`
742      ${ap(op(r,h),s)}
743      float ${o}(int row, int col, int depth, int depth2) {
744        return ${o}(${up(_,d)});
745      }
746    `}if(r.shapeInfo.isUniform)return`
747      float ${o}(int row, int col, int depth, int depth2) {
748        int index = round(dot(vec4(row, col, depth, depth2),
749                          vec4(${c}, ${p}, ${l}, 1)));
750        ${ip(r)}
751      }
752    `;const m=r.shapeInfo.flatOffset,g=r.shapeInfo.texShape,y=g[0],w=g[1],v=`int stride2 = ${i}Shape[3];`,N=`int stride1 = ${i}Shape[2] * stride2;`,T=`int stride0 = ${i}Shape[1] * stride1;`;if(w===c&&m==null)return s?`
753      float ${o}(int row, int col, int depth, int depth2) {
754        ${v}
755        ${N}
756        float texR = float(row);
757        float texC =
758            dot(vec3(col, depth, depth2),
759                vec3(stride1, stride2, 1));
760        vec2 uv = (vec2(texC, texR) + halfCR) /
761                   vec2(${i}TexShape[1], ${i}TexShape[0]);
762        return sampleTexture(${i}, uv);
763      }
764    `:`
765      float ${o}(int row, int col, int depth, int depth2) {
766        float texR = float(row);
767        float texC =
768            dot(vec3(col, depth, depth2),
769                vec3(${p}, ${l}, 1));
770        vec2 uv = (vec2(texC, texR) + halfCR) /
771                   vec2(${w}.0, ${y}.0);
772        return sampleTexture(${i}, uv);
773      }
774    `;if(w===l&&m==null)return s?`
775      float ${o}(int row, int col, int depth, int depth2) {
776        float texR = dot(vec3(row, col, depth),
777                         vec3(${i}Shape[1] * ${i}Shape[2], ${i}Shape[2], 1));
778        float texC = float(depth2);
779        vec2 uv = (vec2(texC, texR) + halfCR) /
780                  vec2(${i}TexShape[1], ${i}TexShape[0]);
781        return sampleTexture(${i}, uv);
782      }
783    `:`
784      float ${o}(int row, int col, int depth, int depth2) {
785        float texR = dot(vec3(row, col, depth),
786                         vec3(${a[1]*a[2]}, ${a[2]}, 1));
787        float texC = float(depth2);
788        vec2 uv = (vec2(texC, texR) + halfCR) /
789                  vec2(${w}.0, ${y}.0);
790        return sampleTexture(${i}, uv);
791      }
792    `;const $=Dh(i);return s?`
793    float ${o}(int row, int col, int depth, int depth2) {
794      // Explicitly use integer operations as dot() only works on floats.
795      ${v}
796      ${N}
797      ${T}
798      int index = row * stride0 + col * stride1 +
799          depth * stride2 + depth2;
800      vec2 uv = uvFromFlat(${i}TexShape[0], ${i}TexShape[1], index + ${$});
801      return sampleTexture(${i}, uv);
802    }
803  `:`
804    float ${o}(int row, int col, int depth, int depth2) {
805      // Explicitly use integer operations as dot() only works on floats.
806      int index = row * ${c} + col * ${p} +
807          depth * ${l} + depth2;
808      vec2 uv = uvFromFlat(${y}, ${w}, index + ${$});
809      return sampleTexture(${i}, uv);
810    }
811  `}(n,e);case 5:return function(r){const s=r.shapeInfo.logicalShape,a=r.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=s[4],l=s[3]*o,p=s[2]*l,c=s[1]*p,{newShape:h,keptDims:d}=je(s);if(h.length<s.length){const v=["row","col","depth","depth2","depth3"];return`
812      ${ap(op(r,h))}
813      float ${i}(int row, int col, int depth, int depth2, int depth3) {
814        return ${i}(${up(v,d)});
815      }
816    `}if(r.shapeInfo.isUniform)return`
817      float ${i}(int row, int col, int depth, int depth2, int depth3) {
818        float index = dot(
819          vec4(row, col, depth, depth2),
820          vec4(${c}, ${p}, ${l}, ${o})) +
821          depth3;
822        ${ip(r)}
823      }
824    `;const m=r.shapeInfo.flatOffset,g=r.shapeInfo.texShape,y=g[0],w=g[1];return w===c&&m==null?`
825      float ${i}(int row, int col, int depth, int depth2, int depth3) {
826        int texR = row;
827        float texC = dot(vec4(col, depth, depth2, depth3),
828                         vec4(${p}, ${l}, ${o}, 1));
829        vec2 uv = (vec2(texC, texR) + halfCR) /
830                   vec2(${w}.0, ${y}.0);
831        return sampleTexture(${a}, uv);
832      }
833    `:w===o&&m==null?`
834      float ${i}(int row, int col, int depth, int depth2, int depth3) {
835        float texR = dot(
836          vec4(row, col, depth, depth2),
837          vec4(${s[1]*s[2]*s[3]},
838               ${s[2]*s[3]}, ${s[3]}, 1));
839        int texC = depth3;
840        vec2 uv = (vec2(texC, texR) + halfCR) /
841                  vec2(${w}.0, ${y}.0);
842        return sampleTexture(${a}, uv);
843      }
844    `:`
845    float ${i}(int row, int col, int depth, int depth2, int depth3) {
846      // Explicitly use integer operations as dot() only works on floats.
847      int index = row * ${c} + col * ${p} + depth * ${l} +
848          depth2 * ${o} + depth3 + ${Dh(a)};
849      vec2 uv = uvFromFlat(${y}, ${w}, index);
850      return sampleTexture(${a}, uv);
851    }
852  `}(n);case 6:return function(r){const s=r.shapeInfo.logicalShape,a=r.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),{newShape:o,keptDims:l}=je(s);if(o.length<s.length){const N=["row","col","depth","depth2","depth3","depth4"];return`
853      ${ap(op(r,o))}
854      float ${i}(int row, int col, int depth,
855                    int depth2, int depth3, int depth4) {
856        return ${i}(${up(N,l)});
857      }
858    `}const p=s[5],c=s[4]*p,h=s[3]*c,d=s[2]*h,m=s[1]*d;if(r.shapeInfo.isUniform)return`
859      float ${i}(int row, int col, int depth,
860                  int depth2, int depth3, int depth4) {
861        int index = round(dot(
862          vec4(row, col, depth, depth2),
863          vec4(${m}, ${d}, ${h}, ${c})) +
864          dot(
865            vec2(depth3, depth4),
866            vec2(${p}, 1)));
867        ${ip(r)}
868      }
869    `;const g=r.shapeInfo.flatOffset,y=r.shapeInfo.texShape,w=y[0],v=y[1];return v===m&&g==null?`
870      float ${i}(int row, int col, int depth,
871                    int depth2, int depth3, int depth4) {
872        int texR = row;
873        float texC = dot(vec4(col, depth, depth2, depth3),
874          vec4(${d}, ${h}, ${c}, ${p})) +
875               float(depth4);
876        vec2 uv = (vec2(texC, texR) + halfCR) /
877                   vec2(${v}.0, ${w}.0);
878        return sampleTexture(${a}, uv);
879      }
880    `:v===p&&g==null?`
881      float ${i}(int row, int col, int depth,
882                    int depth2, int depth3, int depth4) {
883        float texR = dot(vec4(row, col, depth, depth2),
884          vec4(${s[1]*s[2]*s[3]*s[4]},
885               ${s[2]*s[3]*s[4]},
886               ${s[3]*s[4]},
887               ${s[4]})) + float(depth3);
888        int texC = depth4;
889        vec2 uv = (vec2(texC, texR) + halfCR) /
890                  vec2(${v}.0, ${w}.0);
891        return sampleTexture(${a}, uv);
892      }
893    `:`
894    float ${i}(int row, int col, int depth,
895                  int depth2, int depth3, int depth4) {
896      // Explicitly use integer operations as dot() only works on floats.
897      int index = row * ${m} + col * ${d} + depth * ${h} +
898          depth2 * ${c} + depth3 * ${p} + depth4 + ${Dh(a)};
899      vec2 uv = uvFromFlat(${w}, ${v}, index);
900      return sampleTexture(${a}, uv);
901    }
902  `}(n);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function LI(n,e){switch(n.shapeInfo.logicalShape.length){case 0:return function(t){const r=t.name;return`
903    vec4 ${"get"+r.charAt(0).toUpperCase()+r.slice(1)}() {
904      return ${Ks().texture2D}(${r}, halfCR);
905    }
906  `}(n);case 1:return function(t,r){const s=t.name,a="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t.shapeInfo.texShape,o=Ks();if(r)return`
907    vec4 ${a}(int index) {
908      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
909      vec2 uv = packedUVfrom1D(
910        packedTexShape[0], packedTexShape[1], index);
911      return ${o.texture2D}(${s}, uv);
912    }
913  `;const l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];return`
914    vec4 ${a}(int index) {
915      vec2 uv = packedUVfrom1D(
916        ${l[0]}, ${l[1]}, index);
917      return ${o.texture2D}(${s}, uv);
918    }
919  `}(n,e);case 2:return function(t,r){const s=t.shapeInfo.logicalShape,a=t.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=t.shapeInfo.texShape,l=o[0],p=o[1],c=Ks();if(o!=null&&le(s,o))return r?`
920      vec4 ${i}(int row, int col) {
921        vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
922
923        return ${c.texture2D}(${a}, uv);
924      }
925    `:`
926      vec4 ${i}(int row, int col) {
927        vec2 uv = (vec2(col, row) + halfCR) / vec2(${p}.0, ${l}.0);
928
929        return ${c.texture2D}(${a}, uv);
930      }
931    `;if(r)return`
932    vec4 ${i}(int row, int col) {
933      ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
934      int valuesPerRow = int(ceil(float(${a}Shape[1]) / 2.0));
935      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
936      return ${c.texture2D}(${a}, uv);
937    }
938  `;const h=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return`
939    vec4 ${i}(int row, int col) {
940      vec2 uv = packedUVfrom2D(${Math.ceil(s[1]/2)}, ${h[0]}, ${h[1]}, row, col);
941      return ${c.texture2D}(${a}, uv);
942    }
943  `}(n,e);case 3:return function(t,r){const s=t.shapeInfo.logicalShape,a=t.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=t.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(s[0]===1){const m=[1,2],g=["b","row","col"];return`
944        ${LI(op(t,s.slice(1)),r)}
945        vec4 ${i}(int b, int row, int col) {
946          return ${i}(${up(g,m)});
947        }
948      `}const p=Ks();if(r)return`
949    vec4 ${i}(int b, int row, int col) {
950      ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
951      int valuesPerRow = int(ceil(float(${a}Shape[2]) / 2.0));
952      int texelsInBatch = valuesPerRow * int(ceil(float(${a}Shape[1]) / 2.0));
953      vec2 uv = packedUVfrom3D(
954        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
955      return ${p.texture2D}(${a}, uv);
956    }
957  `;const c=l[0],h=l[1],d=Math.ceil(s[2]/2);return`
958    vec4 ${i}(int b, int row, int col) {
959      vec2 uv = packedUVfrom3D(
960        ${c}, ${h}, ${d*Math.ceil(s[1]/2)}, ${d}, b, row, col);
961      return ${p.texture2D}(${a}, uv);
962    }
963  `}(n,e);default:return function(t,r){const s=t.name,a="get"+s.charAt(0).toUpperCase()+s.slice(1),i=Ks();if(r)return`
964    vec4 ${a}(int b2, int b, int row, int col) {
965      int valuesPerRow = int(ceil(float(${s}Shape[3]) / 2.0));
966      int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[2]) / 2.0));
967      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
968      texelsInBatch *= ${s}Shape[1];
969      index = b2 * texelsInBatch + index;
970      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
971      int texR = index / packedTexShape[1];
972      int texC = index - texR * packedTexShape[1];
973      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${i.texture2D}(${s}, uv);
974    }
975  `;const o=t.shapeInfo.logicalShape,l=o.length,p=t.shapeInfo.texShape,c=[Math.ceil(p[0]/2),Math.ceil(p[1]/2)],h=c[0],d=c[1],m=Math.ceil(o[l-1]/2);let g=m*Math.ceil(o[l-2]/2),y="int b, int row, int col",w=`b * ${g} + (row / 2) * ${m} + (col / 2)`;for(let v=2;v<l-1;v++)y=`int b${v}, `+y,g*=o[l-v-1],w=`b${v} * ${g} + `+w;return`
976    vec4 ${a}(${y}) {
977      int index = ${w};
978      int texR = index / ${d};
979      int texC = index - texR * ${d};
980      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${h});
981      return ${i.texture2D}(${s}, uv);
982    }
983  `}(n,e)}}const _F=`
984vec2 uvFromFlat(int texNumR, int texNumC, int index) {
985  int texR = index / texNumC;
986  int texC = index - texR * texNumC;
987  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
988}
989vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
990  int texelIndex = index / 2;
991  int texR = texelIndex / texNumC;
992  int texC = texelIndex - texR * texNumC;
993  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
994}
995`,DF=`
996vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
997  int texNumC, int row, int col) {
998  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
999  int texR = texelIndex / texNumC;
1000  int texC = texelIndex - texR * texNumC;
1001  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
1002}
1003`,FF=`
1004vec2 packedUVfrom3D(int texNumR, int texNumC,
1005    int texelsInBatch, int texelsInLogicalRow, int b,
1006    int row, int col) {
1007  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
1008  int texR = index / texNumC;
1009  int texC = index - texR * texNumC;
1010  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
1011}
1012`,MF=`
1013  float getChannel(vec4 frag, vec2 innerDims) {
1014    vec2 modCoord = mod(innerDims, 2.);
1015    return modCoord.x == 0. ?
1016      (modCoord.y == 0. ? frag.r : frag.g) :
1017      (modCoord.y == 0. ? frag.b : frag.a);
1018  }
1019  float getChannel(vec4 frag, int dim) {
1020    float modCoord = mod(float(dim), 2.);
1021    return modCoord == 0. ? frag.r : frag.g;
1022  }
1023`;function Dh(n){return`offset${n}`}function ip(n){const e=n.name,t=j(n.shapeInfo.logicalShape);return t<2?`return ${e};`:`
1024    for (int i = 0; i < ${t}; i++) {
1025      if (i == index) {
1026        return ${e}[i];
1027      }
1028    }
1029  `}function Xn(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function _x(n,e,t){const{newShape:r,keptDims:s}=je(e),a=e.length,i=n&&a===3&&e[0]===1,o=i?e.slice(1):r,l=!n&&a>1&&!le(e,t)&&r.length<a||i;return{useSqueezeShape:l,uniformShape:l?o:e,keptDims:s}}function op(n,e){const t=JSON.parse(JSON.stringify(n));return t.shapeInfo.logicalShape=e,t}function up(n,e){return e.map(t=>n[t]).join(", ")}function zI(n,e,t){const r=[],s=[];let a,i,o,l=null,p=null;p=n.getUniformLocation(t,"NAN",!1),xe().getNumber("WEBGL_VERSION")===1&&(l=n.getUniformLocation(t,"INFINITY",!1));const c=!1;for(const h of e.variableNames){const d={name:h,uniform:n.getUniformLocation(t,h,c),offset:n.getUniformLocation(t,`offset${h}`,c)};e.enableShapeUniforms&&(d.shape=n.getUniformLocation(t,`${h}Shape`,c),d.texShape=n.getUniformLocation(t,`${h}TexShape`,c)),r.push(d)}if(e.enableShapeUniforms&&(a=n.getUniformLocation(t,"outShape",c),o=n.getUniformLocation(t,"outShapeStrides",c),i=n.getUniformLocation(t,"outTexShape",c)),e.customUniforms)for(const h of e.customUniforms)s.push(n.getUniformLocation(t,h.name,c));return{variablesLocations:r,customUniformLocations:s,infLoc:l,nanLoc:p,outShapeLocation:a,outShapeStridesLocation:o,outTexShapeLocation:i}}function PI(n,e){if(n.length!==e.length)throw Error(`Binary was compiled with ${n.length}
1029 inputs, but was executed with ${e.length} inputs`);n.forEach((t,r)=>{const s=t.logicalShape,a=e[r],i=a.shape;if(!le(s,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${i} must match`);if(t.isUniform&&a.isUniform)return;const o=t.texShape,l=a.isUniform?null:a.texData.texShape;if(!le(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function Ds(n){return xe().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}class OF{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=zf.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Ks();this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length),this.userCode=`
1030      ivec3 outCoordsFromFlatIndex(int index) {
1031        ${this.enableShapeUniforms?py(["r","c","d"],e):_h(["r","c","d"],e)}
1032        return ivec3(r, c, d);
1033      }
1034
1035      void main() {
1036        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
1037        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
1038
1039        vec4 result = vec4(0.);
1040
1041        for (int i=0; i<4; i++) {
1042          int flatIndex = index + i;
1043          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
1044          result[i] = getA(rc.x, rc.y, rc.z);
1045        }
1046
1047        ${t.output} = result;
1048      }
1049    `}}class LF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=zf.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Ks();this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length),this.userCode=`
1050      ivec3 outCoordsFromFlatIndex(int index) {
1051        ${this.enableShapeUniforms?py(["r","c","d"],e):_h(["r","c","d"],e)}
1052        return ivec3(r, c, d);
1053      }
1054
1055      void main() {
1056        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
1057        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
1058
1059        vec4 result = vec4(0.);
1060
1061        for (int i=0; i<4; i++) {
1062          int flatIndex = index + i;
1063          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
1064          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
1065        }
1066
1067        ${t.output} = result;
1068      }
1069    `}}class zF{constructor(e){this.variableNames=["A"],this.outTexUsage=Ka.DOWNLOAD;const t=Ks();this.outputShape=e,this.userCode=`
1070      ${MI}
1071
1072      void main() {
1073        float x = getAAtOutCoords();
1074        ${t.output} = encode_float(x);
1075      }
1076    `}}class PF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ka.DOWNLOAD;const t=Ks();this.outputShape=e,this.userCode=`
1077      ${MI}
1078
1079      void main() {
1080        ivec3 coords = getOutputCoords();
1081        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
1082        ${t.output} = encode_float(x);
1083      }
1084    `}}const BF={R:0,G:1,B:2,A:3};class BI{constructor(e,t=!1,r="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const s=Ks();this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let i="";for(let o=0;o<r.length;o++){const l=r[o];i+=`
1085          if(offset == ${o}) {
1086            result = values[${BF[l]}];
1087          }`}this.userCode=`
1088      ${this.enableShapeUniforms?`
1089  int getFlatIndex(ivec3 coords) {
1090    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
1091  }
1092`:Rx(e)}
1093
1094      void main() {
1095        ivec3 coords = getOutputCoords();
1096        int flatIndex = getFlatIndex(coords);
1097        float result = 0.;
1098        int offset = imod(flatIndex, ${r.length});
1099
1100        flatIndex = idiv(flatIndex, ${r.length}, 1.);
1101
1102        int r = flatIndex / texShape[1];
1103        if (r < texShape[0]) {
1104          int c = imod(flatIndex, texShape[1]);
1105          vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
1106          vec4 values = ${s.texture2D}(A, uv);
1107          ${i}
1108        }
1109        ${s.output} = vec4(${a}, 0., 0., 0.);
1110      }
1111    `}}class VF{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Ks();this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length);let s="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let i=0;i<=1;i++)for(let o=0;o<=1;o++){const l=2*i+o;s+=`
1112          localCoords = coords;
1113          if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
1114          localCoords[2] += ${o};
1115          if (localCoords[1] + ${i} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
1116            localCoords[1] += ${i};
1117
1118            flatIndex = getFlatIndex(localCoords);
1119            offset = imod(flatIndex, 4);
1120
1121            flatIndex = idiv(flatIndex, 4, 1.);
1122
1123            int r = flatIndex / texShape[1];
1124            int c = imod(flatIndex, texShape[1]);
1125            vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
1126            values = ${r.texture2D}(A, uv);
1127
1128            if (offset == 0) {
1129              result[${l}
1129] = values[0];
1130            } else if (offset == 1) {
1131              result[${l}] = values[1];
1132            } else if (offset == 2) {
1133              result[${l}] = values[2];
1134            } else {
1135              result[${l}] = values[3];
1136            }
1137          }
1138        }
1139        `}this.userCode=`
1140        ${this.enableShapeUniforms?`
1141  int getFlatIndex(ivec3 coords) {
1142    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
1143  }
1144`:Rx(e)}
1145
1146        void main() {
1147          ivec3 coords = getOutputCoords();
1148
1149          vec4 result = vec4(0.);
1150          int flatIndex, r, c, offset;
1151          ivec3 localCoords;
1152          vec2 uv;
1153          vec4 values;
1154
1155          ${s}
1156
1157          ${r.output} = ${a};
1158        }
1159    `}}function VI(n){const e=Ks();return pI(n,`${e.version}
1160    precision highp float;
1161    ${e.attribute} vec3 clipSpacePos;
1162    ${e.attribute} vec2 uv;
1163    ${e.varyingVs} vec2 resultUV;
1164
1165    void main() {
1166      gl_Position = vec4(clipSpacePos, 1);
1167      resultUV = uv;
1168    }`)}function UI(n){return yI(n,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function WI(n){return bI(n,new Uint16Array([0,1,2,2,1,3]))}function Gf(n,e,t,r,s,a){wI(e,t);const i=xI(n),o=n.TEXTURE_2D;return kt(n,()=>n.bindTexture(o,i)),kt(n,()=>n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),kt(n,()=>n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),kt(n,()=>n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)),kt(n,()=>n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)),xe().getNumber("WEBGL_VERSION")===1?kt(n,()=>n.texImage2D(o,0,r,e,t,0,s,a,null)):kt(n,()=>n.texStorage2D(o,1,r,e,t)),kt(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:i,texShape:[t,e]}}function Dx(n){return n.internalFormatFloat}function GI(n,e,t,r){const[s,a]=Pf(e,t);return Gf(n,s,a,Dx(r),r.textureFormatFloat,n.FLOAT)}function Fx(n){return n.internalFormatHalfFloat}function HI(n,e,t,r){const[s,a]=Pf(e,t);return Gf(n,s,a,Fx(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Mx(n){return n.downloadTextureFormat}function jI(n,e,t,r){const[s,a]=Pf(e,t);return Gf(n,s,a,Mx(r),n.RGBA,n.UNSIGNED_BYTE)}function Ox(n){return n.internalFormatPackedFloat}function KI(n,e,t,r){const[s,a]=rp(e,t);return Gf(n,s,a,Ox(r),n.RGBA,n.FLOAT)}function Lx(n){return n.internalFormatPackedHalfFloat}function qI(n,e,t,r){const[s,a]=rp(e,t);return Gf(n,s,a,Lx(r),n.RGBA,r.textureTypeHalfFloat)}function XI(n,e,t){return kt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),Ex(n,e,"clipSpacePos",t,3,20,0)&&Ex(n,e,"uv",t,2,20,12)}function YI(n,e,t,r,s,a){let i,o,l;kt(n,()=>n.bindTexture(n.TEXTURE_2D,e)),s instanceof Uint8Array?(i=new Uint8Array(t*r*4),o=n.UNSIGNED_BYTE,l=n.RGBA):(i=new Float32Array(t*r*4),o=n.FLOAT,l=a.internalFormatPackedFloat),i.set(s),xe().getNumber("WEBGL_VERSION")===2?kt(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t,r,n.RGBA,o,i)):kt(n,()=>n.texImage2D(n.TEXTURE_2D,0,l,t,r,0,n.RGBA,o,i)),kt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function ZI(n,e,t){kt(n,()=>n.bindTexture(n.TEXTURE_2D,e)),t.data instanceof Uint8Array?xe().getNumber("WEBGL_VERSION")===2?kt(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t.width,t.height,n.RGBA,n.UNSIGNED_BYTE,t.data)):kt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t.width,t.height,0,n.RGBA,n.UNSIGNED_BYTE,t.data)):xe().getNumber("WEBGL_VERSION")===2?kt(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,t)):kt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t)),kt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function QI(n,e,t,r){const s=n.createBuffer();kt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,s));const a=16*e*t;return kt(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,a,n.STREAM_READ)),kt(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,0)),kt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),s}function JI(n,e,t){const r=n,s=new Float32Array(t);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function eS(n,e,t,r){const[s,a]=Pf(e,t),i=new Uint8Array(e*t*4);return kt(n,()=>n.readPixels(0,0,s,a,r.downloadTextureFormat,n.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function tS(n,e,t,r,s,a,i,o){const l=n,p=new Float32Array(function(c,h){const[d,m]=rp(c,h);return d*m*4}(a,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,e),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,p),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),p}function nS(n,e,t){const r=new Float32Array(e*t*4);return kt(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,r)),r}class fy{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=xe().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,cI(t,e)):this.gl=ho(t),e=this.gl,xe().getNumber("WEBGL_VERSION")===2){const a=e;this.createVertexArray=()=>kt(a,()=>a.createVertexArray()),this.bindVertexArray=i=>kt(a,()=>a.bindVertexArray(i)),this.deleteVertexArray=i=>kt(a,()=>a.deleteVertexArray(i)),this.getVertexArray=()=>kt(a,()=>a.getParameter(a.VERTEX_ARRAY_BINDING))}else if(e!=null){const a=e.getExtension("OES_vertex_array_object");
vendor: 12,363 bytes, lines 1168-1193
1168if(a==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>kt(e,()=>a.createVertexArrayOES()),this.bindVertexArray=i=>kt(e,()=>a.bindVertexArrayOES(i)),this.deleteVertexArray=i=>kt(e,()=>a.deleteVertexArrayOES(i)),this.getVertexArray=()=>kt(e,()=>e.getParameter(a.VERTEX_ARRAY_BINDING_OES))}let r="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),xe().getNumber("WEBGL_VERSION")===1){const a="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=Bf(this.gl,a),qa(this.gl,i))this.textureHalfFloatExtension=Bf(this.gl,i);else if(xe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(r),qa(this.gl,s))this.colorBufferHalfFloatExtension=Bf(this.gl,s);else if(xe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(r="EXT_color_buffer_float",qa(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else{if(!qa(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=UI(this.gl),this.indexBuffer=WI(this.gl),this.framebuffer=vI(this.gl),this.textureConfig=Sx(this.gl,this.textureHalfFloatExtension)}get debug(){return xe().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;kt(e,()=>e.finish()),kt(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),kt(e,()=>e.deleteFramebuffer(this.framebuffer)),kt(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),kt(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),kt(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),GI(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),HI(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),jI(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),ZI(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,r,s){this.throwIfDisposed(),YI(this.gl,e,t,r,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),qI(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),KI(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Cx(this.gl,this.framebuffer),this.outputTexture=null),kt(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r){return this.downloadMatrixDriver(e,()=>eS(this.gl,t,r,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,r,s,a,i){return tS(this.gl,e,0,0,0,a,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return JI(this.gl,e,t)}createBufferFromTexture(e,t,r){this.bindTextureToFrameBuffer(e);const s=QI(this.gl,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,r;if(xe().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,a=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=()=>{const i=s.clientWaitSync(a,0,0);return i===s.ALREADY_SIGNALED||i===s.CONDITION_SATISFIED},t=a}else xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=()=>this.isQueryAvailable(t,xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):r=()=>!0;return{query:t,isFencePassed:r}}downloadMatrixFromPackedTexture(e,t,r){return this.downloadMatrixDriver(e,()=>nS(this.gl,t,r))}createProgram(e){this.throwIfDisposed();const t=this.gl;this.vertexShader==null&&(this.vertexShader=VI(t));const r=mI(t);kt(t,()=>t.attachShader(r,this.vertexShader)),kt(t,()=>t.attachShader(r,e)),gI(t,r);const s=Object.assign(r,{vao:this.createVertexArray()});return this.debug&&uy(t,s),s}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;kt(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),XI(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(kt(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&uy(this.gl,this.program),kt(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,r=!0){return this.throwIfDisposed(),r?NI(this.gl,e,t):II(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),kt(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),SI(this.gl,e,t,r)}setOutputMatrixTexture(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)}setOutputPackedMatrixTexture(e,t,r){this.throwIfDisposed();const[s,a]=rp(t,r);this.setOutputMatrixTextureDriver(e,s,a)}setOutputMatrixWriteRegion(e,t,r,s){this.setOutputMatrixWriteRegionDriver(r,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,r,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&uy(this.gl,this.program),Vf(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}kt(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),kt(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Bf(this.gl,xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const r=this.gl,s=this.getQueryTimerExtensionWebGL2(),a=r.createQuery();return r.beginQuery(s.TIME_ELAPSED_EXT,a),a}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,r=this.getQueryTimerExtensionWebGL2();return void t.endQuery(r.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await q(()=>this.disposed||this.isQueryAvailable(e,xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}{const r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const r=this.gl,s=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),a&&!this.disjoint}{const r=this.getQueryTimerExtensionWebGL1(),s=r.getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),s&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=function(t){let r=0;for(;r<t.length&&t[r]();++r);return r-1}(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:r}=this.itemsToPoll[t];r()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let r;"setTimeoutCustom"in xe().platform&&(r=xe().platform.setTimeoutCustom.bind(xe().platform)),q(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,r)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),ly(this.gl,e,this.framebuffer),this.debug&&Vf(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(ly(this.gl,this.outputTexture,this.framebuffer),this.debug&&Vf(this.gl)):Cx(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const r=t();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(e,t,r){this.throwIfDisposed();const s=this.gl;ly(s,e,this.framebuffer),this.debug&&Vf(s),this.outputTexture=e,kt(s,()=>s.viewport(0,0,t,r)),kt(s,()=>s.scissor(0,0,t,r))}setOutputMatrixWriteRegionDriver(e,t,r,s){this.throwIfDisposed(),kt(this.gl,()=>this.gl.scissor(e,t,r,s))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}const{addImpl:UF,bincountImpl:rS,bincountReduceImpl:WF,bitwiseAndImpl:GF,castImpl:HF,ceilImpl:jF,concatImpl:KF,equalImpl:qF,expImpl:XF,expm1Impl:YF,floorImpl:ZF,gatherNdImpl:QF,gatherV2Impl:JF,greaterImpl:eM,greaterEqualImpl:tM,lessImpl:nM,lessEqualImpl:rM,linSpaceImpl:sM,logImpl:aM,maxImpl:iM,maximumImpl:oM,minimumImpl:uM,multiplyImpl:lM,negImpl:cM,notEqualImpl:hM,prodImpl:dM,raggedGatherImpl:pM,raggedRangeImpl:fM,raggedTensorToTensorImpl:mM,rangeImpl:gM,rsqrtImpl:yM,scatterImpl:bM,sigmoidImpl:xM,simpleAbsImpl:sS,sliceImpl:wM,sparseFillEmptyRowsImpl:vM,sparseReshapeImpl:kM,sparseSegmentReductionImpl:aS,sqrtImpl:NM,staticRegexReplaceImpl:IM,stridedSliceImpl:SM,stringNGramsImpl:TM,stringSplitImpl:EM,stringToHashBucketFastImpl:CM,subImpl:$M,tileImpl:AM,topKImpl:RM,transposeImpl:zx,uniqueImpl:_M}=M;function iS(n,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${n}.${t}`)}function qs(n,e){return e===1?[n]:iS(n,e)}class DM{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=Ds(this.outputShape.length),this.rank===0)this.userCode=`
1169        void main() {
1170          setOutput(vec4(getA(), 0., 0., 0.));
1171        }
1172      `;else{const t=qs("rc",this.rank),r=Xn(this.rank),s=this.getOutOfBoundsCondition(t),a=this.getSetup(t),i=this.getOutput(t);this.userCode=`
1173        void main() {
1174          ${r} rc = getOutputCoords();
1175
1176          if(${s}) {
1177            setOutput(vec4(0));
1178          } else {
1179            ${a}
1180
1181            setOutput(vec4(${i}));
1182          }
1183        }
1184      `}}getSourceCoordsArr(e){const t=[];for(let r=0;r<=1;r++)for(let s=0;s<=1;s++){let a=`${r===0?"r":"rp1"}, ${s===0?"c":"cp1"}`;for(let i=2;i<this.rank;i++)a=`${e[e.length-1-i]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let r=this.rank-2;r<this.rank;r++)t+=`${e[r]} >= ${this.enableShapeUniforms?`outShape[${r}]`:this.outputShape[r]}`,r<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";const t=e.slice(-2),r=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],s=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
1185      int r = ${t[0]};
1186      int c = ${t[1]};
1187      int rp1 = r + 1;
1188      int cp1 = c + 1;
1189
1190      bool cEdge = cp1 >= ${r};
1191      bool rEdge = rp1 >= ${s};
1192    `}getOutput(e){const t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
1193            cEdge ? 0. : getA(${t[1]}),
1194            rEdge ? 0. : getA(${t[2]}),
1195            rEdge || cEdge ? 0. : getA(${t[3]})`}}class oS{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length);let r="";for(let i=0;i<4;i++){let o="thisRC = rc;";i%2==1&&(o+="thisRC.z += 1;"),i>1&&(o+="thisRC.y += 1;"),r+=`
1196        ${o}
1197        ${i>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
1198          int flatIndex = getFlatIndex(thisRC);
1199
1200          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
1201          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
1202
1203          result[${i}] =
1204            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
1205        ${i>0?"}":""}
1206      `}var s,a;this.userCode=`
1207      ${s=t,a=this.enableShapeUniforms,`
1208    ivec3 inputCoordsFromReshapedOutCoords(int index) {
1209      ${a?function(i,o,l="index"){const p=function(c,h){const d=c.length,m=c.map(y=>`${h}[${y}]`),g=new Array(d-1);g[d-2]=m[d-1];for(let y=d-3;y>=0;--y)g[y]=`(${g[y+1]} * ${m[y+1]})`;return g}(i.map((c,h)=>h),o);return p.map((c,h)=>`int ${i[h]} = ${l} / ${p[h]}; ${h===p.length-1?`int ${i[h+1]} = ${l} - ${i[h]} * ${p[h]}`:`index -= ${i[h]} * ${p[h]}`};`).join("")}(["r","c","d"],"inputShape"):_h(["r","c","d"],s)}
1210      return ivec3(r, c, d);
1211    }
1212  `}
1213      ${this.enableShapeUniforms?`
1214  int getFlatIndex(ivec3 coords) {
1215    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
1216  }
1217`:Rx(e)}
1218
1219      void main() {
1220        ivec3 rc = getOutputCoords();
1221
1222        vec4 result = vec4(0.);
1223
1224        ivec3 thisRC;
1225        int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
1226        int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
1227
1228        ${r}
1229
1230        setOutput(result);
1231      }
1232    `}}class FM{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,r){const s=lS(t,r),a=cS(e,s,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const i=uS(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();const l=this.freeTextures[a].pop();return this.usedTextures[a].push(l),l}let o;return s===Ns.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Ns.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Ns.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Ns.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Ns.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(o),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),o}releaseTexture(e,t,r,s){if(this.freeTextures==null)return;const a=lS(r,s),i=cS(t,a,s);i in this.freeTextures||(this.freeTextures[i]=[]);const o=uS(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,s),l=xe().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[i].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const p=this.usedTextures[i],c=p&&p.indexOf(e);if(c==null||c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");p[c]=p[p.length-1],p.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function uS(n,e,t,r,s){const a=function(l,p){switch(l){case Ns.PACKED_2X2_FLOAT32:return Ox(p);case Ns.PACKED_2X2_FLOAT16:return Lx(p);case Ns.UNPACKED_FLOAT32:return Dx(p);case Ns.UNPACKED_FLOAT16:return Fx(p);case Ns.PACKED_4X1_UNSIGNED_BYTE:return Mx(p);default:throw new Error(`Unknown physical texture type ${l}`)}}(e,r);let i;if(s){const[l,p]=rp(n[0],n[1]);i=l*p}else{const[l,p]=Pf(n[0],n[1]);i=l*p}const o=function(l,p){const c=l;if(p===c.R32F)return 4;if(p===c.R16F)return 2;if(p===c.RGBA32F||p===l.RGBA)return 16;if(p===c.RGBA16F)return 8;if(p===c.RGBA8)return 4;throw new Error(`Unknown internal format ${p}`)}(t,a);return i*o}function lS(n,e){if(n===Ka.UPLOAD)return Ns.PACKED_2X2_FLOAT32;if(n===Ka.RENDER||n==null)return function(t){return xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Ns.PACKED_2X2_FLOAT32:Ns.UNPACKED_FLOAT32:t?Ns.PACKED_2X2_FLOAT16:Ns.UNPACKED_FLOAT16}(e);if(n===Ka.DOWNLOAD||n===Ka.PIXELS)return Ns.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function cS(n,e,t){return`${n[0]}_${n[1]}_${e}_${t}`}class Qo{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length),this.userCode=`
1233      float unaryOperation(float x) {
1234        ${t}
1235      }
1236
1237      void main() {
1238        float x = getAAtOutCoords();
1239        float y = unaryOperation(x);
1240
1241        setOutput(y);
1242      }
1243    `}}const yi="if (isnan(x)) return x;",hS="return abs(x);",MM=yi+`
1244  return (x < 0.0) ? 0.0 : x;
1245`,OM=yi+`
1246  return (x < 0.0) ? 0.0 : min(6.0, x);
1247`,hc="return x;";class dc{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length),this.userCode=`
1248      vec4 unaryOperation(vec4 x) {
1249        ${t}
1250      }
1251
1252      void main() {
1253        vec4 x = getAAtOutCoords();
1254        vec4 y = unaryOperation(x);
1255
1256        setOutput(y);
1257      }
1258    `}}class LM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length);const t=e.length,r=qs("rc",t),s=Xn(t),a=function(l,p){if(l===1)return"rc";let c="";for(let h=0;h<l;h++)c+=p[h],h<l-1&&(c+=",");return c}(t,r),i=r.slice(-2),o=t<=1?"rc":`vec2(${i.join(",")})`;this.userCode=`
1259      void main() {
1260        ${s} rc = getOutputCoords();
1261        vec4 packedInput = getA(${a});
1262
1263        setOutput(getChannel(packedInput, ${o}));
1264      }
1265    `}}const zM=eg,Px={},PM=xe().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
1265class Hf extends E{nextDataId(){return Hf.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!xe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof fy)t=e;else{const s=ho(xe().getNumber("WEBGL_VERSION"),e);t=new fy(s)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const s=ho(xe().getNumber("WEBGL_VERSION"));t=new fy(s),this.binaryCache=((r=xe().getNumber("WEBGL_VERSION"))in Px||(Px[r]={}),Px[r]),this.gpgpuCreatedLocally=!0}var r;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new FM(this.gpgpu),this.numMBBeforeWarning=xe().global.screen==null?1024:xe().global.screen.height*xe().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new k(this,wa())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,r,s,a,i){const o=this.makeTensorInfo(t,r),l=this.texData.get(o.dataId);l.isPacked=!1,l.texture={texture:e,texShape:[s,a]},l.texShape=[s,a];const p=Uf(t),c=new BI(p,!1,i),h=this.runWebGLProgram(c,[o],r,[[s,a]]);return h.shape=t,l.texture=null,this.disposeIntermediateTensorInfo(o),h.dataId}write(e,t,r){if((xe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||xe().getBool("DEBUG"))&&this.checkNumericalProblems(e),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.texData.set(s,{shape:t,dtype:r,values:e,usage:Ka.UPLOAD,refCount:1}),s}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,t,r,s,a){if(xe().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:s,values:t,usage:Ka.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:r,dtype:s,complexTensorInfos:a,slice:i,shape:o,isPacked:l}=t;if(i!=null){let d;d=l?new dc(o,hc):new Qo(o,hc);const m=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:s}],s),g=this.readSync(m.dataId);return this.disposeIntermediateTensorInfo(m),g}if(r!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return r;const p=this.activeTimers!=null;let c,h;return p&&(c=Fn()),h=s==="complex64"?zu(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),p&&(this.downloadWaitMs+=Fn()-c),this.convertAndCacheOnCPU(e,h)}async read(e){if(this.pendingRead.has(e)){const g=this.pendingRead.get(e);return new Promise(y=>g.push(y))}const t=this.texData.get(e),{values:r,shape:s,slice:a,dtype:i,complexTensorInfos:o,isPacked:l}=t;if(a!=null){let g;g=l?new dc(s,hc):new Qo(s,hc);const y=this.runWebGLProgram(g,[{dataId:e,shape:s,dtype:i}],i),w=this.read(y.dataId);return this.disposeIntermediateTensorInfo(y),w}if(r!=null)return this.convertAndCacheOnCPU(e);if(xe().getBool("DEBUG")&&!xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&xe().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let p,c,h=null;if(i!=="complex64"&&xe().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);const g=this.texData.get(p.dataId);h=this.gpgpu.createBufferFromTexture(g.texture.texture,...oy(s))}if(this.pendingRead.set(e,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence(),i==="complex64"){const g=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);c=zu(g[0],g[1])}else if(h==null)c=this.getValuesFromTexture(e);else{const g=j(s);c=this.gpgpu.downloadFloat32MatrixFromBuffer(h,g)}if(p!=null&&this.disposeIntermediateTensorInfo(p),h!=null){const g=this.gpgpu.gl;kt(g,()=>g.deleteBuffer(h))}const d=this.convertAndCacheOnCPU(e,c),m=this.pendingRead.get(e);return this.pendingRead.delete(e),m.forEach(g=>g(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&wa().removeDataId(e,this),this.pendingDeletes--),d}readToGPU(e,t={}){const r=this.texData.get(e),{values:s,shape:a,slice:i,dtype:o,isPacked:l,texture:p}=r;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let m;m=l?new dc(a,hc):new Qo(a,hc);const g=this.runWebGLProgram(m,[{dataId:e,shape:a,dtype:o}],o),y=this.readToGPU(g,t);return this.disposeIntermediateTensorInfo(g),y}if(p==null)throw s!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const c=this.decode(e,t.customTexShape),h=wa().makeTensorFromTensorInfo(c),d=this.texData.get(c.dataId);return Object.assign({tensorRef:h},d.texture)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const r=t.map(s=>gr(s));return ln(e.shape,e.dtype,r)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return ln(e.shape,e.dtype,t)}
vendor: 8,742 bytes, line 1265
1265checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){const r=e[t];if(!hI(r))throw xe().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${r} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${r} cannot be represented on this device.`)}}getValuesFromTexture(e){const{shape:t,dtype:r,isPacked:s}=this.texData.get(e),a=j(t);if(xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const d=this.decode(e),m=this.texData.get(d.dataId),g=this.gpgpu.downloadMatrixFromPackedTexture(m.texture.texture,...oy(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(d),g}const i=xe().getBool("WEBGL_PACK")&&s===!0,o=i?Uf(t):t,l=i?new PF(o):new zF(o),p=this.runWebGLProgram(l,[{shape:o,dtype:r,dataId:e}],"float32"),c=this.texData.get(p.dataId),h=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture.texture,c.texShape[0],c.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(p),h}timerAvailable(){return xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){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=Ba(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),i=Ba(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,s&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const l=await Promise.all(a);o.kernelMs=mt(l),o.getExtraProfileInfo=()=>l.map((p,c)=>({name:i[c],ms:p})).map(p=>`${p.name}: ${p.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Fn(),endMs:null}}endTimer(e){return xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Fn(),e)}async getQueryTime(e){if(xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:r}=this.texData.get(e);return r!=null&&(this.disposeData(r.real.dataId,t),this.disposeData(r.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:r,texShape:s,usage:a,isPacked:i,slice:o}=this.texData.get(e),l=o&&o.origDataId||e,p=this.dataRefCount.get(l);p>1?this.dataRefCount.set(l,p-1):(this.dataRefCount.delete(l),t!=null&&(this.numBytesInGPU-=this.computeBytes(s,r),this.textureManager.releaseTexture(t,s,a,i)));const c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=PM){return xe().getBool("WEBGL_CPU_FORWARD")&&e.every(r=>this.texData.get(r.dataId).texture==null&&j(r.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){In("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return zM(e.shape,t)}packedUnaryOp(e,t,r){const s=new dc(e.shape,t),a=this.compileAndRun(s,[e],r);return wa().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const s=sS(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,s)}if(xe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,hS,e.dtype);const t=new Qo(e.shape,hS),r=this.compileAndRun(t,[e]);return wa().makeTensorFromTensorInfo(r)}makeTensorInfo(e,t,r){let s;if(t==="string"&&r!=null&&r.length>0&&Qn(r[0])){const a=r.map(i=>dn(i));s=this.write(a,e,t)}else s=this.write(r,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,r){return wa().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,r),this)}unpackTensor(e){const t=new LM(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new DM(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const r=[Ah(e.shape),...Rh(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[Ah(t),...Rh(t)],i=new oS(a,r),o=[r],l=this.runWebGLProgram(i,[s],e.dtype,o,!0);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){const r=this.texData.get(e),{isPacked:s,shape:a,dtype:i}=r;t!=null&&A(j(a)<=t[0]*t[1]*4,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");const o=Uf(a);let l;l=s?new LF(o):new OF(o);const p=[t??oy(o)];return{dtype:i,shape:a,dataId:this.runWebGLProgram(l,[{shape:o,dtype:i,dataId:e}],i,p,!0,t).dataId}}runWebGLProgram(e,t,r,s,a=!1,i){const o=this.makeTensorInfo(e.outputShape,r),l=this.texData.get(o.dataId);if(e.packedOutput&&(l.isPacked=!0),e.outPackingScheme===zf.DENSE){const v=i??oy(e.outputShape);l.texShape=v.map(N=>2*N)}if(e.outTexUsage!=null&&(l.usage=e.outTexUsage),j(o.shape)===0)return l.values=_t(o.dtype,0),o;const p=[],c=t.map(v=>{if(v.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let N=this.texData.get(v.dataId);if(N.texture==null){if(!e.packedInputs&&j(v.shape)<=xe().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:v.shape,texData:null,isUniform:!0,uniformValues:N.values};e.packedInputs&&(N.isPacked=!0,N.shape=v.shape)}if(this.uploadToGPU(v.dataId),!!N.isPacked!=!!e.packedInputs)v=N.isPacked?this.unpackTensor(v):this.packTensor(v),p.push(v),N=this.texData.get(v.dataId);else if(N.isPacked&&!Wf(N.shape,v.shape)){const T=v,$=v.shape;v.shape=N.shape,v=this.packedReshape(v,$),p.push(v),N=this.texData.get(v.dataId),T.shape=$}return{shape:v.shape,texData:N,isUniform:!1}});this.uploadToGPU(o.dataId);const h={shape:o.shape,texData:l,isUniform:!1},d=function(v,N,T){let $="";N.concat(T).forEach(z=>{const O=z.texData!=null&&z.texData.slice!=null&&z.texData.slice.flatOffset>0;if(v.enableShapeUniforms&&!z.isUniform){const V=z.texData.texShape,{useSqueezeShape:U,uniformShape:X,keptDims:ne}=_x(v.packedInputs,z.shape,V);let ae="",Ie="",me="";if(X.length===1&&v.packedInputs){const lt=[Math.ceil(V[0]/2),Math.ceil(V[1]/2)];ae=`${lt[0]>1}_${lt[1]>1}`}else if(X.length!==2||v.packedInputs){if(X.length>2&&!v.packedInputs){const lt=Ge(X);me=`${lt[0]===V[1]}_${lt[lt.length-1]===V[1]}`}}else Ie=`${X[0]>1}_${X[1]>1}`;const we=z.shape.length,$e=X.length===2&&le(z.shape,V),ze=j(z.shape)===1,We=ys(z.shape,T.shape),Je=!v.packedInputs&&we===T.shape.length&&le(V,T.texData.texShape),nt=v.packedInputs||X.length>2?"":`${V[0]>1}_${V[1]>1}`;$+=`${we}_${Je}_${U?ne:""}_${X.length}_${ze}_${We}_${$e}_${ae}_${Ie}_${me}_${nt}_${O}`}else{const V=z.isUniform?"uniform":z.texData.texShape;$+=`${z.shape}_${V}_${O}`}});const _=v.userCode;let L=v.constructor.name;return L+="_"+$+"_"+_+`${xe().getNumber("WEBGL_VERSION")}`,L}(e,c,h),m=this.getAndSaveBinary(d,()=>function(v,N,T,$){const _=T.map((X,ne)=>{const ae={logicalShape:X.shape,texShape:X.isUniform?null:X.texData.texShape,isUniform:X.isUniform,isPacked:!X.isUniform&&X.texData.isPacked,flatOffset:null};return X.texData!=null&&X.texData.slice!=null&&X.texData.slice.flatOffset>0&&(ae.flatOffset=X.texData.slice.flatOffset),{name:N.variableNames[ne],shapeInfo:ae}}),L=_.map(X=>X.shapeInfo),z={logicalShape:$.shape,texShape:$.texData.texShape,isUniform:!1,isPacked:$.texData.isPacked,flatOffset:null},O=RF(_,z,N),V=fI(v.gl,O),U=v.createProgram(V);return xe().get("ENGINE_COMPILE_ONLY")?{program:N,fragmentShader:V,source:O,webGLProgram:U,inShapeInfos:L,outShapeInfo:z,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(v.buildVao(U),Object.assign({program:N,fragmentShader:V,source:O,webGLProgram:U,inShapeInfos:L,outShapeInfo:z},zI(v,N,U)))}(this.gpgpu,e,c,h)),g=this.activeTimers!=null;let y;g&&(y=this.startTimer()),xe().get("ENGINE_COMPILE_ONLY")||function(v,N,T,$,_){N.program.enableShapeUniforms||(PI(N.inS
1265hapeInfos,T),PI([N.outShapeInfo],[$]));const L=$.texData.texture,z=$.texData.texShape;$.texData.isPacked?v.setOutputPackedMatrixTexture(L.texture,z[0],z[1]):v.setOutputMatrixTexture(L.texture,z[0],z[1]),v.setProgram(N.webGLProgram),v.bindVertexArray(N.webGLProgram.vao),xe().getNumber("WEBGL_VERSION")===1&&N.infLoc!==null&&v.gl.uniform1f(N.infLoc,1/0),N.nanLoc!==null&&v.gl.uniform1f(N.nanLoc,NaN);for(let V=0;V<T.length;++V){const U=T[V],{uniform:X,offset:ne,shape:ae,texShape:Ie}=N.variablesLocations[V];if(ae){const{uniformShape:me}=_x(N.program.packedInputs,U.shape,U.texData.texShape);switch(me.length){case 1:v.gl.uniform1iv(ae,new Int32Array(me));break;case 2:v.gl.uniform2iv(ae,new Int32Array(me));break;case 3:v.gl.uniform3iv(ae,new Int32Array(me));break;case 4:v.gl.uniform4iv(ae,new Int32Array(me))}}if(Ie&&v.gl.uniform2i(Ie,U.texData.texShape[0],U.texData.texShape[1]),X!=null)if(U.isUniform)if(j(U.shape)<2)v.gl.uniform1f(X,U.uniformValues[0]);else{let me=U.uniformValues;me instanceof Float32Array||(me=new Float32Array(me)),v.gl.uniform1fv(X,me)}else U.texData.slice!=null&&ne!=null&&v.gl.uniform1i(ne,U.texData.slice.flatOffset),v.setInputMatrixTexture(U.texData.texture.texture,X,V)}const O=N.outShapeLocation;if(O)switch($.shape.length){case 1:v.gl.uniform1iv(O,new Int32Array($.shape));break;case 2:v.gl.uniform2iv(O,new Int32Array($.shape));break;case 3:v.gl.uniform3iv(O,new Int32Array($.shape));break;case 4:v.gl.uniform4iv(O,new Int32Array($.shape))}if(N.outShapeStridesLocation){const V=Ge($.shape);switch($.shape.length){case 2:v.gl.uniform1iv(N.outShapeStridesLocation,new Int32Array(V));break;case 3:v.gl.uniform2iv(N.outShapeStridesLocation,new Int32Array(V));break;case 4:v.gl.uniform3iv(N.outShapeStridesLocation,new Int32Array(V))}}if(N.outTexShapeLocation&&v.gl.uniform2i(N.outTexShapeLocation,$.texData.texShape[0],$.texData.texShape[1]),N.program.customUniforms&&_)for(let V=0;V<N.program.customUniforms.length;++V){const U=N.program.customUniforms[V],X=N.customUniformLocations[V],ne=_[V];if(U.type==="float")v.gl.uniform1fv(X,ne);else if(U.type==="vec2")v.gl.uniform2fv(X,ne);else if(U.type==="vec3")v.gl.uniform3fv(X,ne);else if(U.type==="vec4")v.gl.uniform4fv(X,ne);else if(U.type==="int")v.gl.uniform1iv(X,ne);else if(U.type==="ivec2")v.gl.uniform2iv(X,ne);else if(U.type==="ivec3")v.gl.uniform3iv(X,ne);else{if(U.type!=="ivec4")throw Error(`uniform type ${U.type} is not supported yet.`);v.gl.uniform4iv(X,ne)}}v.executeProgram()}(this.gpgpu,m,c,h,s),p.forEach(v=>this.disposeIntermediateTensorInfo(v)),g&&(y=this.endTimer(y),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(y)}));const w=xe().getNumber("WEBGL_FLUSH_THRESHOLD");if(w>0){const v=Fn();v-this.lastGlFlushTime>w&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=v)}if(!xe().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&a===!1){const v=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),v}return o}compileAndRun(e,t,r,s,a=!1){return r=r||t[0].dtype,this.runWebGLProgram(e,t,r,s,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(xe().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=be(()=>{if(!xe().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=xe().getBool("DEBUG");xe().set("DEBUG",!1);const t=this.abs(Pt(1e-8)).dataSync()[0];if(xe().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:r,dtype:s,values:a,texture:i,usage:o,isPacked:l}=t;if(i!=null)return;const p=this.activeTimers!=null;
1265let c;p&&(c=Fn());let h=t.texShape;if(h==null&&(h=CI(r,l),t.texShape=h),a!=null){const d=Uf(r);let m,g=h[1],y=h[0];const w=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!l&&w||([g,y]=rp(h[0],h[1])),m=l?new VF(d,w):new BI(d,w);const v=w?[y,g]:h,N=this.makeTensorInfo(v,s),T=this.texData.get(N.dataId);T.usage=w?Ka.PIXELS:Ka.UPLOAD,T.texShape=v,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(N.dataId),g,y,a);const $=[[y,g]],_=!0,L=this.runWebGLProgram(m,[N],s,$,_),z=this.texData.get(L.dataId);t.texShape=z.texShape,t.isPacked=z.isPacked,t.usage=z.usage,xe().get("ENGINE_COMPILE_ONLY")?this.disposeData(L.dataId):(t.texture=z.texture,t.values=null,this.texData.delete(L.dataId)),this.disposeIntermediateTensorInfo(N),p&&(this.uploadWaitMs+=Fn()-c)}else{const d=this.acquireTexture(h,o,s,l);t.texture=d}}convertAndCacheOnCPU(e,t){const r=this.texData.get(e),{dtype:s}=r;return t!=null&&(r.values=function(a,i){if(i==="float32"||i==="complex64")return a;if(i==="int32"||i==="bool"){const o=i==="int32"?new Int32Array(a.length):new Uint8Array(a.length);for(let l=0;l<o.length;++l)o[l]=Math.round(a[l]);return o}throw new Error(`Unknown dtype ${i}`)}(t,s)),r.values}acquireTexture(e,t,r,s){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${a} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*fr(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const r=new Promise(s=>{try{this.checkCompletion_(t),s(!0)}catch(a){throw a}});e.push(r)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await z0(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(Tx(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:r,infLoc:s,nanLoc:a,outShapeLocation:i,outShapeStridesLocation:o,outTexShapeLocation:l}=zI(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=r,e.infLoc=s,e.nanLoc=a,e.outShapeLocation=i,e.outShapeStridesLocation=o,e.outTexShapeLocation=l}}createTensorFromGPUData(e,t,r){e.channels=e.channels||"RGBA";const{texture:s,height:a,width:i,channels:o}=e,l=wa().backend;if(!l.gpgpu.gl.isTexture(s))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const p=l.writeTexture(s,t,r,a,i,o);return wa().makeTensorFromDataId(p,t,r,l)}}Hf.nextDataId=0;const dS="4.22.0";function pS(){xe().set("WEBGL_FORCE_F16_TEXTURES",!0)}yr()&&Tp("webgl",()=>new Hf,2);const BM={forceHalfFloat:pS},Bx=`
1266  if (isnan(a)) return a;
1267  if (isnan(b)) return b;
1268`;class Fh{constructor(e,t,r){this.variableNames=["A","B"],this.outputShape=Gt(t,r),this.enableShapeUniforms=Ds(this.outputShape.length),this.userCode=`
1269      float binaryOperation(float a, float b) {
1270        ${e}
1271      }
1272
1273      void main() {
1274        float a = getAAtOutCoords();
1275        float b = getBAtOutCoords();
1276        setOutput(binaryOperation(a, b));
1277      }
1278    `}}const Mh=`
1279  result.r = isNaN.r ? NAN : result.r;
1280  result.g = isNaN.g ? NAN : result.g;
1281  result.b = isNaN.b ? NAN : result.b;
1282  result.a = isNaN.a ? NAN : result.a;
1283`;class lp{constructor(e,t,r,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Gt(t,r);const a=this.outputShape.length;this.enableShapeUniforms=Ds(a);let i="";if(s)if(a===0||j(this.outputShape)===1)i=`
1284          result.y = 0.;
1285          result.z = 0.;
1286          result.w = 0.;
1287        `;else if(i=`
1288          ${Xn(a)} coords = getOutputCoords();
1289        `,a===1)this.enableShapeUniforms?i+=`
1290            result.y = (coords + 1) >= outShape ? 0. : result.y;
1291            result.z = 0.;
1292            result.w = 0.;
1293          `:i+=`
1294            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
1295            result.z = 0.;
1296            result.w = 0.;
1297          `;else{const o=qs("coords",a);this.enableShapeUniforms?i+=`
1298            bool nextRowOutOfBounds =
1299              (${o[a-2]} + 1) >= outShape[${a} - 2];
1300            bool nextColOutOfBounds =
1301              (${o[a-1]} + 1) >= outShape[${a} - 1];
1302            result.y = nextColOutOfBounds ? 0. : result.y;
1303            result.z = nextRowOutOfBounds ? 0. : result.z;
1304            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
1305          `:i+=`
1306            bool nextRowOutOfBounds =
1307              (${o[a-2]} + 1) >= ${this.outputShape[a-2]};
1308            bool nextColOutOfBounds =
1309              (${o[a-1]} + 1) >= ${this.outputShape[a-1]};
1310            result.y = nextColOutOfBounds ? 0. : result.y;
1311            result.z = nextRowOutOfBounds ? 0. : result.z;
1312            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
1313          `}this.userCode=`
1314      vec4 binaryOperation(vec4 a, vec4 b) {
1315        ${e}
1316      }
1317
1318      void main() {
1319        vec4 a = getAAtOutCoords();
1320        vec4 b = getBAtOutCoords();
1321
1322        vec4 result = binaryOperation(a, b);
1323        ${i}
1324
1325        setOutput(result);
1326      }
1327    `}}function Ra(n){const{inputs:e,backend:t}=n,{x:r}=e;return t.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const VM={kernelName:Ja,backendName:"webgl",kernelFunc:Ra};function pc(n){const{inputs:e,backend:t}=n,{real:r,imag:s}=e,a=t.makeTensorInfo(r.shape,"complex64"),i=t.texData.get(a.dataId),o=Ra({inputs:{x:r},backend:t}),l=Ra({inputs:{x:s},backend:t});return i.complexTensorInfos={real:o,imag:l},a}const UM={kernelName:Wh,backendName:"webgl",kernelFunc:pc},fS="return (a < 0.) ? b * a : a;",mS=`
1328  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
1329  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
1330`,WM={kernelName:rr,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{alpha:a}=r,i=t.makeTensorInfo([],"float32",Bn(a,"float32")),o=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lp(mS,s.shape,i.shape):new Fh(fS,s.shape,i.shape),l=t.runWebGLProgram(o,[s,i],"float32");return t.disposeIntermediateTensorInfo(i),l}},gS="return (a < 0.) ? b * a : a;",yS=`
1331  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
1332  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
1333`,GM={kernelName:ti,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r,alpha:s}=e,a=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lp(yS,r.shape,s.shape):new Fh(gS,r.shape,s.shape);return t.runWebGLProgram(a,[r,s],"float32")}},cp="if (isnan(x)) return x;";function Cn({opSnippet:n,packedOpSnippet:e,cpuKernelImpl:t,dtype:r}){return({inputs:s,backend:a})=>{const{x:i}=s,o=a,l=r||i.dtype;if(o.shouldExecuteOnCPU([i])&&t!=null){const c=o.texData.get(i.dataId),h=t(c.values,l);return o.makeTensorInfo(i.shape,l,h)}let p;return p=xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null?new dc(i.shape,e):new Qo(i.shape,n),o.runWebGLProgram(p,[i],l)}}function Is({opSnippet:n,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:i,backend:o})=>{const{a:l,b:p}=i,c=o;if(r&&l.dtype==="complex64"){const m=c.texData.get(l.dataId),g=c.texData.get(p.dataId),[y,w]=[[m.complexTensorInfos.real,g.complexTensorInfos.real],[m.complexTensorInfos.imag,g.complexTensorInfos.imag]].map(N=>{const[T,$]=N,_={dataId:T.dataId,dtype:T.dtype,shape:l.shape},L={dataId:$.dataId,dtype:$.dtype,shape:p.shape},z=new Fh(n,l.shape,p.shape);return c.runWebGLProgram(z,[_,L],Cs(T.dtype,$.dtype))}),v=pc({inputs:{real:y,imag:w},backend:c});return c.disposeIntermediateTensorInfo(y),c.disposeIntermediateTensorInfo(w),v}const h=a||Cs(l.dtype,p.dtype);if((l.dtype==="string"||p.dtype==="string"||c.shouldExecuteOnCPU([l,p]))&&s!=null){const m=c.texData.get(l.dataId).values,g=c.texData.get(p.dataId).values,y=l.dtype==="string"?Pu(m):m,w=l.dtype==="string"?Pu(g):g,[v,N]=s(l.shape,p.shape,y,w,h),T=c.makeTensorInfo(N,h);return c.texData.get(T.dataId).values=v,T}let d;return d=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null?new lp(e,l.shape,p.shape,t):new Fh(n,l.shape,p.shape),c.runWebGLProgram(d,[l,p],h)}}function jf(n,e=!1){if(n==="linear")return"return x;";if(n==="relu")return e?`
1334  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
1335  bvec4 isNaN = isnan(x);
1336
1337  result.r = isNaN.r ? x.r : result.r;
1338  result.g = isNaN.g ? x.g : result.g;
1339  result.b = isNaN.b ? x.b : result.b;
1340  result.a = isNaN.a ? x.a : result.a;
1341
1342  return result;
1343`:MM;if(n==="elu")return e?`
1344  vec4 result;
1345
1346  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
1347  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
1348  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
1349  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
1350
1351  return result;
1352`:"return (x >= 0.0) ? x : (exp(x) - 1.0);";if(n==="relu6")return e?`
1353  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
1354  bvec4 isNaN = isnan(x);
1355
1356  result.r = isNaN.r ? x.r : result.r;
1357  result.g = isNaN.g ? x.g : result.g;
1358  result.b = isNaN.b ? x.b : result.b;
1359  result.a = isNaN.a ? x.a : result.a;
1360
1361  return result;
1362`:OM;if(n==="prelu")return e?yS:gS;if(n==="leakyrelu")return e?mS:fS;if(n==="sigmoid")return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}class bS{constructor(e,t,r,s=!1,a=!1,i=!1,o=null,l=!1,p=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.enableShapeUniforms=Ds(this.outputShape.length);const c=s?e[1]:e[2],h=Math.ceil(c/2),d=s?"i * 2, rc.y":"rc.y, i * 2",m=a?"rc.z, i * 2":"i * 2, rc.z",g=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],y=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let w="",v="";o&&(w=l?`vec4 activation(vec4 a) {
1363          vec4 b = getPreluActivationWeightsAtOutCoords();
1364          ${o}
1365        }`:p?`vec4 activation(vec4 a) {
1366          vec4 b = getLeakyreluAlphaAtOutCoords();
1367          ${o}
1368        }`:`vec4 activation(vec4 x) {
1369          ${o}
1370        }`,v="result = activation(result);");const N=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),p&&this.variableNames.push("leakyreluAlpha");let T="rc.x",$="rc.x";e[0]<t[0]?T=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&($=`imod(rc.x, ${t[0]})`),this.userCode=`
1371      ${w}
1372      // Don't use uniform for sharedDimensionPacked for performance.
1373      const float sharedDimension = ${h}.0;
1374
1375      vec4 dot2x2ARowBCol(ivec3 rc) {
1376        vec4 result = vec4(0);
1377        int batchA = ${T};
1378        int batchB = ${$};
1379        for (int i = 0; i < ${h}; i++) {
1380          vec4 a = getMatrixA(batchA, ${d});
1381          vec4 b = getMatrixB(batchB, ${m});
1382
1383          // These swizzled products need to be separately added.
1384          // See: https://github.com/tensorflow/tfjs/issues/1735
1385          result += (${g[0]} * ${y[0]});
1386          result += (${g[1]} * ${y[1]});
1387        }
1388        return result;
1389      }
1390
1391      void main() {
1392        ivec3 rc = getOutputCoords();
1393        vec4 result = dot2x2ARowBCol(rc);
1394
1395        ${N}
1396
1397        ${v}
1398
1399        setOutput(result);
1400      }
1401    `}}class xS{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Gt(t,r),this.userCode=`
1402      float binaryOpComplex(
1403          float areal, float aimag, float breal, float bimag) {
1404        ${e}
1405      }
1406
1407      void main() {
1408        float areal = getARealAtOutCoords();
1409        float aimag = getAImagAtOutCoords();
1410        float breal = getBRealAtOutCoords();
1411        float bimag = getBImagAtOutCoords();
1412        setOutput(binaryOpComplex(areal, aimag, breal, bimag));
1413      }
1414    `}}const wS="return a * b;";function Vx(n){const{inputs:e,backend:t}=n,{a:r,b:s}=e,a=Cs(r.dtype,s.dtype);if(r.dtype==="complex64"){const o=t.texData.get(r.dataId),l=t.texData.get(s.dataId),p=new xS("return areal * breal - aimag * bimag;",r.shape,s.shape),c=new xS("return areal * bimag + aimag * breal;",r.shape,s.shape),h=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:r.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:s.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:s.shape}],d=t.runWebGLProgram(p,h,"float32"),m=t.runWebGLProgram(c,h,"float32"),g=pc({inputs:{real:d,imag:m},backend:t});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(m),g}if(t.shouldExecuteOnCPU([r,s])){const o=t.texData.get(r.dataId),l=t.texData.get(s.dataId),[p,c]=lM(r.shape,s.shape,o.values,l.values,a),h=t.makeTensorInfo(c,a);return t.texData.get(h.dataId).values=p,h}let i;return i=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lp(wS,r.shape,s.shape):new Fh(wS,r.shape,s.shape),t.runWebGLProgram(i,[r,s],a)}const HM={kernelName:Di,backendName:"webgl",kernelFunc:Vx};function It(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{shape:a}=r,i=t,o=j(s.shape),l=Le(a,o),p=j(l);A(o===p,()=>`The new shape (${l}) has ${p} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);const c=i.texData.get(s.dataId);return!c.isPacked||Wf(s.shape,l)||c.texture!==null&&Wf(c.shape,l)?(i.incRef(s.dataId),{dataId:s.dataId,shape:l,dtype:s.dtype}):function(h,d,m){const g=[Ah(h.shape),...Rh(h.shape)],y={dtype:h.dtype,shape:g,dataId:h.dataId},w=[Ah(d),...Rh(d)],v=new oS(w,g),N=[g],T=m.runWebGLProgram(v,[y],h.dtype,N,!0);return{dataId:T.dataId,shape:d,dtype:T.dtype}}(s,l,i)}const jM={kernelName:_o,backendName:"webgl",kernelFunc:It};class vS{constructor(e,t){this.variableNames=["x"];const{windowSize:r,batchSize:s,inSize:a,outSize:i}=e;this.outputShape=[s,i];const o=4*Math.floor(r/4),l=r%4;let p="sumValue += dot(values, ones);";if(t!=null){const h=1/t;p=`sumValue += dot(values * ${ue(h)?h.toPrecision(2):h}, ones);`}let c="";a%r>0&&(c=`
1415        if (inIdx < 0 || inIdx >= ${a}) {
1416          return 0.0;
1417        }
1418      `),this.userCode=`
1419      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
1420
1421      float getValue(int batch, int inIdx) {
1422        ${c}
1423        return getX(batch, inIdx);
1424      }
1425
1426      void main() {
1427        ivec2 coords = getOutputCoords();
1428        int batch = coords[0];
1429        int outIdx = coords[1];
1430        int inOffset = outIdx * ${r};
1431
1432        float sumValue = 0.0;
1433
1434        for (int i = 0; i < ${o}; i += 4) {
1435          int inIdx = inOffset + i;
1436          vec4 values = vec4(
1437            getValue(batch, inIdx),
1438            getValue(batch, inIdx + 1),
1439            getValue(batch, inIdx + 2),
1440            getValue(batch, inIdx + 3)
1441          );
1442
1443          ${p}
1444        }
1445
1446        int inIdx = inOffset + ${o};
1447        if (${l===1}) {
1448          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
1449
1450          ${p}
1451        } else if (${l===2}) {
1452          vec4 values = vec4(
1453            getValue(batch, inIdx),
1454            getValue(batch, inIdx + 1), 0.0, 0.0);
1455
1456          ${p}
1457        } else if (${l===3}) {
1458          vec4 values = vec4(
1459            getValue(batch, inIdx),
1460            getValue(batch, inIdx + 1),
1461            getValue(batch, inIdx + 2), 0.0);
1462
1463          ${p}
1464        }
1465        setOutput(sumValue);
1466      }
1467    `}}class KM{constructor(e,t){this.variableNames=["x"];const{windowSize:r,batchSize:s,inSize:a,outSize:i}=e;this.outputShape=[s,i];let o="0.0",l="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",l="min"):t==="max"&&(o="-1.0 / 1e-20",l="max");let p=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?p="sumValue":t==="prod"?p="prodValue":t==="all"?p="allValue":t==="any"&&(p="anyValue");const c=4*Math.floor(r/4),h=r%4;let d=`
1468      if (${t==="sum"}) {
1469        sumValue += dot(values, ones);
1470      } else if (${t==="prod"}) {
1471        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
1472        prodValue *= tmp[0] * tmp[1];
1473      } else {
1474        minMaxValue = ${l}(values, minMaxValue);
1475        if (${t==="min"} || ${t==="max"}) {
1476          minMaxValue = ${l}(values, minMaxValue);
1477          bvec4 isNaN = isnan(values);
1478          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
1479            minMaxValue = vec4(NAN);
1480          }
1481        }
1482      }
1483    `,m="vec4";t==="all"?(o="1.0",d=`
1484        bool reducedAllValue = all(values);
1485        float floatedReducedAllValue = float(reducedAllValue);
1486        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
1487      `,m="bvec4"):t==="any"&&(o="0.0",d=`
1488        bool reducedAnyValue = any(values);
1489        float floatedReducedAnyValue = float(reducedAnyValue);
1490        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
1491      `,m="bvec4");let g="";a%r>0&&(g=`
1492        if (inIdx < 0 || inIdx >= ${a}) {
1493          return initializationValue;
1494        }
1495      `),this.userCode=`
1496      const float initializationValue = ${o};
1497      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
1498
1499      float getValue(int batch, int inIdx) {
1500        ${g}
1501        return getX(batch, inIdx);
1502      }
1503
1504      void main() {
1505        ivec2 coords = getOutputCoords();
1506        int batch = coords[0];
1507        int outIdx = coords[1];
1508        int inOffset = outIdx * ${r};
1509
1510        vec4 minMaxValue = vec4(${o});
1511        float prodValue = 1.0;
1512        float sumValue = 0.0;
1513        float allValue = 1.0;
1514        float anyValue = 0.0;
1515
1516        for (int i = 0; i < ${c}; i += 4) {
1517          int inIdx = inOffset + i;
1518          ${m} values = ${m}(
1519            getValue(batch, inIdx),
1520            getValue(batch, inIdx + 1),
1521            getValue(batch, inIdx + 2),
1522            getValue(batch, inIdx + 3)
1523          );
1524
1525          ${d}
1526        }
1527
1528        int inIdx = inOffset + ${c};
1529        if (${h===1}) {
1530          ${m} values = ${m}(
1531            getValue(batch, inIdx),
1532            initializationValue,
1533            initializationValue,
1534            initializationValue
1535          );
1536
1537          ${d}
1538        } else if (${h===2}) {
1539          ${m} values = ${m}(
1540            getValue(batch, inIdx),
1541            getValue(batch, inIdx + 1),
1542            initializationValue,
1543            initializationValue
1544          );
1545
1546          ${d}
1547        } else if (${h===3}) {
1548          ${m} values = ${m}(
1549            getValue(batch, inIdx),
1550            getValue(batch, inIdx + 1),
1551            getValue(batch, inIdx + 2),
1552            initializationValue
1553          );
1554
1555          ${d}
1556        }
1557        setOutput(${p});
1558      }
1559    `}}function Oh(n,e,t,r){const s=function(i){const o=[];for(;o.length===0||o[o.length-1].outSize!==1;){const l=o.length?o[o.length-1].outSize:i[1],p=lg(l);o.push({inSize:l,windowSize:p,outSize:Math.ceil(l/p)})}return o}(n.shape);let a=n;for(let i=0;i<s.length;i++){const{inSize:o,windowSize:l,outSize:p}=s[i];let c,h;c=t==="mean"?i===0?new vS({windowSize:l,inSize:o,batchSize:n.shape[0],outSize:p},o):new vS({windowSize:l,inSize:o,batchSize:n.shape[0],outSize:p}):new KM({windowSize:l,inSize:o,batchSize:n.shape[0],outSize:p},t),h=a,a=r.runWebGLProgram(c,[a],e),h.dataId!==n.dataId&&r.disposeIntermediateTensorInfo(h)}return a}class qM{constructor(e,t){this.variableNames=["A"];const r=new Array(e.length);for(let i=0;i<r.length;i++)r[i]=e[t[i]];this.outputShape=r,this.rank=r.length;const s=Xn(this.rank),a=function(i){const o=i.length;if(o>6)throw Error(`Transpose for rank ${o} is not yet supported`);const l=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],p=new Array(o);for(let c=0;c<i.length;c++)p[i[c]]=l[c];return p.join()}(t);this.userCode=`
1560    void main() {
1561      ${s} resRC = getOutputCoords();
1562      setOutput(getA(${a}));
1563    }
1564    `}}class XM{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const r=new Array(e.length);for(let c=0;c<r.length;c++)r[c]=e[t[c]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=Xn(this.rank),a=iS("rc",this.rank),i=new Array(this.rank);for(let c=0;c<t.length;c++)i[t[c]]=a[c];const o=`vec2(${i.slice(-2).join()})`,l=`++${a[this.rank-1]} < ${r[this.rank-1]}`,p=`getChannel(getA(${i.join()}), ${o})`;this.userCode=`
1565    void main() {
1566      ${s} rc = getOutputCoords();
1567      vec4 result = vec4(0.);
1568      result[0] = ${p};
1569      if(${l}) {
1570        result[1] = ${p};
1571      }
1572      --${a[this.rank-1]};
1573      if(++${a[this.rank-2]} < ${r[this.rank-2]}) {
1574        result[2] = ${p};
1575        if(${l}) {
1576          result[3] = ${p};
1577        }
1578      }
1579      setOutput(result);
1580    }
1581    `}}function my(n,e,t){const r=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XM(n.shape,e):new qM(n.shape,e);return t.runWebGLProgram(r,[n],n.dtype)}function gy(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r;return function(o,l,p,c){const h=l,d=o.shape.length,m=Oe(h,o.shape);let g=m;const y=Ir(g,d),w=y!=null;let v=o;w&&(v=my(o,y,c),g=Or(g.length,d)),xs("sum",g,d);const[N,T]=us(v.shape,g);let $=N;p&&($=Mr(N,m));const _=j(T),L=It({inputs:{x:v},attrs:{shape:[j(o.shape)/_,_]},backend:c}),z=Oh(L,Kc(o.dtype),"sum",c),O=It({inputs:{x:z},attrs:{shape:$},backend:c});return c.disposeIntermediateTensorInfo(L),c.disposeIntermediateTensorInfo(z),w&&c.disposeIntermediateTensorInfo(v),O}(s,a,i,t)}const YM={kernelName:La,backendName:"webgl",kernelFunc:gy};function Xs(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{perm:a}=r,i=t,o=s.shape.length,l=new Array(o);for(let c=0;c<l.length;c++)l[c]=s.shape[a[c]];let p;if(i.shouldExecuteOnCPU([s])){const c=i.texData.get(s.dataId).values,h=zx(c,s.shape,s.dtype,a,l);p=i.makeTensorInfo(l,s.dtype),i.texData.get(p.dataId).values=h}else p=my(s,a,i);return p}const ZM={kernelName:Oo,backendName:"webgl",kernelFunc:Xs};function yy({a:n,b:e,transposeA:t,transposeB:r,backend:s,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){const p=n.shape.length,c=e.shape.length,h=t?n.shape[p-2]:n.shape[p-1],d=r?e.shape[c-1]:e.shape[c-2],m=t?n.shape[p-1]:n.shape[p-2],g=r?e.shape[c-2]:e.shape[c-1],y=n.shape.slice(0,-2),w=e.shape.slice(0,-2),v=j(y),N=j(w),T=Gt(n.shape.slice(0,-2),e.shape.slice(0,-2)).c
1581oncat([m,g]);A(h===d,()=>`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${e.shape} and transposeA=${t} and transposeB=${r} must match.`);const $=t?[v,h,m]:[v,m,h],_=r?[N,g,d]:[N,d,g],L=It({inputs:{x:n},backend:s,attrs:{shape:$}}),z=It({inputs:{x:e},backend:s,attrs:{shape:_}}),O=[L,z],V=Math.max(v,N),U=t?L.shape[1]:L.shape[2],X=a!=null,ne=i!=null,ae=l==="leakyrelu",Ie=l!=null?jf(l,!0):null;let me;if((m===1||g===1)&&U>1e3&&(X||ne||ae||Ie!=null)===!1){let $e=L,ze=z;t&&($e=Xs({inputs:{x:L},backend:s,attrs:{perm:[0,2,1]}}),O.push($e)),r&&(ze=Xs({inputs:{x:z},backend:s,attrs:{perm:[0,2,1]}}),O.push(ze));const We=g===1;let Je=$e;g!==1&&(Je=It({inputs:{x:$e},backend:s,attrs:{shape:[V,U,1]}}),O.push(Je));const nt=g===1?2:1;let lt=ze;We&&(lt=It({inputs:{x:ze},backend:s,attrs:{shape:[V,1,U]}}),O.push(lt));const dt=Vx({inputs:{a:Je,b:lt},backend:s});me=gy({inputs:{x:dt},backend:s,attrs:{axis:nt,keepDims:!0}}),O.push(dt)}else{const $e=Cs(n.dtype,e.dtype),ze=new bS($,_,[V,m,g],t,r,X,Ie,ne,ae),We=[L,z];if(a!=null&&We.push(a),ne&&We.push(i),ae){const Je=s.makeTensorInfo([],"float32",Bn(o,"float32"));We.push(Je),O.push(Je)}me=s.runWebGLProgram(ze,We,$e)}const we=It({inputs:{x:me},backend:s,attrs:{shape:T}});O.push(me);for(const $e of O)s.disposeIntermediateTensorInfo($e);return we}const QM={kernelName:Jn,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a,bias:i,preluActivationWeights:o}=e,{transposeA:l,transposeB:p,activation:c,leakyreluAlpha:h}=r;return yy({a:s,b:a,transposeA:l,transposeB:p,backend:t,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},kS="return abs(x);",JM={kernelName:Yu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e;if(t.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){const a=t.texData.get(r.dataId),i=sS(a.values);return t.makeTensorInfo(r.shape,r.dtype,i)}let s;return s=xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new dc(r.shape,kS):new Qo(r.shape,kS),t.runWebGLProgram(s,[r],r.dtype)}},eO=Cn({opSnippet:yi+`
1582  if (abs(x) > 1.) {
1583    return NAN;
1584  }
1585  return acos(x);
1586`}),tO={kernelName:Da,backendName:"webgl",kernelFunc:eO},nO=Cn({opSnippet:yi+`
1587  if (x < 1.0) return NAN;
1588return log(x + sqrt(x * x - 1.0));`}),rO={kernelName:Js,backendName:"webgl",kernelFunc:nO},NS="return a + b;",sO=Is({opSnippet:NS,packedOpSnippet:NS,supportsComplex:!0,cpuKernelImpl:UF}),aO={kernelName:bi,backendName:"webgl",kernelFunc:sO};class iO{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((a,i)=>`T${i}`);const r=[];this.variableNames.forEach(a=>{r.push(`float v${a} = get${a}AtOutCoords();`)});const s=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
1589      void main() {
1590        ${r.join(`
1591        `)}
1592
1593        float result = ${s};
1594        setOutput(result);
1595      }
1596    `}}class oO{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((a,i)=>`T${i}`);const r=[];this.variableNames.forEach(a=>{r.push(`vec4 v${a} = get${a}AtOutCoords();`)});const s=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
1597      void main() {
1598        ${r.join(`
1599        `)}
1600
1601        vec4 result = ${s};
1602        setOutput(result);
1603      }
1604    `}}const uO={kernelName:yc,backendName:"webgl",kernelFunc:function n(e){const{inputs:t,backend:r}=e,s=t;if(s.length===1)return Ra({inputs:{x:s[0]},backend:r});if(s.length>xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const l=Math.floor(s.length/2),p=n({inputs:s.slice(0,l),backend:r}),c=n({inputs:s.slice(l),backend:r});return n({inputs:[p,c],backend:r})}const a=s.map(l=>l.dtype).reduce((l,p)=>Cs(l,p)),i=s.map(l=>l.shape),o=xe().getBool("WEBGL_PACK")?new oO(s[0].shape,i):new iO(s[0].shape,i);return r.runWebGLProgram(o,s,a)}},lO={kernelName:bc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r,o=s.shape.length,l=Oe(a,s.shape);let p=l;const c=Ir(p,o);let h=s;c!=null&&(h=Xs({inputs:{x:s},backend:t,attrs:{perm:c}}),p=Or(p.length,o)),xs("all",p,o);const[d,m]=us(h.shape,p),g=It({inputs:{x:h},backend:t,attrs:{shape:[-1,j(m)]}}),y=Oh(g,g.dtype,"all",t);let w;return w=It(i?{inputs:{x:y},backend:t,attrs:{shape:Mr(d,l)}}
1604:{inputs:{x:y},backend:t,attrs:{shape:d}}),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),c!=null&&t.disposeIntermediateTensorInfo(h),w}},cO={kernelName:xi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r,o=s.shape.length,l=Oe(a,s.shape);let p=l;const c=Ir(p,o);let h=s;c!=null&&(h=Xs({inputs:{x:s},backend:t,attrs:{perm:c}}),p=Or(p.length,o)),xs("any",p,o);const[d,m]=us(h.shape,p),g=It({inputs:{x:h},backend:t,attrs:{shape:[-1,j(m)]}}),y=Oh(g,g.dtype,"any",t);let w;return w=It(i?{inputs:{x:y},backend:t,attrs:{shape:Mr(d,l)}}:{inputs:{x:y},backend:t,attrs:{shape:d}}),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),c!=null&&t.disposeIntermediateTensorInfo(h),w}};class hO{constructor(e,t,r){this.variableNames=["A"];const{windowSize:s,batchSize:a,outSize:i}=e;r||this.variableNames.push("bestIndicesA"),this.outputShape=[a,i];const o=t==="max"?">":"<",l=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
1605      void main() {
1606        ivec2 coords = getOutputCoords();
1607        int batch = coords[0];
1608        int outIdx = coords[1];
1609        int inOffset = outIdx * ${s};
1610
1611        int bestIndex = inOffset;
1612        float bestValue = getA(batch, bestIndex);
1613
1614        for (int i = 0; i < ${s}; i++) {
1615          int inIdx = ${l};
1616          float candidate = getA(batch, inIdx);
1617          if (candidate ${o} bestValue) {
1618            bestValue = candidate;
1619            bestIndex = inIdx;
1620          }
1621        }
1622        setOutput(float(bestIndex));
1623      }
1624    `}}class dO{constructor(e,t,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,A(e.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);const a=e[e.length-1],i=Math.ceil(a/t);this.outputShape=e.slice(0,-1),i>1&&this.outputShape.push(i),s||this.variableNames.push("bestIndicesA");const o=this.outputShape,l=o.length,p=Xn(l),c=qs("coords",l);let h,d;if(i===1){d=l+1;const O=Xn(d);h=`
1625        ${O} sourceLocR = ${O}(${c.join()}, 0);
1626        ++${c[l-1]};
1627        ${O} sourceLocG = ${O}(${c.join()}, 0);
1628        ++${c[l-2]};
1629        ${O} sourceLocA = ${O}(${c.join()}, 0);
1630        --${c[l-1]};
1631        ${O} sourceLocB = ${O}(${c.join()}, 0);
1632        --${c[l-2]};`}else d=l,h=`
1633        ${p} sourceLocR = coords;
1634        ++${c[l-1]};
1635        ${p} sourceLocG = coords;
1636        ++${c[l-2]};
1637        ${p} sourceLocA = coords;
1638        --${c[l-1]};
1639        ${p} sourceLocB = coords;
1640        --${c[l-2]};`;const m=["x","y","z","w","u","v"].slice(0,d),g="."+m[d-1],y=m.map(O=>"int "+O),w=qs("sourceLocR",d-1).concat("inIdx.r"),v=qs("sourceLocG",d-1).concat("inIdx.g"),N=qs("sourceLocB",d-1).concat("inIdx.b"),T=qs("sourceLocA",d-1).concat("inIdx.a"),$=r==="max"?"greaterThan":"lessThan",_=s?"":`
1641          inIdx = round(vec4(getBestIndicesAChannel(${w.join()}),
1642                             getBestIndicesAChannel(${v.join()}),
1643                             getBestIndicesAChannel(${N.join()}),
1644                             getBestIndicesAChannel(${T.join()})));`,L=`vec4(
1645            getAChannel(${w.join()}),
1646            hasNextCol ? getAChannel(${v.join()}) : 0.,
1647            hasNextRow ? getAChannel(${N.join()}) : 0.,
1648            hasNextRow && hasNextCol ? getAChannel(${T.join()}) : 0.)`,z=s?"":`
1649      float getBestIndicesAChannel(${y.join()}) {
1650        return getChannel(getBestIndicesA(${m.join()}),
1651                                          vec2(${m.slice(-2).join()}));
1652      }`;this.userCode=`
1653      float getAChannel(${y.join()}) {
1654        return getChannel(getA(${m.join()}),
1655                               vec2(${m.slice(-2).join()}));
1656      }
1657      ${z}
1658      void main() {
1659        ${p} coords = getOutputCoords();
1660        bool hasNextCol = ${c[l-1]} < ${o[l-1]-1};
1661        bool hasNextRow = ${c[l-2]} < ${o[l-2]-1};
1662        ${h}
1663        ivec4 srcIdx = ivec4(sourceLocR${g}, sourceLocG${g},
1664          sourceLocB${g}, sourceLocA${g}) * ${t};
1665        ivec4 inIdx = srcIdx;
1666        vec4 bestIndex = vec4(inIdx);
1667        vec4 bestValue = ${L};
1668
1669        for (int i = 0; i < ${t}; i++) {
1670          inIdx = srcIdx;
1671          ${_}
1672          vec4 candidate = ${L};
1673          bvec4 nan = isnan(candidate);
1674          bvec4 replace = bvec4(
1675            vec4(${$}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
1676
1677          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,
1678                           replace.y  ? candidate.y : bestValue.y,
1679                           replace.z  ? candidate.z : bestValue.z,
1680                           replace.w  ? candidate.w : bestValue.w);
1681          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
1682          srcIdx++;
1683        }
1684        setOutput(bestIndex);
1685      }
1686    `}}function IS(n,e,t,r=null){let s=e.shape[0],a=e.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);const i=lg(a),o={windowSize:i,inSize:a,batchSize:s,outSize:Math.ceil(a/i)},l=new hO(o,t,r==null),p=[e];r!=null&&p.push(r);const c=n.runWebGLProgram(l,p,"int32");if(c.shape[1]===1)return c;const h=IS(n,e,t,c);return n.disposeIntermediateTensorInfo(c),h}function SS(n,e,t,r=null){const s=r!=null?r.shape:e.shape,a=lg(s[s.length-1]),i=new dO(s,a,t,r==null),o=r==null?[e]:[e,r],l=n.runWebGLProgram(i,o,"int32");if(l.shape.length===e.shape.length){const p=SS(n,e,t,l);return n.disposeIntermediateTensorInfo(l),p}return l}function TS(n,e,t,r){const s=[t];if(xs("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,e.shape.length),!xe().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){const a=[],i=n.texData.get(e.dataId);let o=e;i!==null&&i.isPacked&&(o=n.unpackTensor(e),a.push(o));const[l,p]=us(o.shape,s),c=j(p),h=It({inputs:{x:o},backend:n,attrs:{shape:[-1,c]}});a.push(h);const d=IS(n,h,r);a.push(d);const m=It({inputs:{x:d},backend:n,attrs:{shape:l}});return a.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}return SS(n,e,r)}const pO={kernelName:Zu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;let i=Oe(a,s.shape);const o=Ir(i,s.shape.length);let l=s;const p=[];
1686o!=null&&(l=Xs({inputs:{x:s},backend:t,attrs:{perm:o}}),p.push(l),i=Or(i.length,l.shape.length)),xs("argMax",[i[0]],l.shape.length);const c=TS(t,l,i[0],"max");return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),c}},fO={kernelName:wi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;let i=Oe(a,s.shape);const o=Ir(i,s.shape.length);let l=s;const p=[];o!=null&&(l=Xs({inputs:{x:s},backend:t,attrs:{perm:o}}),p.push(l),i=Or(i.length,l.shape.length)),xs("argMin",[i[0]],l.shape.length);const c=TS(t,l,i[0],"min");return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),c}},mO=Cn({opSnippet:yi+`
1687  if (abs(x) > 1.) {
1688    return NAN;
1689  }
1690  return asin(x);
1691`}),gO={kernelName:pa,backendName:"webgl",kernelFunc:mO},yO=Cn({opSnippet:yi+"return log(x + sqrt(x * x + 1.0));"}),bO={kernelName:go,backendName:"webgl",kernelFunc:yO},xO=Cn({opSnippet:yi+`
1692  return atan(x);
1693`}),wO={kernelName:Za,backendName:"webgl",kernelFunc:xO},vO=Is({opSnippet:Bx+`
1694  return atan(a, b);
1695`,packedOpSnippet:`
1696  vec4 result = atan(a, b);
1697  bvec4 isNaNA = isnan(a);
1698  bvec4 isNaNB = isnan(b);
1699  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
1700  `+Mh+`
1701  return result;
1702`}),kO={kernelName:Jo,backendName:"webgl",kernelFunc:vO},NO=Cn({opSnippet:yi+`
1703  if ((x < -1.0) || (x > 1.0)) return NAN;
1704return (log(1.0 + x) - log(1.0 - x)) / 2.0;`}),IO={kernelName:vi,backendName:"webgl",kernelFunc:NO};class Kf{constructor(e,t,r,s=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");const i=e.filterWidth,o=e.strideHeight,l=e.strideWidth,p=e.dilationHeight,c=e.dilationWidth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,m=e.padInfo.top,g=e.padInfo.left;this.outputShape=e.outShape;const y=t==="avg",w=`((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(y||(N="-1.0 / 1e-20"),r){const z=">=";return void(this.userCode=`
1705        const ivec2 strides = ivec2(${o}, ${l});
1706        const ivec2 pads = ivec2(${m}, ${g});
1707
1708        void main() {
1709          ivec4 coords = getOutputCoords();
1710          int batch = coords[0];
1711          int d = coords[3];
1712
1713          ivec2 xRCCorner = coords.yz * strides - pads;
1714          int xRCorner = xRCCorner.x;
1715          int xCCorner = xRCCorner.y;
1716
1717          // max/min x(?, ?, d) to get y(yR, yC, d).
1718          // ? = to be determined
1719          float minMaxValue = 0.0;
1720          float minMaxValueFound = 0.0;
1721          int minMaxPosition = 0;
1722          float avgValue = 0.0;
1723
1724          for (int wR = 0; wR < ${h};
1725              wR += ${p}) {
1726            int xR = xRCorner + wR;
1727
1728            if (xR < 0 || xR >= ${e.inHeight}) {
1729              continue;
1730            }
1731
1732            for (int wC = 0; wC < ${d};
1733                wC += ${c}) {
1734              int xC = xCCorner + wC;
1735
1736              if (xC < 0 || xC >= ${e.inWidth}) {
1737                continue;
1738              }
1739
1740              float value = getX(batch, xR, xC, d);
1741
1742              // If a min / max value has already been found, use it. If not,
1743              // use the current value.
1744              float currMinMaxValue = mix(
1745                  value, minMaxValue, minMaxValueFound);
1746              if (value ${z} currMinMaxValue) {
1747                minMaxValue = value;
1748                minMaxValueFound = 1.0;
1749                minMaxPosition = ${s?a?w:v:`wR * ${d} + wC`};
1750              }
1751            }
1752          }
1753          setOutput(float(minMaxPosition));
1754        }
1755      `)}let T=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(T="avgValue / max(count, 1.0)");const $=4*Math.floor(i/4),_=i%4,L=`
1756      if (${y}) {
1757        avgValue += dot(values, ones);
1758      } else {
1759        minMaxValue = max(values, minMaxValue);
1760      }
1761    `;this.userCode=`
1762      const ivec2 strides = ivec2(${o}, ${l});
1763      const ivec2 pads = ivec2(${m}, ${g});
1764      const float initializationValue = ${N};
1765      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
1766
1767      float count = 0.0;
1768
1769      float getValue(int batch, int xR, int xC, int d) {
1770        if (xC < 0 || xC >= ${e.inWidth}) {
1771          return initializationValue;
1772        }
1773        count += 1.0;
1774        return getX(batch, xR, xC, d);
1775      }
1776
1777      void main() {
1778        ivec4 coords = getOutputCoords();
1779        int batch = coords[0];
1780        int d = coords[3];
1781
1782        ivec2 xRCCorner = coords.yz * strides - pads;
1783        int xRCorner = xRCCorner.x;
1784        int xCCorner = xRCCorner.y;
1785
1786        // max/min x(?, ?, d) to get y(yR, yC, d).
1787        // ? = to be determined
1788        vec4 minMaxValue = vec4(${N});
1789        float avgValue = 0.0;
1790        count = 0.0;
1791
1792        for (int wR = 0; wR < ${h};
1793            wR += ${p}) {
1794          int xR = xRCorner + wR;
1795
1796          if (xR < 0 || xR >= ${e.inHeight}) {
1797            continue;
1798          }
1799
1800          for (int wC = 0; wC < ${$}; wC += 4) {
1801            int xC = xCCorner + wC * ${c};
1802
1803            vec4 values = vec4(
1804              getValue(batch, xR, xC, d),
1805              getValue(batch, xR, xC + ${c}, d),
1806              getValue(batch, xR, xC + 2 * ${c}, d),
1807              getValue(batch, xR, xC + 3 * ${c}, d)
1808            );
1809
1810            ${L}
1811          }
1812
1813          int xC = xCCorner + ${$};
1814          if (${_===1}) {
1815            vec4 values = vec4(
1816              getValue(batch, xR, xC, d),
1817              initializationValue,
1818              initializationValue,
1819              initializationValue
1820            );
1821
1822            ${L}
1823          } else if (${_===2}) {
1824            vec4 values = vec4(
1825              getValue(batch, xR, xC, d),
1826              getValue(batch, xR, xC + ${c}, d),
1827              initializationValue,
1828              initializationValue
1829            );
1830
1831            ${L}
1832          } else if (${_===3}) {
1833            vec4 values = vec4(
1834              getValue(batch, xR, xC, d),
1835              getValue(batch, xR, xC + ${c}, d),
1836              getValue(batch, xR, xC + 2 * ${c}, d),
1837              initializationValue
1838            );
1839
1840            ${L}
1841          }
1842        }
1843        setOutput(${T});
1844      }
1845    `}}class Ux{constructor(e,t,r,s=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");const i=e.filterWidth,o=e.strideDepth,l=e.strideHeight,p=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterDepth,g=e.effectiveFilterHeight,y=e.effectiveFilterWidth,w=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const T=t==="avg";let $="0.0";if(T||($="-1.0 / 1e-20"),r){const V=">=";return void(this.userCode=`
1846        const ivec3 strides =
1847            ivec3(${o}, ${l}, ${p});
1848        const ivec3 pads = ivec3(${w}, ${v}, ${N});
1849
1850        void main() {
1851          ivec5 coords = getOutputCoords();
1852          int batch = coords.x;
1853          int ch = coords.u;
1854
1855          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
1856          int xDCorner = xCorner.x;
1857          int xRCorner = xCorner.y;
1858          int xCCorner = xCorner.z;
1859
1860          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
1861          // ? = to be determined
1862          float minMaxValue = 0.0;
1863          float minMaxValueFound = 0.0;
1864          int minMaxPosition = 0;
1865
1866          for (int wD = 0; wD < ${m};
1867              wD += ${c}) {
1868            int xD = xDCorner + wD;
1869
1870            if (xD < 0 || xD >= ${e.inDepth}) {
1871              continue;
1872            }
1873
1874            for (int wR = 0; wR < ${g};
1875                wR += ${h}) {
1876              int xR = xRCorner + wR;
1877
1878              if (xR < 0 || xR >= ${e.inHeight}) {
1879                continue;
1880              }
1881
1882              for (int wC = 0; wC < ${y};
1883                  wC += ${d}) {
1884                int xC = xCCorner + wC;
1885
1886                if (xC < 0 || xC >= ${e.inWidth}) {
1887                  continue;
1888                }
1889
1890                float value = getX(batch, xD, xR, xC, ch);
1891
1892                // If a min / max value has already been found, use it. If not,
1893                // use the current value.
1894                float currMinMaxValue = mix(
1895                    value, minMaxValue, minMaxValueFound);
1896                if (value ${V} currMinMaxValue) {
1897                  minMaxValue = value;
1898                  minMaxValueFound = 1.0;
1899                  minMaxPosition = ${s?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${g} * ${y} +
1900                      wR * ${y} + wC`};
1901                }
1902              }
1903            }
1904          }
1905          setOutput(float(minMaxPosition));
1906        }
1907      `)}let _=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / max(count, 1.0)");const L=4*Math.floor(i/4),z=i%4,O=`
1908      if (${T}) {
1909        avgValue += dot(values, ones);
1910      } else {
1911        minMaxValue = max(values, minMaxValue);
1912      }
1913    `;this.userCode=`
1914      const ivec3 strides =
1915        ivec3(${o}, ${l}, ${p});
1916      const ivec3 pads = ivec3(${w}, ${v}, ${N});
1917      const float initializationValue = ${$};
1918      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
1919
1920      float count = 0.0;
1921
1922      float getValue(int batch, int xD, int xR, int xC, int ch) {
1923        if (xC < 0 || xC >= ${e.inWidth}) {
1924          return initializationValue;
1925        }
1926        count += 1.0;
1927        return getX(batch, xD, xR, xC, ch);
1928      }
1929
1930      void main() {
1931        ivec5 coords = getOutputCoords();
1932        int batch = coords.x;
1933        int ch = coords.u;
1934
1935        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
1936        int xDCorner = xCorner.x;
1937        int xRCorner = xCorner.y;
1938        int xCCorner = xCorner.z;
1939
1940        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
1941        // ? = to be determined
1942        vec4 minMaxValue = vec4(${$});
1943        float avgValue = 0.0;
1944        count = 0.0;
1945
1946        for (int wD = 0; wD < ${m};
1947            wD += ${c}) {
1948          int xD = xDCorner + wD;
1949
1950          if (xD < 0 || xD >= ${e.inDepth}) {
1951            continue;
1952          }
1953
1954          for (int wR = 0; wR < ${g};
1955            wR += ${h}) {
1956            int xR = xRCorner + wR;
1957
1958            if (xR < 0 || xR >= ${e.inHeight}) {
1959              continue;
1960            }
1961
1962            for (int wC = 0; wC < ${L}; wC += 4) {
1963              int xC = xCCorner + wC * ${d};
1964
1965              vec4 values = vec4(
1966                getValue(batch, xD, xR, xC, ch),
1967                getValue(batch, xD, xR, xC + ${d}, ch),
1968                getValue(batch, xD, xR, xC + 2 * ${d}, ch),
1969                getValue(batch, xD, xR, xC + 3 * ${d}, ch)
1970              );
1971
1972              ${O}
1973            }
1974
1975            int xC = xCCorner + ${L};
1976            if (${z===1}) {
1977              vec4 values = vec4(
1978                getValue(batch, xD, xR, xC, ch),
1979                initializationValue,
1980                initializationValue,
1981                initializationValue
1982              );
1983
1984              ${O}
1985            } else if (${z===2}) {
1986              vec4 values = vec4(
1987                getValue(batch, xD, xR, xC, ch),
1988                getValue(batch, xD, xR, xC + ${d}, ch),
1989                initializationValue,
1990                initializationValue
1991              );
1992
1993              ${O}
1994            } else if (${z===3}) {
1995              vec4 values = vec4(
1996                getValue(batch, xD, xR, xC, ch),
1997                getValue(batch, xD, xR, xC + ${d}, ch),
1998                getValue(batch, xD, xR, xC + 2 * ${d}, ch),
1999                initializationValue
2000              );
2001
2002              ${O}
2003            }
2004          }
2005        }
2006        setOutput(${_});
2007      }
2008    `}}const SO={kernelName:xc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e;sp(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;A(bs(i,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`);const p=li(s.shape,a,i,1,o,l);if(p.filterWidth===1&&p.filterHeight===1&&le(p.inShape,p.outShape))return Ra({inputs:{x:s},backend:t});const c=new Kf(p,"avg",!1);return t.runWebGLProgram(c,[s],"float32")}},TO={kernelName:Qu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=r,c=_u(s.shape,a,i,[1,1,1],o,l,p),h=new Ux(c,"avg",!1);return t.runWebGLProgram(h,[s],"float32")}};class EO{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,r=e.filterWidth,s=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,c=l-1-e.padInfo.top,h=p-1-e.padInfo.left,d=1/(t*r);this.userCode=`
2009      const ivec2 pads = ivec2(${c}, ${h});
2010      const float avgMultiplier = float(${d});
2011
2012      void main() {
2013        ivec4 coords = getOutputCoords();
2014        int b = coords[0];
2015        int d = coords[3];
2016
2017        ivec2 dyRCCorner = coords.yz - pads;
2018        int dyRCorner = dyRCCorner.x;
2019        int dyCCorner = dyRCCorner.y;
2020
2021        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
2022        // ? = to be determined. : = across all values in that axis.
2023        float dotProd = 0.0;
2024        for (int wR = 0; wR < ${l};
2025            wR += ${i}) {
2026          float dyR = float(dyRCorner + wR) / ${s}.0;
2027
2028          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2029            continue;
2030          }
2031          int idyR = int(dyR);
2032
2033          for (int wC = 0; wC < ${p};
2034            wC+= ${o}) {
2035            float dyC = float(dyCCorner + wC) / ${a}.0;
2036
2037            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2038                fract(dyC) > 0.0) {
2039              continue;
2040            }
2041            int idyC = int(dyC);
2042
2043            float dyValue = getDy(b, idyR, idyC, d);
2044
2045            dotProd += dyValue * avgMultiplier;
2046          }
2047        }
2048        setOutput(dotProd);
2049      }
2050    `}}class CO{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,r=e.filterHeight,s=e.filterWidth,a=e.strideDepth,i=e.strideHeight,o=e.strideWidth,l=e.dilationDepth,p=e.dilationHeight,c=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,m=e.effectiveFilterWidth,g=h-1-e.padInfo.front,y=d-1-e.padInfo.top,w=m-1-e.padInfo.left,v=1/(t*r*s);this.userCode=`
2051      const ivec3 pads = ivec3(${g}, ${y}, ${w});
2052      const float avgMultiplier = float(${v});
2053
2054      void main() {
2055        ivec5 coords = getOutputCoords();
2056        int batch = coords.x;
2057        int ch = coords.u;
2058
2059        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
2060        int dyDCorner = dyCorner.x;
2061        int dyRCorner = dyCorner.y;
2062        int dyCCorner = dyCorner.z;
2063
2064        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
2065        // dx(xD, xR, xC, ch).
2066        // ? = to be determined. : = across all values in that axis.
2067        float dotProd = 0.0;
2068
2069        for (int wD = 0; wD < ${h};
2070            wD += ${l}) {
2071          float dyD = float(dyDCorner + wD) / ${a}.0;
2072
2073          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2074            continue;
2075          }
2076          int idyD = int(dyD);
2077
2078          for (int wR = 0; wR < ${d};
2079              wR += ${p}) {
2080            float dyR = float(dyRCorner + wR) / ${i}.0;
2081
2082            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2083                fract(dyR) > 0.0) {
2084              continue;
2085            }
2086            int idyR = int(dyR);
2087
2088            for (int wC = 0; wC < ${m};
2089                wC += ${c}) {
2090              float dyC = float(dyCCorner + wC) / ${o}.0;
2091
2092              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2093                  fract(dyC) > 0.0) {
2094                continue;
2095              }
2096              int idyC = int(dyC);
2097
2098              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2099
2100              dotProd += dyValue * avgMultiplier;
2101            }
2102          }
2103        }
2104        setOutput(dotProd);
2105      }
2106    `}}const $O={kernelName:Ju,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,i=a,{filterSize:o,strides:l,pad:p,dimRoundingMode:c}=r,h=_u(i.shape,o,l,[1,1,1],p,c),d=new CO(h);return t.runWebGLProgram(d,[s],i.dtype)}},AO={kernelName:wc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,i=a;sp([s,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:p}=r,c=li(i.shape,o,l,1,p),h=new EO(c);return t.runWebGLProgram(h,[s],i.dtype)}},RO={kernelName:yo,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a}=e,{transposeA:i,transposeB:o}=r;return yy({a:s,b:a,transposeA:i,transposeB:o,backend:t})}};class _O{constructor(e,t,r,s,a,i){this.outputShape=[],this.variableNames=["x","mean","variance"],Gt(e,t),Gt(e,r);let o="0.0";s!=null&&(Gt(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let l="1.0";a!=null&&(Gt(e,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2107      void main() {
2108        float x = getXAtOutCoords();
2109        float mean = getMeanAtOutCoords();
2110        float variance = getVarianceAtOutCoords();
2111        float offset = ${o};
2112        float scale = ${l};
2113        float inv = scale * inversesqrt(variance + float(${i}));
2114        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
2115      }
2116    `}}class DO{constructor(e,t,r,s,a,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Gt(e,t),Gt(e,r);let o="vec4(0.0)";s!=null&&(Gt(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let l="vec4(1.0)";a!=null&&(Gt(e,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2117      void main() {
2118        vec4 offset = ${o};
2119        vec4 scale = ${l};
2120
2121        vec4 x = getXAtOutCoords();
2122        vec4 mean = getMeanAtOutCoords();
2123        vec4 variance = getVarianceAtOutCoords();
2124
2125        vec4 inv = scale * inversesqrt(variance + vec4(${i}));
2126
2127        setOutput((x - mean) * inv + offset);
2128      }
2129    `}}const FO={kernelName:hl,backendName:"webgl",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:r,mean:s,variance:a,offset:i,scale:o}=n;A(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);const p=[r,s,a];let c=null;i!=null&&(c=i.shape,p.push(i));let h=null;o!=null&&(h=o.shape,p.push(o));const d=xe().getBool("WEBGL_PACK_NORMALIZATION")?new DO(r.shape,s.shape,a.shape,c,h,l):new _O(r.shape,s.shape,a.shape,c,h,l);return e.runWebGLProgram(d,p,p[0].dtype)}};class MO{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Xn(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];
2129const r=function(a){if(a===1)return"sourceLoc";if(a<=6)return Wx.slice(0,a).map(i=>"sourceLoc."+i).join(",");throw Error(`Slicing for rank ${a} is not yet supported`)}(this.rank);let s;s=`
2130        ${t} sourceLoc;
2131        ${t} coords = getOutputCoords();
2132        ${e.map((a,i)=>`sourceLoc.${Wx[i]} = start[${i}] + coords.${Wx[i]};`).join(`
2133`)}
2134      `,this.userCode=`
2135      void main() {
2136        ${s}
2137        setOutput(getSource(${r}));
2138      }
2139    `}}const Wx=["x","y","z","w","u","v"];class OO{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=Xn(this.rank),r=qs("coords",this.rank),s=qs("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,i=`getChannel(getSource(${s.join()}), ${a})`,o=`
2140      result.x = ${i};
2141      if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
2142        ++${s[this.rank-1]};
2143        result.y = ${i};
2144        --${s[this.rank-1]};
2145      }
2146    `,l=this.rank===1?"":`
2147      --${r[this.rank-1]};
2148      if (++${r[this.rank-2]} < ${e[this.rank-2]}) {
2149        ++${s[this.rank-2]};
2150        result.z = ${i};
2151        if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
2152          ++${s[this.rank-1]};
2153          result.w = ${i};
2154        }
2155      }
2156    `,p=this.rank<=4?`sourceLoc = coords +
2157            ${t}(${e.map((c,h)=>`start[${h}]`).join()});`:e.map((c,h)=>`${s[h]} = ${r[h]} + start[${h}];`).join(`
2158`);this.userCode=`
2159      void main() {
2160        ${t} coords = getOutputCoords();
2161        ${t} sourceLoc;
2162        ${p}
2163        vec4 result = vec4(0.);
2164        ${o}
2165        ${l}
2166        setOutput(result);
2167      }
2168    `}}function hp(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,size:i}=r,[o,l]=rn(s,a,i);if(Ed(s,o,l),j(l)===0)return t.makeTensorInfo(l,s.dtype,[]);if(t.shouldExecuteOnCPU([s])||s.dtype==="string"){const h=t.texData.get(s.dataId),d=wM(h.values,o,l,s.shape,s.dtype);return t.makeTensorInfo(l,s.dtype,d)}const{isPacked:p}=t.texData.get(s.dataId),c=qt(s.shape,o,l);if(p||!c){const h=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new OO(l):new MO(l),d=[o];return t.runWebGLProgram(h,[s],s.dtype,d)}return t.uploadToGPU(s.dataId),function(h,d,m,g){const y=g.texData.get(h.dataId),w=g.makeTensorInfo(m,h.dtype),v=g.texData.get(w.dataId);Object.assign(v,y),v.refCount=1,v.shape=m,v.dtype=h.dtype;let N=un(d,Ge(h.shape));y.slice&&(N+=y.slice.flatOffset),v.slice={flatOffset:N,origDataId:y.slice&&y.slice.origDataId||h.dataId};const T=g.dataRefCount.get(v.slice.origDataId)||1;return g.dataRefCount.set(v.slice.origDataId,T+1),w}(s,o,l,t)}const LO={kernelName:Lc,backendName:"webgl",kernelFunc:hp},zO={kernelName:el,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,crops:i}=r;A(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const o=a.reduce((N,T)=>N*T),l=pf(s.shape,a,o),p=ff(l.length,a.length),c=mf(s.shape,a,o),h=U0(i,a.length),d=W0(c,i,a.length),m=[],g=It({inputs:{x:s},backend:t,attrs:{shape:l}}),y=Xs({inputs:{x:g},backend:t,attrs:{perm:p}}),w=It({inputs:{x:y},backend:t,attrs:{shape:c}}),v=hp({inputs:{x:w},backend:t,attrs:{begin:h,size:d}});return m.push(g),m.push(y),m.push(w),m.forEach(N=>t.disposeIntermediateTensorInfo(N)),v}},PO={kernelName:eu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:i}=r,o=t.readSync(s.dataId),l=t.readSync(a.dataId),p=rS(o,l,a.dtype,a.shape,i);return t.makeTensorInfo([i],a.dtype,p)}},BO={kernelName:ki,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{a:r,b:s}=e,a=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=xe().getNumber("WEBGL_VERSION");if(t.shouldExecuteOnCPU([r,s])||i===1){const l=t.texData.get(r.dataId).values,p=t.texData.get(s.dataId).values,[c,h]=GF(r.shape,s.shape,l,p,r.dtype),d=t.makeTensorInfo(h,r.dtype);return t.texData.get(d.dataId).values=c,d}let o;return o=a?new lp(`
2169  int r = int(a.r) & int(b.r);
2170  int g = int(a.g) & int(b.g);
2171  int rb = int(a.b) & int(b.b);
2172  int ra = int(a.a) & int(b.a);
2173  return vec4(r, g, rb, ra);
2174`,r.shape,s.shape,!1):new Fh(`
2175  return float(int(a.r) & int(b.r));
2176`,r.shape,s.shape),t.runWebGLProgram(o,[r,s],r.dtype)}},VO={kernelName:vc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{s0:r,s1:s}=e,a=t.readSync(r.dataId),i=t.readSync(s.dataId),o=Gt(Array.from(a),Array.from(i));return t.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},ES=Is({opSnippet:"return float(a != b);",cpuKernelImpl:hM,dtype:"bool"}),UO={kernelName:$o,backendName:"webgl",kernelFunc:ES};function qf(n){const{inputs:e,backend:t}=n,{input:r}=e;return Ra({inputs:{x:t.texData.get(r.dataId).complexTensorInfos.real},backend:t})}const WO={kernelName:xl,backendName:"webgl",kernelFunc:qf},GO={kernelName:tl,backendName:"webgl",kernelFunc:function n(e){const{inputs:t,backend:r,attrs:s}=e,{x:a}=t,{dtype:i}=s;if(i==="complex64"){if(a.dtype==="complex64")return Ra({inputs:{x:a},backend:r});
2176const o=Wr(a.shape),l=n({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),p=pc({inputs:{real:l,imag:o},backend:r});return o.dispose(),r.disposeIntermediateTensorInfo(l),p}if(a.dtype==="complex64"){const o=qf({inputs:{input:a},backend:r}),l=n({inputs:{x:o},backend:r,attrs:{dtype:i}});return r.disposeIntermediateTensorInfo(o),l}if(!ve(a.dtype,i)){const o=Ra({inputs:{x:a},backend:r});return{dataId:o.dataId,shape:o.shape,dtype:i}}if(r.shouldExecuteOnCPU([a])){const o=r.texData.get(a.dataId).values,[l,p,c]=HF(o,a.shape,a.dtype,i);return r.makeTensorInfo(l,p,c)}if(i==="int32")return function(o,l){const p=new Qo(o.shape,"return float(int(x));"),c=l.runWebGLProgram(p,[o],"int32");return{dataId:c.dataId,shape:c.shape,dtype:c.dtype}}(a,r);if(i==="bool"){const o=r.makeTensorInfo([],"bool",_t("bool",1)),l=ES({inputs:{a,b:o},backend:r});return r.disposeIntermediateTensorInfo(o),l}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},CS="return ceil(x);",HO=Cn({opSnippet:CS,packedOpSnippet:CS,cpuKernelImpl:jF}),jO={kernelName:nl,backendName:"webgl",kernelFunc:HO};class KO{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2177
2178      void main() {
2179        float value = getAAtOutCoords();
2180        if (isnan(value)) {
2181          setOutput(value);
2182          return;
2183        }
2184
2185        setOutput(clamp(value, minVal, maxVal));
2186      }
2187    `}}class qO{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2188      void main() {
2189        vec4 value = getAAtOutCoords();
2190
2191        if (any(isnan(value))) {
2192          setOutput(value);
2193          return;
2194        }
2195
2196        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
2197      }
2198    `}}const XO={kernelName:bo,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{clipValueMin:a,clipValueMax:i}=r;let o;o=xe().getBool("WEBGL_PACK_CLIP")?new qO(s.shape):new KO(s.shape);const l=[[a],[i]];return t.runWebGLProgram(o,[s],s.dtype,l)}};class YO{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2199      void main() {
2200        float re = abs(getRealAtOutCoords());
2201        float im = abs(getImagAtOutCoords());
2202        float mx = max(re, im);
2203
2204        // sadly the length function in glsl is not underflow-safe
2205        // (at least not on Intel GPUs). So the safe solution is
2206        // to ensure underflow-safety in all cases.
2207        setOutput(
2208          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
2209        );
2210      }
2211    `}}function $S(n,e){return{dataId:e.dataId,dtype:e.dtype,shape:n.shape}}const ZO={kernelName:rl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e,s=t.texData.get(r.dataId),a=new YO(r.shape),i=[$S(r,s.complexTensorInfos.real),$S(r,s.complexTensorInfos.imag)];return t.runWebGLProgram(a,i,i[0].dtype)}};class QO{constructor(e){this.outputShape=[],this.outputShape=jo(e,1),this.variableNames=e.map((i,o)=>`T${o}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let i=1;i<t.length;i++)t[i]=t[i-1]+e[i][1];const r=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<t.length;i++){const o=t[i-1];r.push(`else if (yC < ${t[i]}) setOutput(getT${i}(yR, yC-${o}));`)}const s=t.length,a=t[t.length-1];r.push(`else setOutput(getT${s}(yR, yC-${a}));`),this.userCode=`
2212      void main() {
2213        ivec2 coords = getOutputCoords();
2214        int yR = coords.x;
2215        int yC = coords.y;
2216
2217        ${r.join(`
2218        `)}
2219      }
2220    `}}class JO{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=jo(e,t);const r=this.outputShape,s=r.length,a=Xn(s),i=qs("coords",s),o=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((y,w)=>`T${w}`);const l=new Array(e.length-1);l[0]=e[0][t];for(let y=1;y<l.length;y++)l[y]=l[y-1]+e[y][t];const p=o[t],c=o.slice(-2),h=o.join();let d=`if (${p} < ${l[0]}) {
2221        return getChannel(
2222            getT0(${h}), vec2(${c.join()}));
2223        }`;for(let y=1;y<l.length;y++){const w=l[y-1];d+=`
2224        if (${p} < ${l[y]}  && ${p} >= ${l[y-1]}) {
2225          return getChannel(
2226            getT${y}(${by(o,p,w)}),
2227            vec2(${by(c,p,w)}));
2228        }`}const m=l.length,g=l[l.length-1];d+=`
2229        return getChannel(
2230          getT${m}(${by(o,p,g)}),
2231          vec2(${by(c,p,g)}));`,this.userCode=`
2232      float getValue(${o.map(y=>"int "+y)}) {
2233        ${d}
2234      }
2235
2236      void main() {
2237        ${a} coords = getOutputCoords();
2238        vec4 result = vec4(getValue(${i}), 0., 0., 0.);
2239
2240        ${i[s-1]} = ${i[s-1]} + 1;
2241        if (${i[s-1]} < ${r[s-1]}) {
2242          result.g = getValue(${i});
2243        }
2244
2245        ${i[s-2]} = ${i[s-2]} + 1;
2246        if (${i[s-2]} < ${r[s-2]}) {
2247          result.a = getValue(${i});
2248        }
2249
2250        ${i[s-1]} = ${i[s-1]} - 1;
2251        if (${i[s-2]} < ${r[s-2]} &&
2252            ${i[s-1]} < ${r[s-1]}) {
2253          result.b = getValue(${i});
2254        }
2255        setOutput(result);
2256      }
2257    `}}function by(n,e,t){const r=n.indexOf(e);return n.map((s,a)=>a===r?`${s} - ${t}`:s).join()}function xy(n){const{inputs:e,backend:t}=n,{input:r}=e;return Ra({inputs:{x:t.texData.get(r.dataId).complexTensorInfos.imag},backend:t})}const eL={kernelName:Ei,backendName:"webgl",kernelFunc:xy};function Xf(n,e,t){const r=n[0].dtype;if(r==="complex64"){const m=n.map(N=>qf({inputs:{input:N},backend:t})),g=n.map(N=>
vendor: 10,612 bytes, lines 2257-2489
2257xy({inputs:{input:N},backend:t})),y=Xf(m,e,t),w=Xf(g,e,t),v=pc({inputs:{real:y,imag:w},backend:t});return m.forEach(N=>t.disposeIntermediateTensorInfo(N)),g.forEach(N=>t.disposeIntermediateTensorInfo(N)),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(w),v}let s=t.shouldExecuteOnCPU(n);if(r==="string"&&(s=!0),s){const m=n.map($=>{const _=j($.shape.slice(e));return It({inputs:{x:$},backend:t,attrs:{shape:[-1,_]}})}),g=m.map($=>({vals:t.readSync($.dataId),shape:$.shape})),y=jo(m.map($=>$.shape),1),w=m[0].shape[0]===1,v=KF(g,y,r,w),N=jo(n.map($=>$.shape),e),T=t.makeTensorInfo(N,r,v);return m.forEach($=>t.disposeIntermediateTensorInfo($)),T}const a=n.filter(m=>j(m.shape)>0),i=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(a.length===1){const m=i?new Qo(n[0].shape,hc):new dc(n[0].shape,hc);return t.runWebGLProgram(m,n,r)}const o=xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(a.length>o){const m=[];for(let y=0;y<a.length;y+=o){const w=a.slice(y,y+o);m.push(Xf(w,e,t))}const g=Xf(m,e,t);for(const y of m)t.disposeIntermediateTensorInfo(y);return g}if(i){const m=new JO(a.map(g=>g.shape),e);return t.runWebGLProgram(m,a,r)}const{tensors2D:l,outShape:p}=function(m,g,y){const w=jo(m.map(v=>v.shape),g);return{tensors2D:m.map(v=>It({inputs:{x:v},attrs:{shape:[-1,j(v.shape.slice(g))]},backend:y})),outShape:w}}(a,e,t),c=new QO(l.map(m=>m.shape)),h=t.runWebGLProgram(c,l,r);l.forEach(m=>t.disposeIntermediateTensorInfo(m));const d=It({inputs:{x:h},attrs:{shape:p},backend:t});return t.disposeIntermediateTensorInfo(h),d}function AS(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r,a=Oe(s,e[0].shape)[0];P0(e.map(l=>l.shape),a);const i=jo(e.map(l=>l.shape),a);if(j(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);const o=e.filter(l=>j(l.shape)>0);return o.length===1?Ra({inputs:{x:o[0]},backend:t}):Xf(o,a,t)}const tL={kernelName:tu,backendName:"webgl",kernelFunc:AS};class RS{constructor(e,t=!1,r=null,s=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,o=e.padInfo.left,l=e.strideHeight,p=e.strideWidth,c=e.dilationHeight,h=e.dilationWidth,d=e.filterHeight,m=e.filterWidth,g=4*Math.floor(e.inChannels/4),y=e.inChannels%4,w=e.dataFormat==="channelsLast",v=w?1:2,N=w?2:3,T=w?3:1;let $="",_="";r&&($=s?`float activation(float a) {
2258          float b = getPreluActivationWeightsAtOutCoords();
2259          ${r}
2260        }`:a?`float activation(float a) {
2261          float b = getLeakyreluAlphaAtOutCoords();
2262          ${r}
2263        }`:`
2264          float activation(float x) {
2265            ${r}
2266          }
2267        `,_="result = activation(result);");const L=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2268      ${$}
2269
2270      const ivec2 strides = ivec2(${l}, ${p});
2271      const ivec2 pads = ivec2(${i}, ${o});
2272
2273      void main() {
2274        ivec4 coords = getOutputCoords();
2275        int batch = coords[0];
2276        int d2 = coords[${T}];
2277
2278        ivec2 xRCCorner =
2279            ivec2(coords[${v}], coords[${N}]) * strides - pads;
2280        int xRCorner = xRCCorner.x;
2281        int xCCorner = xRCCorner.y;
2282
2283        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
2284        // ? = to be determined. : = across all values in that axis.
2285        float dotProd = 0.0;
2286        for (int wR = 0; wR < ${d}; wR++) {
2287          int xR = xRCorner + wR * ${c};
2288
2289          if (xR < 0 || xR >= ${e.inHeight}) {
2290            continue;
2291          }
2292
2293          for (int wC = 0; wC < ${m}; wC++) {
2294            int xC = xCCorner + wC * ${h};
2295
2296            if (xC < 0 || xC >= ${e.inWidth}) {
2297              continue;
2298            }
2299
2300            for (int d1 = 0; d1 < ${g}; d1 += 4) {
2301              vec4 wValues = vec4(
2302                getW(wR, wC, d1, d2),
2303                getW(wR, wC, d1 + 1, d2),
2304                getW(wR, wC, d1 + 2, d2),
2305                getW(wR, wC, d1 + 3, d2)
2306              );
2307
2308              if (${w}) {
2309                vec4 xValues = vec4(
2310                  getX(batch, xR, xC, d1),
2311                  getX(batch, xR, xC, d1 + 1),
2312                  getX(batch, xR, xC, d1 + 2),
2313                  getX(batch, xR, xC, d1 + 3)
2314                );
2315                dotProd += dot(xValues, wValues);
2316              } else {
2317                vec4 xValues = vec4(
2318                  getX(batch, d1, xR, xC),
2319                  getX(batch, d1 + 1, xR, xC),
2320                  getX(batch, d1 + 2, xR, xC),
2321                  getX(batch, d1 + 3, xR, xC)
2322                );
2323                dotProd += dot(xValues, wValues);
2324              }
2325            }
2326
2327            if (${y===1}) {
2328
2329              if (${w}) {
2330                dotProd +=
2331                    getX(batch, xR, xC, ${g}) *
2332                    getW(wR, wC, ${g}, d2);
2333              } else {
2334                dotProd +=
2335                    getX(batch, ${g}, xR, xC) *
2336                    getW(wR, wC, ${g}, d2);
2337              }
2338
2339            } else if (${y===2}) {
2340              vec2 wValues = vec2(
2341                getW(wR, wC, ${g}, d2),
2342                getW(wR, wC, ${g} + 1, d2)
2343              );
2344
2345              if (${w}) {
2346                vec2 xValues = vec2(
2347                  getX(batch, xR, xC, ${g}),
2348                  getX(batch, xR, xC, ${g} + 1)
2349                );
2350                dotProd += dot(xValues, wValues);
2351              } else {
2352                vec2 xValues = vec2(
2353                  getX(batch, ${g}, xR, xC),
2354                  getX(batch, ${g} + 1, xR, xC)
2355                );
2356                dotProd += dot(xValues, wValues);
2357              }
2358
2359            } else if (${y===3}) {
2360              vec3 wValues = vec3(
2361                getW(wR, wC, ${g}, d2),
2362                getW(wR, wC, ${g} + 1, d2),
2363                getW(wR, wC, ${g} + 2, d2)
2364              );
2365
2366              if (${w}) {
2367                vec3 xValues = vec3(
2368                  getX(batch, xR, xC, ${g}),
2369                  getX(batch, xR, xC, ${g} + 1),
2370                  getX(batch, xR, xC, ${g} + 2)
2371                );
2372                dotProd += dot(xValues, wValues);
2373              } else {
2374                vec3 xValues = vec3(
2375                  getX(batch, ${g}, xR, xC),
2376                  getX(batch, ${g} + 1, xR, xC),
2377                  getX(batch, ${g} + 2, xR, xC)
2378                );
2379                dotProd += dot(xValues, wValues);
2380              }
2381
2382            }
2383          }
2384        }
2385
2386        float result = dotProd;
2387        ${L}
2388        ${_}
2389        setOutput(result);
2390      }
2391    `}}class nL{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,r=e.padInfo.top,s=e.padInfo.left,a=e.strideDepth,i=e.strideHeight,o=e.strideWidth,l=e.dilationDepth,p=e.dilationHeight,c=e.dilationWidth,h=e.filterDepth,d=e.filterHeight,m=e.filterWidth,g=4*Math.floor(e.inChannels/4),y=e.inChannels%4;this.userCode=`
2392      const ivec3 strides = ivec3(${a}, ${i}, ${o});
2393      const ivec3 pads = ivec3(${t}, ${r}, ${s});
2394
2395      void main() {
2396        ivec5 coords = getOutputCoords();
2397        int batch = coords.x;
2398        int d2 = coords.u;
2399
2400        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
2401        int xFCorner = xFRCCorner.x;
2402        int xRCorner = xFRCCorner.y;
2403        int xCCorner = xFRCCorner.z;
2404
2405        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
2406        // y(yF, yR, yC, d2). ? = to be determined. : = across all
2407        // values in that axis.
2408        float dotProd = 0.0;
2409        for (int wF = 0; wF < ${h}; wF++) {
2410          int xF = xFCorner + wF * ${l};
2411
2412          if (xF < 0 || xF >= ${e.inDepth}) {
2413            continue;
2414          }
2415
2416          for (int wR = 0; wR < ${d}; wR++) {
2417            int xR = xRCorner + wR * ${p};
2418
2419            if (xR < 0 || xR >= ${e.inHeight}) {
2420              continue;
2421            }
2422
2423            for (int wC = 0; wC < ${m}; wC++) {
2424              int xC = xCCorner + wC * ${c};
2425
2426              if (xC < 0 || xC >= ${e.inWidth}) {
2427                continue;
2428              }
2429
2430              for (int d1 = 0; d1 < ${g}; d1 += 4) {
2431                vec4 xValues = vec4(
2432                  getX(batch, xF, xR, xC, d1),
2433                  getX(batch, xF, xR, xC, d1 + 1),
2434                  getX(batch, xF, xR, xC, d1 + 2),
2435                  getX(batch, xF, xR, xC, d1 + 3)
2436                );
2437                vec4 wValues = vec4(
2438                  getW(wF, wR, wC, d1, d2),
2439                  getW(wF, wR, wC, d1 + 1, d2),
2440                  getW(wF, wR, wC, d1 + 2, d2),
2441                  getW(wF, wR, wC, d1 + 3, d2)
2442                );
2443
2444                dotProd += dot(xValues, wValues);
2445              }
2446
2447              if (${y===1}) {
2448                dotProd +=
2449                  getX(batch, xF, xR, xC, ${g}) *
2450                  getW(wF, wR, wC, ${g}, d2);
2451              } else if (${y===2}) {
2452                vec2 xValues = vec2(
2453                  getX(batch, xF, xR, xC, ${g}),
2454                  getX(batch, xF, xR, xC, ${g} + 1)
2455                );
2456                vec2 wValues = vec2(
2457                  getW(wF, wR, wC, ${g}, d2),
2458                  getW(wF, wR, wC, ${g} + 1, d2)
2459                );
2460                dotProd += dot(xValues, wValues);
2461              } else if (${y===3}) {
2462                vec3 xValues = vec3(
2463                  getX(batch, xF, xR, xC, ${g}),
2464                  getX(batch, xF, xR, xC, ${g} + 1),
2465                  getX(batch, xF, xR, xC, ${g} + 2)
2466                );
2467                vec3 wValues = vec3(
2468                  getW(wF, wR, wC, ${g}, d2),
2469                  getW(wF, wR, wC, ${g} + 1, d2),
2470                  getW(wF, wR, wC, ${g} + 2, d2)
2471                );
2472                dotProd += dot(xValues, wValues);
2473              }
2474            }
2475          }
2476        }
2477        setOutput(dotProd);
2478      }
2479    `}}class _S{constructor(e,t=!1,r=null,s=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ds(this.outputShape.length);const i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,p=e.filterHeight,c=e.filterWidth,h=c;let d=`
2480       int xR; int xC; int xCOffset;
2481       vec4 wTexel; vec4 previous; vec4 final;`;for(let w=0;w<c;w++)d+=`
2482           vec4 xTexelC${2*w};
2483           int xTexelC${2*w}Ready;
2484           vec4 xTexelC${2*w+1};
2485           int xTexelC${2*w+1}Ready;
2486           vec4 xC${w};`;d+=`
2487     for (int r = 0; r < ${p}; r++) {
2488      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
2489       `;
2489for(let w=0;w<c;w++)d+=`
2490           xTexelC${2*w} = vec4(0.0);
2491           xTexelC${2*w}Ready = 0;
2492           xTexelC${2*w+1} = vec4(0.0);
2493           xTexelC${2*w+1}Ready = 0;
2494           xC${w} = vec4(0.0);`;d+=`
2495         xR = xRCorner + r * dilations[0];
2496         if (xR >=0 && xR < inDims[0]) {
2497       `;for(let w=0;w<(h+1)/2;w++){const v=2*w;if(d+=`
2498           xC = xCCorner + ${v*l};
2499           `,o===1){if(v<c&&(i%2==1?(d+=`
2500                 xCOffset = xC + 1;
2501                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v}Ready == 0) {
2502                   xTexelC${v} = getX(batch, xR, xCOffset, d1);
2503
2504                   // Need to manually clear unused channels in case
2505                   // we're reading from recycled texture.
2506                   if (xCOffset + 1 >= inDims[1]) {
2507                     xTexelC${v}.zw = vec2(0.0);
2508                   }
2509                   xTexelC${v}Ready = 1;
2510                 }
2511               `,d+=l===1&&v>0?`
2512                 xC${v} = vec4(xTexelC${v-2}.zw, xTexelC${v}.xy);
2513                 `:`
2514                   xCOffset = xC + 1 - 2;
2515
2516                   if (xCOffset >= 0 && xCOffset < inDims[1]) {
2517                     previous = getX(batch, xR, xCOffset, d1);
2518
2519                     // Need to manually clear unused channels in case
2520                     // we're reading from recycled texture.
2521                     if (xCOffset + 1 >= inDims[1]) {
2522                       previous.zw = vec2(0.0);
2523                     }
2524
2525                     xC${v} = vec4(previous.zw, xTexelC${v}.xy);
2526                   } else {
2527                     xC${v} = vec4(0.0, 0.0, xTexelC${v}.xy);
2528                   }
2529                   `):d+=`
2530                 if (xC >= 0 && xC < inDims[1] && xTexelC${v}Ready == 0) {
2531                   xTexelC${v} = getX(batch, xR, xC, d1);
2532                   if (xC + 1 >= inDims[1]) {
2533                     xTexelC${v}.zw = vec2(0.0);
2534                   }
2535                   xTexelC${v}Ready = 1;
2536                 }
2537
2538                 xC${v} = xTexelC${v};
2539                 `,v+1<c)){const N=i%2==0?Ce(l):l;l%2==0&&i%2==1||l%2!=0&&i%2!=1?(d+=`
2540                   xCOffset = xC + imod(pads[1], 2) + ${N};
2541
2542                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) {
2543                     xTexelC${v+1} = getX(batch, xR, xCOffset, d1);
2544
2545                     // Need to manually clear unused channels in case
2546                     // we're reading from recycled texture.
2547                     if (xCOffset + 1 >= inDims[1]) {
2548                       xTexelC${v+1}.zw = vec2(0.0);
2549                     }
2550                     xTexelC${v+1}Ready = 1;
2551                   }
2552                   `,d+=l>1?`
2553                     xCOffset -= 2;
2554                     if (xCOffset >= 0 && xCOffset < inDims[1]) {
2555                      previous = getX(batch, xR, xCOffset, d1);
2556                      xC${v+1} = vec4(previous.zw, xTexelC${v+1}.xy);
2557                     } else {
2558                      xC${v+1} = vec4(0.0, 0.0, xTexelC${v+1}.xy);
2559                     }
2560                     `:`
2561                     xC${v+1} = vec4(xTexelC${v}.zw, xTexelC${v+1}.xy);
2562                     `):d+=N===1?`
2563                     xC${v+1} = xTexelC${v};
2564                     `:`
2565                     xCOffset = xC + ${N};
2566
2567                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) {
2568                       xTexelC${v+1} = getX(batch, xR, xCOffset, d1);
2569                       if (xCOffset + 1 >= inDims[1]) {
2570                         xTexelC${v+1}.zw = vec2(0.0);
2571                       }
2572                       xTexelC${v+1}Ready = 1;
2573                     }
2574
2575                     xC${v+1} = xTexelC${v+1};
2576                     `}}else v<c&&(i%2==1?(d+=`
2577                 xCOffset = xC + 1 - strides[1];
2578                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v}Ready == 0) {
2579                   xTexelC${v} = getX(batch, xR, xCOffset, d1);
2580                   // Need to manually clear unused channels in case
2581                   // we're reading from recycled texture.
2582                   if (xCOffset + 1 >= inDims[1]) {
2583                     xTexelC${v}.zw = vec2(0.0);
2584                   }
2585                   xTexelC${v}Ready = 1;
2586                 }
2587
2588                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${v+1}Ready == 0) {
2589                   xTexelC${v+1} = getX(batch, xR, xC + 1, d1);
2590                   // Need to manually clear unused channels in case
2591                   // we're reading from recycled texture.
2592                   if (xC + 2 >= inDims[1]) {
2593                     xTexelC${v+1}.zw = vec2(0.0);
2594                   }
2595                   xTexelC${v+1}Ready = 1;
2596                 }
2597
2598                 xC${v} = vec4(xTexelC${v}.zw, xTexelC${v+1}.zw);
2599               `,v+1<c&&(d+=`
2600                   final = vec4(0.0);
2601                   xCOffset = xC + 1 + strides[1];
2602                   if(xCOffset >= 0 && xCOffset < inDims[1]) {
2603                     final = getX(batch, xR, xCOffset, d1);
2604                   }
2605                   xC${v+1} = vec4(xTexelC${v+1}.xy, final.xy);
2606                 `)):(d+=`
2607                 if(xC >= 0 && xC < inDims[1] && xTexelC${v}Ready == 0) {
2608                   xTexelC${v} = getX(batch, xR, xC, d1);
2609                   if (xC + 1 >= inDims[1]) {
2610                     xTexelC${v}.zw = vec2(0.0);
2611                   }
2612                   xTexelC${v}Ready = 1;
2613                 }
2614
2615                 xCOffset = xC + strides[1];
2616                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) {
2617                   xTexelC${v+1} = getX(batch, xR, xCOffset, d1);
2618                   if (xCOffset + 1 >= inDims[1]) {
2619                     xTexelC${v+1}.zw = vec2(0.);
2620                   }
2621                   xTexelC${v+1}Ready = 1;
2622                 }
2623
2624                 xC${v} = vec4(
2625                   xTexelC${v}.xy, xTexelC${v+1}.xy);
2626               `,v+1<c&&(d+=`
2627                   xC${v+1} = vec4(xTexelC${v}.zw, xTexelC${v+1}.zw);
2628                 `)));v<c&&(d+=`
2629             wTexel = getW(r, ${v}, d1, d2);
2630             dotProd += xC${v}.xxzz * vec4(wTexel.xy, wTexel.xy);
2631             if(d1 + 1 < ${e.inChannels}) {
2632               dotProd += xC${v}.yyww * vec4(wTexel.zw, wTexel.zw);
2633             }
2634           `,v+1<c&&(d+=`
2635               wTexel = getW(r, ${v+1}, d1, d2);
2636               dotProd += xC${v+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
2637               if(d1 + 1 < ${e.inChannels}) {
2638                 dotProd += xC${v+1}.yyww * vec4(wTexel.zw, wTexel.zw);
2639               }
2640             `))}d+=`
2641     }
2642   `,d+=`
2643     }
2644   `,d+=`
2645     }
2646   `;let m="",g="";r&&(m=s?`vec4 activation(vec4 a) {
2647           vec4 b = getPreluActivationWeightsAtOutCoords();
2648           ${r}
2649         }`:a?`vec4 activation(vec4 a) {
2650           vec4 b = getLeakyreluAlphaAtOutCoords();
2651           ${r}
2652         }`:`vec4 activation(vec4 x) {
2653           ${r}
2654         }`,g="result = activation(result);");const y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2655       ${m}
2656
2657       void main() {
2658         ivec4 coords = getOutputCoords();
2659         int batch = coords.x;
2660         ivec2 xRCCorner = coords.yz * strides - pads;
2661         int d2 = coords.w;
2662         int xRCorner = xRCCorner.x;
2663         int xCCorner = xRCCorner.y;
2664
2665         //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
2666         vec4 dotProd = vec4(0.000000000000001);
2667
2668         ${d}
2669
2670         vec4 result = dotProd - vec4(0.000000000000001);
2671         ${y}
2672         ${g}
2673         setOutput(result);
2674       }
2675     `}}class rL{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Ds(this.outputShape.length);const{dataFormat:r}=t,s=Ks(),a=r==="channelsLast",i=a?1:2,o=a?2:3,l=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let p="";for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)p+=`
2676          blockIndex = rc.z + ${h};
2677          pos = rc.y + ${c};
2678
2679          ${l}
2680            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
2681            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
2682
2683            if(d0 < inputShape[${i}] && d0 >= 0) {
2684              // Use custom imod instead mod. On Intel GPU, mod may generate
2685              // unexpected value.
2686              // https://github.com/tensorflow/tfjs/issues/5447
2687              offsetX = imod(blockIndex, outWidth) * stride[1] - pad[
26871];
2688              d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
2689                  inChannels);
2690
2691              if(d1 < inputShape[${o}] && d1 >= 0) {
2692
2693                ch = imod(pos, inChannels);
2694
2695                if (${a}) {
2696                  innerDims = vec2(d1, ch);
2697                  result[${2*c+h}] = getChannel(
2698                    getA(rc.x, d0, int(innerDims.x),
2699                    int(innerDims.y)), innerDims);
2700                } else {
2701                  innerDims = vec2(d0, d1);
2702                  result[${2*c+h}] = getChannel(
2703                    getA(rc.x, ch, int(innerDims.x),
2704                    int(innerDims.y)), innerDims);
2705                }
2706              }
2707            }
2708          }
2709        `;this.userCode=`
2710      void main() {
2711        ivec3 rc = getOutputCoords();
2712
2713        vec4 result = vec4(0);
2714
2715        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
2716        vec2 innerDims;
2717
2718        ${p}
2719
2720        ${s.output} = result;
2721      }
2722    `}}function wy(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 DS({x:n,filter:e,convInfo:t,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=n.shape,p=r.texData.get(n.dataId),c=t.inChannels,h=l[0]*l[1]*l[2],d=t.outChannels,m=t.dataFormat==="channelsLast",g=!1;let y;const w=[];if(a!=null){const v=wy(a.shape,m);v!=null&&(a=It({inputs:{x:a},backend:r,attrs:{shape:v}}),w.push(a))}if(s!=null){const v=wy(s.shape,m);v!=null&&(s=It({inputs:{x:s},backend:r,attrs:{shape:v}}),w.push(s))}if((h!==1&&d!==1||!(c>1e3))&&p.isPacked&&m&&p.texture!=null&&l[2]%2!=0&&le(p.shape.slice(-3),l.slice(-3))){const v=l[0]*l[1]*(l[2]+1),N={dataId:n.dataId,shape:[1,v,t.inChannels],dtype:n.dtype},T=p.shape;p.shape=p.shape.slice(),p.shape[p.shape.length-2]++,A(Wf(p.shape,N.shape),()=>`packed reshape ${p.shape} to ${N.shape} isn't free`);const $=It({inputs:{x:e},backend:r,attrs:{shape:[1,t.inChannels,t.outChannels]}});w.push($);const _=yy({a:N,b:$,backend:r,transposeA:!1,transposeB:g,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),L=r.texData.get(_.dataId);A(L.isPacked,()=>"batchMatMul result is expected to be packed"),p.shape=T,L.shape=t.outShape,y=Ra({inputs:{x:_},backend:r}),y.shape=t.outShape,w.push(_)}else{const v=t.outHeight*t.outWidth,N=It({inputs:{x:n},backend:r,attrs:{shape:m?[t.batchSize,v,t.inChannels]:[t.batchSize,t.inChannels,v]}}),T=It({inputs:{x:e},backend:r,attrs:{shape:[1,t.inChannels,t.outChannels]}}),$=yy({a:m?N:T,b:m?T:N,transposeA:!m,transposeB:g,backend:r,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i});y=It({inputs:{x:$},backend:r,attrs:{shape:t.outShape}}),w.push(N),w.push(T),w.push($)}for(const v of w)r.disposeIntermediateTensorInfo(v);return y}function FS({x:n,filter:e,convInfo:t,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:l,filterHeight:p,inChannels:c,outWidth:h,outHeight:d,dataFormat:m}=t,g=m==="channelsLast",y=l*p*c,w=d*h,v=[t.batchSize,y,w],N=[];if(a!=null){const we=wy(a.shape,g);we!=null&&(a=It({inputs:{x:a},backend:r,attrs:{shape:we}}),N.push(a))}if(s!=null){const we=wy(s.shape,g);we!=null&&(s=It({inputs:{x:s},backend:r,attrs:{shape:we}}),N.push(s))}const T=It({inputs:{x:e},backend:r,attrs:{shape:[1,y,j(e.shape)/y]}});N.push(T);const $=new rL(v,t),_=[n.shape,[t.padInfo.top,t.padInfo.left],[t.strideHeight,t.strideWidth],[t.dilationHeight,t.dilationWidth],[t.inChannels],[t.filterWidth*t.inChannels],[t.outWidth]],L=r.runWebGLProgram($,[n],"float32",_),z=It({inputs:{x:L},backend:r,attrs:{shape:v}});N.push(L),N.push(z);const O=s!=null,V=a!=null,U=o==="leakyrelu",X=o?jf(o,!0):null,ne=new bS(g?z.shape:T.shape,g?T.shape:z.shape,g?[t.batchSize,w,t.outChannels]:[t.batchSize,t.outChannels,w],!0,!1,O,X,V,U),ae=g?[z,T]:[T,z];if(s&&ae.push(s),V&&ae.push(a),U){const we=r.makeTensorInfo([],"float32",Bn(i,"float32"));ae.push(we),N.push(we)}const Ie=r.runWebGLProgram(ne,ae,"float32"),me=It({inputs:{x:Ie},backend:r,attrs:{shape:t.outShape}});N.push(Ie);for(const we of N)r.disposeIntermediateTensorInfo(we);return me}const sL={kernelName:ds,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dataFormat:l,dilations:p,dimRoundingMode:c}=r,h=Du(l),d=is(s.shape,a.shape,i,p,o,c,!1,h);let m;if(d.filterHeight!==1||d.filterWidth!==1||d.dilationHeight!==1||d.dilationWidth!==1||d.strideHeight!==1||d.strideWidth!==1||d.padInfo.type!=="SAME"&&d.padInfo.type!=="VALID")if(d.strideWidth<=2&&h==="channelsLast"&&xe().getBool("WEBGL_EXP_CONV")){const y=new _S(d),w=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth
vendor: 15,866 bytes, lines 2722-3069
2722]];m=t.runWebGLProgram(y,[s,a],"float32",w)}else if(xe().getBool("WEBGL_CONV_IM2COL"))m=FS({x:s,filter:a,convInfo:d,backend:t});else{const y=new RS(d);m=t.runWebGLProgram(y,[s,a],"float32")}else m=DS({x:s,filter:a,convInfo:d,backend:t});const g=It({inputs:{x:m},backend:t,attrs:{shape:d.outShape}});return t.disposeIntermediateTensorInfo(m),g}};class aL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,r=e.strideWidth,s=e.padInfo.top,a=e.padInfo.left,i=e.dataFormat==="channelsLast";this.userCode=`
2723      void main() {
2724        ivec4 coords = getOutputCoords();
2725        int wR = coords.x;
2726        int wC = coords.y;
2727        int d1 = coords.z;
2728        int d2 = coords.w;
2729
2730        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
2731        // ? = to be determined. : = across all values in that axis.
2732        float dotProd = 0.0;
2733
2734        for (int b = 0; b < ${e.batchSize}; b++) {
2735          for (int yR = 0; yR < ${e.outHeight}; yR++) {
2736            int xR = wR + yR * ${t} - ${s};
2737
2738            if (xR < 0 || xR >= ${e.inHeight}) {
2739              continue;
2740            }
2741
2742            for (int yC = 0; yC < ${e.outWidth}; yC++) {
2743              int xC = wC + yC * ${r} - ${a};
2744
2745              if (xC < 0 || xC >= ${e.inWidth}) {
2746                continue;
2747              }
2748
2749              ${i?`float dyValue = getDy(b, yR, yC, d2);
2750              float xValue = getX(b, xR, xC, d1);
2751              dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
2752              float xValue = getX(b, d1, xR, xC);
2753              dotProd += (xValue * dyValue);`}
2754            }
2755          }
2756        }
2757        setOutput(dotProd);
2758      }
2759    `}}class iL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,r=e.filterWidth,s=e.strideHeight,a=e.strideWidth,i=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,l=r-1-e.padInfo.left,p=i?1:2,c=i?2:3,h=i?3:1;this.userCode=`
2760      const ivec2 pads = ivec2(${o}, ${l});
2761
2762      void main() {
2763        ivec4 coords = getOutputCoords();
2764        int batch = coords[0];
2765        int d1 = coords[${h}];
2766
2767        ivec2 dyCorner = ivec2(coords[${p}], coords[${c}]) - pads;
2768        int dyRCorner = dyCorner.x;
2769        int dyCCorner = dyCorner.y;
2770
2771        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
2772        // ? = to be determined. : = across all values in that axis.
2773        float dotProd = 0.0;
2774        for (int wR = 0; wR < ${t}; wR++) {
2775          float dyR = float(dyRCorner + wR) / ${s}.0;
2776
2777          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2778            continue;
2779          }
2780          int idyR = int(dyR);
2781
2782          int wRPerm = ${t} - 1 - wR;
2783
2784          for (int wC = 0; wC < ${r}; wC++) {
2785            float dyC = float(dyCCorner + wC) / ${a}.0;
2786
2787            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2788                fract(dyC) > 0.0) {
2789              continue;
2790            }
2791            int idyC = int(dyC);
2792
2793            int wCPerm = ${r} - 1 - wC;
2794
2795            for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2796
2797              if (${i}) {
2798                float xValue = getDy(batch, idyR, idyC, d2);
2799                float wValue = getW(wRPerm, wCPerm, d1, d2);
2800                dotProd += xValue * wValue;
2801              } else {
2802                float xValue = getDy(batch, d2, idyR, idyC);
2803                float wValue = getW(wRPerm, wCPerm, d1, d2);
2804                dotProd += xValue * wValue;
2805              }
2806
2807            }
2808          }
2809        }
2810        setOutput(dotProd);
2811      }
2812    `}}class oL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,r=e.strideHeight,s=e.strideWidth,a=e.padInfo.front,i=e.padInfo.top,o=e.padInfo.left;this.userCode=`
2813      void main() {
2814        ivec5 coords = getOutputCoords();
2815        int wF = coords.x;
2816        int wR = coords.y;
2817        int wC = coords.z;
2818        int d1 = coords.w;
2819        int d2 = coords.u;
2820
2821        float dotProd = 0.0;
2822
2823        for (int b = 0; b < ${e.batchSize}; b++) {
2824          for (int yF = 0; yF < ${e.outDepth}; yF++) {
2825            int xF = wF + yF * ${t} - ${a};
2826
2827            if (xF < 0 || xF >= ${e.inDepth}) {
2828              continue;
2829            }
2830
2831            for (int yR = 0; yR < ${e.outHeight}; yR++) {
2832              int xR = wR + yR * ${r} - ${i};
2833
2834              if (xR < 0 || xR >= ${e.inHeight}) {
2835                continue;
2836              }
2837
2838              for (int yC = 0; yC < ${e.outWidth}; yC++) {
2839                int xC = wC + yC * ${s} - ${o};
2840
2841                if (xC < 0 || xC >= ${e.inWidth}) {
2842                  continue;
2843                }
2844
2845                float dyValue = getDy(b, yF, yR, yC, d2);
2846                float xValue = getX(b, xF, xR, xC, d1);
2847                dotProd += (xValue * dyValue);
2848              }
2849            }
2850          }
2851        }
2852        setOutput(dotProd);
2853      }
2854    `}}class uL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,r=e.filterHeight,s=e.filterWidth,a=e.strideDepth,i=e.strideHeight,o=e.strideWidth,l=t-1-e.padInfo.front,p=r-1-e.padInfo.top,c=s-1-e.padInfo.left;this.userCode=`
2855      const ivec3 pads = ivec3(${l}, ${p}, ${c});
2856
2857      void main() {
2858        ivec5 coords = getOutputCoords();
2859        int batch = coords.x;
2860        int d1 = coords.u;
2861
2862
2863        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
2864        int dyFCorner = dyCorner.x;
2865        int dyRCorner = dyCorner.y;
2866        int dyCCorner = dyCorner.z;
2867
2868        float dotProd = 0.0;
2869        for (int wF = 0; wF < ${t}; wF++) {
2870          float dyF = float(dyFCorner + wF) / ${a}.0;
2871
2872          if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
2873            continue;
2874          }
2875          int idyF = int(dyF);
2876
2877          int wFPerm = ${t} - 1 - wF;
2878
2879          for (int wR = 0; wR < ${r}; wR++) {
2880            float dyR = float(dyRCorner + wR) / ${i}.0;
2881
2882            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2883              fract(dyR) > 0.0) {
2884              continue;
2885            }
2886            int idyR = int(dyR);
2887
2888            int wRPerm = ${r} - 1 - wR;
2889
2890            for (int wC = 0; wC < ${s}; wC++) {
2891              float dyC = float(dyCCorner + wC) / ${o}.0;
2892
2893              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2894                  fract(dyC) > 0.0) {
2895                continue;
2896              }
2897              int idyC = int(dyC);
2898
2899              int wCPerm = ${s} - 1 - wC;
2900
2901              for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2902                float xValue = getDy(batch, idyF, idyR, idyC, d2);
2903                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
2904                dotProd += xValue * wValue;
2905              }
2906            }
2907          }
2908        }
2909        setOutput(dotProd);
2910      }
2911    `}}const lL={kernelName:Gh,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,pad:o,dataFormat:l,dimRoundingMode:p,filterShape:c}=r,h=Du(l),d=is(s.shape,c,i,1,o,p,!1,h),m=new aL(d);return t.runWebGLProgram(m,[s,a],"float32")}};class cL{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=Ds(this.outputShape.length);const t=e.filterHeight,r=e.filterWidth,s=t-1-e.padInfo.top,a=r-1-e.padInfo.left;this.userCode=`
2912      const ivec2 pads = ivec2(${s}, ${a});
2913
2914      void main() {
2915        ivec4 coords = getOutputCoords();
2916        int batch = coords[0];
2917        int d1 = coords[3];
2918
2919        ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
2920        int dyRCorner = dyCorner.x;
2921        int dyCCorner = dyCorner.y;
2922
2923        vec4 result = vec4(0.);
2924        for (int wR = 0; wR < ${t}; wR++) {
2925          float dyR = float(dyRCorner + wR) / strides[0];
2926          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2927            continue;
2928          }
2929          int idyR = int(dyR);
2930          int wRPerm = ${t} - 1 - wR;
2931
2932          for (int wC = 0; wC < ${r}; wC++) {
2933            int wCPerm = ${r} - 1 - wC;
2934
2935            float dyC = float(dyCCorner + wC) / strides[1];
2936            bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
2937              && (fract(dyC) == 0.0);
2938            int idyC = int(dyC);
2939
2940            float dyC2 = float(dyCCorner + wC + 1) / strides[1];
2941            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
2942              && (fract(dyC2) == 0.0);
2943            int idyC2 = int(dyC2);
2944
2945            if (idyCVal && idyCVal2) {
2946              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2947                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
2948                vec4 dySample = getDy(batch, idyR, idyC, d2);
2949                vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
2950                  dySample : getDy(batch, idyR, idyC2, d2);
2951
2952                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
2953                  dySample.xy : dySample.zw;
2954                result.xy += vec2(dot(dyValue, wValue.xy),
2955                  dot(dyValue, wValue.zw));
2956
2957                dyValue = mod(float(idyC2), 2.) == 0. ?
2958                  dySample2.xy : dySample2.zw;
2959                result.zw += vec2(dot(dyValue, wValue.xy),
2960                  dot(dyValue, wValue.zw));
2961              }
2962            } else if (idyCVal) {
2963              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2964                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
2965                vec4 dySample = getDy(batch, idyR, idyC, d2);
2966                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
2967                  dySample.xy : dySample.zw;
2968                result.xy += vec2(dot(dyValue, wValue.xy),
2969                  dot(dyValue, wValue.zw));
2970              }
2971            } else if (idyCVal2) {
2972              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2973                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
2974                vec4 dySample = getDy(batch, idyR, idyC2, d2);
2975                vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
2976                  dySample.xy : dySample.zw;
2977                result.zw += vec2(dot(dyValue, wValue.xy),
2978                  dot(dyValue, wValue.zw));
2979              }
2980            }
2981          }
2982        }
2983        setOutput(result);
2984      }
2985    `}}const hL={kernelName:sl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{inputShape:i,strides:o,pad:l,dataFormat:p,dimRoundingMode:c}=r,h=Du(p),d=is(i,a.shape,o,1,l,c,!1,h);if(xe().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&h==="channelsLast"){const m=[[d.strideHeight,d.strideWidth]],g=new cL(d);return t.runWebGLProgram(g,[s,a],"float32",m)}{const m=new iL(d);return t.runWebGLProgram(m,[s,a],"float32")}}},dL={kernelName:kc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dilations:l}=r,p=Gl(s.shape,a.shape,i,l,o),c=new nL(p);return t.runWebGLProgram(c,[s,a],"float32")}},pL={kernelName:Hh,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,pad:o,filterShape:l}=r,p=Gl(s.shape,l,i,1,o),c=new oL(p);return t.runWebGLProgram(c,[s,a],"float32")}},fL={kernelName:Nc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{pad:i,strides:o,inputShape:l}=r,p=Gl(l,a.shape,o,1,i),c=new uL(p);return t.runWebGLProgram(c,[s,a],"float32")}},mL=Cn({opSnippet:cp+`
2986  return cos(x);
2987`,packedOpSnippet:`
2988  vec4 result = cos(x);
2989  bvec4 isNaN = isnan(x);
2990  ${Mh}
2991  return result;
2992`}),gL={kernelName:xo,backendName:"webgl",kernelFunc:mL},yL=Cn({opSnippet:`
2993  float e2x = exp(-x);
2994  return (e2x + 1.0 / e2x) / 2.0;
2995`}),bL={kernelName:Ii,backendName:"webgl",kernelFunc:yL};class xL{constructor(e,t,r,s,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[i,o,l,p]=e,[c]=t,[h,d]=r;this.outputShape=[c,h,d,p];const m=s==="bilinear"?1:0,[g,y]=[o-1+".0",l-1+".0"],[w,v,N]=h>1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio",`y1*${g} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${g}`],[T,$,_]=d>1?[""+(l-1)/(d-1),"(x2-x1) * width_ratio",`x1*${y} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${y}`];this.userCode=`
2996      const float height_ratio = float(${w});
2997      const float width_ratio = float(${T});
2998      void main() {
2999        ivec4 coords = getOutputCoords();
3000        int b = coords[0];
3001        int y = coords[1];
3002        int x = coords[2];
3003        int d = coords[3];
3004
3005        // get box vals
3006        float y1 = getBoxes(b,0);
3007        float x1 = getBoxes(b,1);
3008        float y2 = getBoxes(b,2);
3009        float x2 = getBoxes(b,3);
3010
3011        // get image in batch index
3012        int bInd = round(getBoxInd(b));
3013        if(bInd < 0 || bInd >= ${i}) {
3014          return;
3015        }
3016
3017        float height_scale = ${v};
3018        float width_scale = ${$};
3019
3020        float in_y = ${N};
3021        if( in_y < 0.0 || in_y > ${g} ) {
3022          setOutput(float(${a}));
3023          return;
3024        }
3025        float in_x = ${_};
3026        if( in_x < 0.0 || in_x > ${y} ) {
3027          setOutput(float(${a}));
3028          return;
3029        }
3030
3031        vec2 sourceFracIndexCR = vec2(in_x,in_y);
3032        if(${m} == 1) {
3033          // Compute the four integer indices.
3034          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
3035          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
3036
3037          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
3038          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
3039          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
3040          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
3041
3042          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
3043
3044          float top = topLeft + (topRight - topLeft) * fracCR.x;
3045          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
3046          float newValue = top + (bottom - top) * fracCR.y;
3047          setOutput(newValue);
3048        } else {
3049          // Compute the coordinators of nearest neighbor point.
3050          ivec2 sourceNearestCR = ivec2(floor(
3051            sourceFracIndexCR + vec2(0.5,0.5)));
3052          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
3053          setOutput(newValue);
3054        }
3055      }
3056    `}}const wL={kernelName:al,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{image:s,boxes:a,boxInd:i}=e,{cropSize:o,method:l,extrapolationValue:p}=r,c=new xL(s.shape,a.shape,o,l,p);return t.runWebGLProgram(c,[s,a,i],"float32")}};var Yf;(function(n){n.Prod="*",n.Sum="+"})(Yf||(Yf={}));class MS{constructor(e,t,r,s){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const a=this.outputShape.length,i=this.op===Yf.Prod?"1.0":"0.0",o=r?i:`getX(${OS(a,"coords",this.op)})`,l=this.outputShape[this.outputShape.length-1];let p="",c="";r?(p=s?"end != "+(l-1):"end != 0",c=s?"end + 1":"end - 1"):(p=s?`end + pow2 < ${l}`:"end >= pow2",c=s?"end + pow2":"end - pow2"),this.userCode=`
3057      void main() {
3058        ${Xn(a)} coords = getOutputCoords();
3059        int end = ${LS(a,"coords",this.op)};
3060        float val = ${o};
3061        int pow2 = int(pow(2.0, index));
3062        if (${p}) {
3063          int idx = ${c};
3064          ${LS(a,"coords",this.op)} = idx;
3065          val ${this.op}= getX(${OS(a,"coords",this.op)});
3066        }
3067        setOutput(val);
3068      }
3069    `}}function OS(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 new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function LS(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 new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function zS(n,e,t,r,s,a){const i=e.shape.length,o=Ir([r],i);let l=e;
3069o!=null&&(l=Xs({inputs:{x:e},backend:t,attrs:{perm:o}}));const p=Or(1,i)[0];if(p!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${r}`);const c=l.shape[p];let h=Ra({inputs:{x:l},backend:t});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){const m=new MS(n,l.shape,!1,a),g=[[d]],y=h;h=t.runWebGLProgram(m,[h],h.dtype,g),t.disposeIntermediateTensorInfo(y)}if(s){const d=new MS(n,l.shape,s,a),m=h;h=t.runWebGLProgram(d,[h],h.dtype),t.disposeIntermediateTensorInfo(m)}if(o!=null){const d=Xs({inputs:{x:h},backend:t,attrs:{perm:Kl(o)}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(l),d}return h}const vL={kernelName:jh,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:i,reverse:o}=r;return zS(Yf.Prod,s,t,a,i,o)}},kL={kernelName:nu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:i,reverse:o}=r;return zS(Yf.Sum,s,t,a,i,o)}},NL={kernelName:il,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:i,binaryOutput:o}=r;if(s.shape.length===1){const l=t.readSync(s.dataId),p=t.readSync(a.dataId),c=rS(l,p,a.dtype,a.shape,i);return t.makeTensorInfo([i],a.dtype,c)}if(s.shape.length===2){const l=t.bufferSync(s),p=t.bufferSync(a),c=WF(l,p,i,o);return t.makeTensorInfo(c.shape,a.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}};class IL{constructor(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,this.userCode=`
3070    void main() {
3071      ivec4 coords = getOutputCoords();
3072      int b = coords[0];
3073      int h = ${this.getHeightCoordString()};
3074      int w = ${this.getWidthCoordString()};
3075      int d = ${this.getDepthCoordString()};
3076
3077      int in_h = h / ${t};
3078      int offset_h = imod(h, ${t});
3079      int in_w = w / ${t};
3080      int offset_w = imod(w, ${t});
3081      int offset_d = (offset_h * ${t} + offset_w) *
3082        ${this.getOutputDepthSize()};
3083      int in_d = d + offset_d;
3084
3085      float result = ${this.getInputSamplingString()};
3086      setOutput(result);
3087    }
3088  `}
3088getHeightCoordString(){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"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const SL={kernelName:Ic,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockSize:a,dataFormat:i}=r,o=s.shape[0],l=(i==="NHWC"?s.shape[1]:s.shape[2])*a,p=(i==="NHWC"?s.shape[2]:s.shape[3])*a,c=(i==="NHWC"?s.shape[3]:s.shape[1])/(a*a),h=new IL(i==="NHWC"?[o,l,p,c]:[o,c,l,p],a,i);return t.runWebGLProgram(h,[s],s.dtype)}};class PS{constructor(e,t=!1,r=null,s=!1,a=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ds(this.outputShape.length);const i=e.filterHeight,o=e.filterWidth,l=e.outChannels/e.inChannels;let p="",c="";r&&(p=s?`float activation(float a) {
3089          float b = getPreluActivationWeightsAtOutCoords();
3090          ${r}
3091        }`:a?`float activation(float a) {
3092          float b = getLeakyreluAlphaAtOutCoords();
3093          ${r}
3094        }`:`
3095          float activation(float x) {
3096            ${r}
3097          }
3098        `,c="result = activation(result);");const h=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
3099      ${p}
3100
3101      void main() {
3102        ivec4 coords = getOutputCoords();
3103        int batch = coords.x;
3104        ivec2 xRCCorner = coords.yz * strides - pads;
3105        int d2 = coords.w;
3106        int d1 = d2 / ${l};
3107        int q = d2 - d1 * ${l};
3108
3109        int xRCorner = xRCCorner.x;
3110        int xCCorner = xRCCorner.y;
3111
3112        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
3113        // ? = to be determined. : = across all values in that axis.
3114        float dotProd = 0.0;
3115        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
3116        for (int wR = 0; wR < ${i}; wR++) {
3117          int xR = xRCorner + wR * dilations[0];
3118
3119          if (xR < 0 || xR >= inDims[0]) {
3120            continue;
3121          }
3122
3123          for (int wC = 0; wC < ${o}; wC++) {
3124            int xC = xCCorner + wC * dilations[1];
3125
3126            if (xC < 0 || xC >= inDims[1]) {
3127              continue;
3128            }
3129
3130            float xVal = getX(batch, xR, xC, d1);
3131            float wVal = getW(wR, wC, d1, q);
3132            dotProd += xVal * wVal;
3133          }
3134        }
3135
3136        float result = dotProd;
3137        ${h}
3138        ${c}
3139        setOutput(result);
3140      }
3141    `}}class BS{constructor(e,t=!1,r=null,s=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ds(this.outputShape.length);const i=e.outChannels/e.inChannels,o=e.padInfo.left,l=e.strideWidth,p=e.dilationWidth,c=e.filterHeight,h=e.filterWidth,d=h;let m=`
3142      int xR; int xC; int xCOffset;
3143      vec4 wTexel; vec4 previous; vec4 final;`;for(let v=0;v<h;v++)m+=`
3144          vec4 xTexelC${2*v};
3145          int xTexelC${2*v}Ready;
3146          vec4 xTexelC${2*v+1};
3147          int xTexelC${2*v+1}Ready;
3148          vec4 xC${v};`;m+=`
3149    for (int r = 0; r < ${c}; r++) {
3150      `;for(let v=0;v<h;v++)m+=`
3151          xTexelC${2*v} = vec4(0.0);
3152          xTexelC${2*v}Ready = 0;
3153          xTexelC${2*v+1} = vec4(0.0);
3154          xTexelC${2*v+1}Ready = 0;
3155          xC${v} = vec4(0.0);`;m+=`
3156        xR = xRCorner + r * dilations[0];
3157        if (xR >=0 && xR < inDims[0]) {
3158      `;for(let v=0;v<(d+1)/2;v++){const N=2*v;if(m+=`
3159          xC = xCCorner + ${N*p};
3160          `,l===1){if(N<h&&(o%2==1?(m+=`
3161                xCOffset = xC + 1;
3162                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${N}Ready == 0) {
3163                  xTexelC${N} = getX(batch, xR, xCOffset, d1);
3164
3165                  // Need to manually clear unused channels in case
3166                  // we're reading from recycled texture.
3167                  if (xCOffset + 1 >= inDims[1]) {
3168                    xTexelC${N}.zw = vec2(0.0);
3169                  }
3170                  xTexelC${N}Ready = 1;
3171                }
3172              `,m+=p===1&&N>0?`
3173                xC${N} = vec4(xTexelC${N-2}.zw, xTexelC${N}.xy);
3174                `:`
3175                  xCOffset = xC + 1 - 2;
3176
3177                  if (xCOffset >= 0 && xCOffset < inDims[1]) {
3178                    previous = getX(batch, xR, xCOffset, d1);
3179
3180                    // Need to manually clear unused channels in case
3181                    // we're reading from recycled texture.
3182                    if (xCOffset + 1 >= inDims[1]) {
3183                      previous.zw = vec2(0.0);
3184                    }
3185
3186                    xC${N} = vec4(previous.zw, xTexelC${N}.xy);
3187                  } else {
3188                    xC${N} = vec4(0.0, 0.0, xTexelC${N}.xy);
3189                  }
3190                  `):m+=`
3191                if (xC >= 0 && xC < inDims[1] && xTexelC${N}Ready == 0) {
3192                  xTexelC${N} = getX(batch, xR, xC, d1);
3193                  if (xC + 1 >= inDims[1]) {
3194                    xTexelC${N}.zw = vec2(0.0);
3195                  }
3196                  xTexelC${N}Ready = 1;
3197                }
3198
3199                xC${N} = xTexelC${N};
3200                `,N+1<h)){const T=o%2==0?Ce(p):p;p%2==0&&o%2==1||p%2!=0&&o%2!=1?(m+=`
3201                  xCOffset = xC + imod(pads[1], 2) + ${T};
3202
3203                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${N+1}Ready == 0) {
3204                    xTexelC${N+1} = getX(batch, xR, xCOffset, d1);
3205
3206                    // Need to manually clear unused channels in case
3207                    // we're reading from recycled texture.
3208                    if (xCOffset + 1 >= inDims[1]) {
3209                      xTexelC${N+1}.zw = vec2(0.0);
3210                    }
3211                    xTexelC${N+1}Ready = 1;
3212                  }
3213                  `,m+=p>1?`
3214                    xCOffset -= 2;
3215                    if (xCOffset >= 0 && xCOffset < inDims[1]) {
3216                     previous = getX(batch, xR, xCOffset, d1);
3217                     xC${N+1} = vec4(previous.zw, xTexelC${N+1}.xy);
3218                    } else {
3219                     xC${N+1} = vec4(0.0, 0.0, xTexelC${N+1}.xy);
3220                    }
3221                    `:`
3222                    xC${N+1} = vec4(xTexelC${N}.zw, xTexelC${N+1}.xy);
3223                    `):m+=T===1?`
3224                    xC${N+1} = xTexelC${N};
3225                    `:`
3226                    xCOffset = xC + ${T};
3227
3228                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${N+1}Ready == 0) {
3229                      xTexelC${N+1} = getX(batch, xR, xCOffset, d1);
3230                      if (xCOffset + 1 >= inDims[1]) {
3231                        xTexelC${N+1}.zw = vec2(0.0);
3232                      }
3233                      xTexelC${N+1}Ready = 1;
3234                    }
3235
3236                    xC${N+1} = xTexelC${N+1};
3237                    `}}else N<h&&(o%2==1?(m+=`
3238                xCOffset = xC + 1 - strides[1];
3239                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${N}Ready == 0) {
3240                  xTexelC${N} = getX(batch, xR, xCOffset, d1);
3241                  // Need to manually clear unused channels in case
3242                  // we're reading from recycled texture.
3243                  if (xCOffset + 1 >= inDims[1]) {
3244                    xTexelC${N}.zw = vec2(0.0);
3245                  }
3246                  xTexelC${N}Ready = 1;
3247                }
3248
3249                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${N+1}Ready == 0) {
3250                  xTexelC${N+1} = getX(batch, xR, xC + 1, d1);
3251                  // Need to manually clear unused channels in case
3252                  // we're reading from recycled texture.
3253                  if (xC + 2 >= inDims[1]) {
3254                    xTexelC${N+1}.zw = vec2(0.0);
3255                  }
3256                  xTexelC${N+1}Ready = 1;
3257                }
3258
3259                xC${N} = vec4(xTexelC${N}.zw, xTexelC${N+1}.zw);
3260              `,N+1<h&&(m+=`
3261                  final = vec4(0.0);
3262                  xCOffset = xC + 1 + strides[1];
3263                  if(xCOffset >= 0 && xCOffset < inDims[1]) {
3264                    final = getX(batch, xR, xCOffset, d1);
3265                  }
3266                  xC${N+1} = vec4(xTexelC${N+1}.xy, final.xy);
3267                `)):(m+=`
3268                if(xC >= 0 && xC < inDims[1] && xTexelC${N}Ready == 0) {
3269                  xTexelC${N} = getX(batch, xR, xC, d1);
3270                  if (xC + 1 >= inDims[1]) {
3271                    xTexelC${N}.zw = vec2(0.0);
3272                  }
3273                  xTexelC${N}Ready = 1;
3274                }
3275
3276                xCOffset = xC + strides[1];
3277                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${N+1}Ready == 0) {
3278                  xTexelC${N+1} = getX(batch, xR, xCOffset, d1);
3279                  if (xCOffset + 1 >= inDims[1]) {
3280                    xTexelC${N+1}.zw = vec2(0.);
3281                  }
3282                  xTexelC${N+1}Ready = 1;
3283                }
3284
3285                xC${N} = vec4(
3286                  xTexelC${N}.xy, xTexelC${N+1}.xy);
3287              `,N+1<h&&(m+=`
3288                  xC${N+1} = vec4(xTexelC${N}.zw, xTexelC${N+1}.zw);
3289                `)));N<h&&(m+=`
3290            wTexel = getW(r, ${N}, d1, q);
3291            dotProd += xC${N} * vec4(wTexel.xz, wTexel.xz);
3292          `,N+1<h&&(m+=`
3293              wTexel = getW(r, ${N+1}, d1, q);
3294              dotProd += xC${N+1} * vec4(wTexel.xz, wTexel.xz);
3295            `))}m+=`
3296    }
3297  `,m+=`
3298      }
3299    `;let g="",y="";r&&(g=s?`vec4 activation(vec4 a) {
3300          vec4 b = getPreluActivationWeightsAtOutCoords();
3301          ${r}
3302        }`:a?`vec4 activation(vec4 a) {
3303          vec4 b = getLeakyreluAlphaAtOutCoords();
3304          ${r}
3305        }`:`vec4 activation(vec4 x) {
3306          ${r}
3307        }`,y="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
3308      ${g}
3309
3310      void main() {
3311        ivec4 coords = getOutputCoords();
3312        int batch = coords.x;
3313        ivec2 xRCCorner = coords.yz * strides - pads;
3314        int d2 = coords.w;
3315        int d1 = d2 / ${i};
3316        int q = d2 - d1 * ${i};
3317        int xRCorner = xRCCorner.x;
3318        int xCCorner = xRCCorner.y;
3319
3320        //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
3321        vec4 dotProd = vec4(0.000000000000001);
3322
3323        ${m}
3324
3325        vec4 result = dotProd - vec4(0.000000000000001);
3326        ${w}
3327        ${y}
3328        setOutput(result);
3329      }
3330    `}}const TL={kernelName:wo,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dilations:l,dimRoundingMode:p}=r;let c=l;c==null&&(c=[1,1]),A(bs(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);const h=is(s.shape,a.shape,i,c,o,p,!0);let d;d=xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?new BS(h):new PS(h);const m=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth
vendor: 5,865 bytes, lines 3330-3454
3330]];return t.runWebGLProgram(d,[s,a],"float32",m)}};class EL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,r=e.strideWidth,s=e.padInfo.top,a=e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
3331      void main() {
3332        ivec4 coords = getOutputCoords();
3333        int wR = coords.x;
3334        int wC = coords.y;
3335        int d1 = coords.z;
3336        int dm = coords.w;
3337        int d2 = d1 * ${i} + dm;
3338
3339        float dotProd = 0.0;
3340
3341        // TO DO: Vec4 over the batch size
3342        for (int b = 0; b < ${e.batchSize}; b++) {
3343          for (int yR = 0; yR < ${e.outHeight}; yR++) {
3344            int xR = wR + yR * ${t} - ${s};
3345
3346            if (xR < 0 || xR >= ${e.inHeight}) {
3347              continue;
3348            }
3349
3350            for (int yC = 0; yC < ${e.outWidth}; yC++) {
3351              int xC = wC + yC * ${r} - ${a};
3352
3353              if (xC < 0 || xC >= ${e.inWidth}) {
3354                continue;
3355              }
3356
3357              float dyValue = getDy(b, yR, yC, d2);
3358              float xValue = getX(b, xR, xC, d1);
3359              dotProd += (xValue * dyValue);
3360            }
3361          }
3362        }
3363        setOutput(dotProd);
3364      }
3365    `}}class CL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,r=e.filterWidth,s=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=r-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode=`
3366      const ivec2 pads = ivec2(${i}, ${o});
3367
3368      void main() {
3369        ivec4 coords = getOutputCoords();
3370        int batch = coords[0];
3371        int d1 = coords[3];
3372        ivec2 dyCorner = coords.yz - pads;
3373        int dyRCorner = dyCorner.x;
3374        int dyCCorner = dyCorner.y;
3375
3376        float dotProd = 0.0;
3377
3378        for (int wR = 0; wR < ${t}; wR++) {
3379          float dyR = float(dyRCorner + wR) / ${s}.0;
3380
3381          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
3382            continue;
3383          }
3384          int idyR = int(dyR);
3385
3386          int wRPerm = ${t} - 1 - wR;
3387
3388          for (int wC = 0; wC < ${r}; wC++) {
3389            float dyC = float(dyCCorner + wC) / ${a}.0;
3390
3391            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
3392                fract(dyC) > 0.0) {
3393              continue;
3394            }
3395            int idyC = int(dyC);
3396
3397            int wCPerm = ${r} - 1 - wC;
3398
3399            // TO DO: Vec4 over the channelMul
3400            for (int dm = 0; dm < ${l}; dm++) {
3401              int d2 = d1 * ${l} + dm;
3402              float xValue = getDy(batch, idyR, idyC, d2);
3403              float wValue = getW(wRPerm, wCPerm, d1, dm);
3404              dotProd += xValue * wValue;
3405            }
3406          }
3407        }
3408        setOutput(dotProd);
3409      }
3410    `}}const $L={kernelName:Sc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:i,dilations:o,pad:l,dimRoundingMode:p,filterShape:c}=r,h=is(s.shape,c,i,o,l,p,!0),d=new EL(h);return t.runWebGLProgram(d,[s,a],"float32")}},AL={kernelName:Fa,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{strides:i,dilations:o,pad:l,dimRoundingMode:p,inputShape:c}=r,h=is(c,a.shape,i,o,l,p,!0),d=new CL(h);return t.runWebGLProgram(d,[s,a],"float32")}};class RL{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
3411      void main() {
3412          ivec2 coords = getOutputCoords();
3413          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
3414          setOutput(val);
3415      }
3416    `}}const _L={kernelName:Tc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e,s=[...r.shape,...r.shape],a=j(r.shape),i=It({inputs:{x:r},backend:t,attrs:{shape:[a]}}),o=new RL(a),l=t.runWebGLProgram(o,[i],i.dtype),p=It({inputs:{x:l},backend:t,attrs:{shape:s}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),p}};class DL{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:r,padInfo:s,strideHeight:a,strideWidth:i,filterHeight:o,filterWidth:l,dilationHeight:p,dilationWidth:c}=e,{top:h,left:d}=s;this.userCode=`
3417      const ivec2 strides = ivec2(${a}, ${i});
3418      const ivec2 pads = ivec2(${h}, ${d});
3419      const float neg_infinity = -3.4e38;
3420
3421      void main() {
3422        ivec4 coords = getOutputCoords();
3423        int batch = coords.x;
3424        int d1 = coords.w;
3425        ivec2 outTopLeftCorner =
3426            coords.yz * strides - pads;
3427        int hBeg = outTopLeftCorner.x;
3428        int wBeg = outTopLeftCorner.y;
3429
3430        float curVal = neg_infinity;
3431        for (int h = 0; h < ${o}; h++) {
3432          int hIn = hBeg + h * ${p};
3433
3434          if (hIn >= 0 && hIn < ${t}) {
3435            for (int w = 0; w < ${l}; w++) {
3436              int wIn = wBeg + w * ${c};
3437
3438              if (wIn >= 0 && wIn < ${r}) {
3439                float xVal = getX(batch, hIn, wIn, d1);
3440                float wVal = getW(h, w, d1);
3441
3442                float val = xVal + wVal;
3443                if (val > curVal) {
3444                  curVal = val;
3445                }
3446              }
3447            }
3448          }
3449        }
3450
3451        float result = curVal;
3452        setOutput(result);
3453      }
3454    `}}const FL={kernelName:Ms,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:i,pad:o,dilations:l}=r,p=jp(s.shape,a.shape,i,o,"NHWC",l);let c;const h=new DL(p);c=t.runWebGLProgram(h,[s,a],"float32");const d=It({inputs:{x:c},backend:t,attrs:{shape:p.outShape}});return t.disposeIntermediateTensorInfo(c),d}},ML={kernelName:Ec,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{equation:s}=r,a=e,{allDims:i,summedDims:o,idDims:l}=Q0(s,a.length);e1(i.length,l,a);const{path:p,steps:c}=t1(o,l),h=c.length;let d=null,m=i.length;const g=[];for(let y=0;y<h;++y){for(const w of c[y]){const{permutationIndices:v,expandDims:N}=J0(m,l[w]);let T;
vendor: 1,037 bytes, lines 3454-3464
3454n1(v)?T=a[w]:(T=Xs({inputs:{x:a[w]},backend:t,attrs:{perm:v}}),g.push(T));const $=T.shape.slice();for(let _=0;_<N.length;++_)$.splice(N[_],0,1);le(T.shape,$)||(T=It({inputs:{x:T},backend:t,attrs:{shape:$}}),g.push(T)),d===null?d=T:(d=Vx({inputs:{a:T,b:d},backend:t}),g.push(d))}y<h-1&&(p[y]>=0&&(d=gy({inputs:{x:d},backend:t,attrs:{axis:p[y]-(i.length-m),keepDims:!1}}),g.push(d)),m--)}for(const y of g)y!==d&&t.disposeIntermediateTensorInfo(y);return d}},OL=Cn({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:`
3455  vec4 result;
3456
3457  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
3458  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
3459  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
3460  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
3461
3462  return result;
3463`}),LL={kernelName:fa,backendName:"webgl",kernelFunc:OL},zL={kernelName:Qa,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t}=n,{dy:r,y:s}=e,a=xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lp(`
3464  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
3465  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
3466`,r.shape,s.shape):new Fh("return (b >= 0.0) ? a : a * (b + 1.0);",r.shape,s.shape);return t.runWebGLProgram(a,[r,s],r.dtype)}},PL=Is({opSnippet:"return float(a == b);",packedOpSnippet:`
3467  return vec4(equal(a, b));
3468`,dtype:"bool",cpuKernelImpl:qF}),BL={kernelName:ol,backendName:"webgl",kernelFunc:PL},VL=Cn({opSnippet:`
3469  // Error function is calculated approximately with elementary function.
3470  // See "Handbook of Mathematical Functions with Formulas,
3471  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
3472  float p = ${G0};
3473  float a1 = ${H0};
3474  float a2 = ${j0};
3475  float a3 = ${K0};
3476  float a4 = ${q0};
3477  float a5 = ${X0};
3478
3479  float sign = sign(x);
3480  x = abs(x);
3481  float t = 1.0 / (1.0 + p * x);
3482  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
3483`}),UL={kernelName:ru,backendName:"webgl",kernelFunc:VL},VS=Cn({opSnippet:cp+`
3484  return exp(x);
3485`,packedOpSnippet:`
3486  vec4 result = exp(x);
3487  bvec4 isNaN = isnan(x);
3488  result.r = isNaN.r ? x.r : result.r;
3489  result.g = isNaN.g ? x.g : result.g;
3490  result.b = isNaN.b ? x.b : result.b;
3491  result.a = isNaN.a ? x.a : result.a;
3492
3493  return result;
3494`,cpuKernelImpl:XF,dtype:"float32"}),WL={kernelName:Os,backendName:"webgl",kernelFunc:VS};function Gx(n){const{inputs:e,attrs:t,backend:r}=n,{dim:s}=t,{input:a}=e,i=a.shape.length,o=a.shape.slice();let l=s;return s<0&&(A(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),It({inputs:{x:a},backend:r,attrs:{shape:o}})}const GL={kernelName:ul,backendName:"webgl",kernelFunc:Gx},US="return exp(x) - 1.0;",HL=Cn({opSnippet:US,packedOpSnippet:US,cpuKernelImpl:YF}),jL={kernelName:vo,backendName:"webgl",kernelFunc:HL};class WS{constructor(e,t,r){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const a=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=r?`${s}.0`:"1.0";let o;if(e==="real")o="return real * expR - imag * expI;";else{if(e!=="imag")throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);o="return real * expI + imag * expR;"}this.userCode=`
3495      const float exponentMultiplier = ${a};
3496
3497      float unaryOpComplex(float real, float expR, float imag, float expI) {
3498        ${o}
3499      }
3500
3501      float mulMatDFT(int batch, int index) {
3502        float indexRatio = float(index) / float(${s});
3503        float exponentMultiplierTimesIndexRatio =
3504            exponentMultiplier * indexRatio;
3505
3506        float result = 0.0;
3507
3508        for (int i = 0; i < ${s}; i++) {
3509          // x = (-2|2 * PI / N) * index * i;
3510          float x = exponentMultiplierTimesIndexRatio * float(i);
3511          float expR = cos(x);
3512          float expI = sin(x);
3513          float real = getReal(batch, i);
3514          float imag = getImag(batch, i);
3515
3516          result +=
3517              unaryOpComplex(real, expR, imag, expI) / ${i};
3518        }
3519
3520        return result;
3521      }
3522
3523      void main() {
3524        ivec2 coords = getOutputCoords();
3525        setOutput(mulMatDFT(coords[0], coords[1]));
3526      }
3527    `}}function GS(n,e,t){const r=t.texData.get(n.dataId),s=j(n.shape),a=n.shape[n.shape.length-1],i=It({inputs:{x:n},backend:t,attrs:{shape:[s/a,a]}}),o=i.shape,l=new WS("real",o,e),p=new WS("imag",o,e),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:o},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:o}],h=t.runWebGLProgram(l,c,"float32"),d=t.runWebGLProgram(p,c,"float32"),m=pc({inputs:{real:h,imag:d},backend:t});t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d);const g=It({inputs:{x:m},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(m),g}const KL={kernelName:ll,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{input:r}=e;return GS(r,!1,t)}};class qL{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
3528      void main() {
3529        // Input can be obtained from uniform value.
3530        setOutput(value);
3531      }
3532    `}}function Zf(n){const{backend:e,attrs:t}=n,{shape:r,value:s}=t;let{dtype:a}=t;if(a=a||St(s),a==="string"){const i=Zt(a,j(r));return i.fill(s),e.makeTensorInfo(r,a,i)}{const i=new qL(r,s),o=[[s]];return e.runWebGLProgram(i,[],a,o)}}const XL={kernelName:cl,backendName:"webgl",kernelFunc:Zf};class YL{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
3533        void main() {
3534          ivec4 coords = getOutputCoords();
3535          int x = coords[2];
3536
3537          int coordX = ${t} - x - 1;
3538          float outputValue;
3539          if(coordX >= 0 && coordX < ${t}) {
3540            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
3541          } else {
3542            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
3543          }
3544          setOutput(outputValue);
3545        }
3546    `}}
3546const ZL={kernelName:Cc,backendName:"webgl",kernelFunc:({inputs:n,backend:e})=>{const{image:t}=n,r=e,s=new YL(t.shape);return r.runWebGLProgram(s,[t],t.dtype)}},HS="return floor(x);",QL=Cn({opSnippet:HS,packedOpSnippet:HS,cpuKernelImpl:ZF}),JL={kernelName:ko,backendName:"webgl",kernelFunc:QL},ez=Is({opSnippet:`
3547  float s = sign(a) * sign(b);
3548  int ia = round(a);
3549  int ib = round(b);
3550  if (ib != 0) {
3551    // Windows (D3D) wants guaranteed non-zero int division at compile-time.
3552    return float(idiv(ia, ib, s));
3553  } else {
3554    return NAN;
3555  }
3556`,packedOpSnippet:`
3557  ivec4 ia = round(a);
3558  ivec4 ib = round(b);
3559  bvec4 cond = notEqual(ib, ivec4(0));
3560  ivec4 result = ivec4(0);
3561  vec4 s = sign(a) * sign(b);
3562
3563  // Windows (D3D) wants guaranteed non-zero int division at compile-time.
3564  if (cond[0]) {
3565    result[0] = idiv(ia[0], ib[0], s[0]);
3566  }
3567  if (cond[1]) {
3568    result[1] = idiv(ia[1], ib[1], s[1]);
3569  }
3570  if (cond[2]) {
3571    result[2] = idiv(ia[2], ib[2], s[2]);
3572  }
3573  if (cond[3]) {
3574    result[3] = idiv(ia[3], ib[3], s[3]);
3575  }
3576  return vec4(result);
3577`,dtype:"int32"}),tz={kernelName:No,backendName:"webgl",kernelFunc:ez};class nz{constructor(e){this.variableNames=["A"];const t=Ks(),[r,s]=e;this.outputShape=e,this.userCode=`
3578      void main() {
3579        ivec3 coords = getOutputCoords();
3580        int texR = coords[0];
3581        int texC = coords[1];
3582        int depth = coords[2];
3583        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${r}.0);
3584
3585        vec4 values = ${t.texture2D}(A, uv);
3586        float value;
3587        if (depth == 0) {
3588          value = values.r;
3589        } else if (depth == 1) {
3590          value = values.g;
3591        } else if (depth == 2) {
3592          value = values.b;
3593        } else if (depth == 3) {
3594          value = values.a;
3595        }
3596
3597        setOutput(floor(value * 255.0 + 0.5));
3598      }
3599    `}}class rz{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Ks(),[r,s]=e;this.outputShape=e,this.userCode=`
3600      void main() {
3601        ivec3 coords = getOutputCoords();
3602        int texR = coords[0];
3603        int texC = coords[1];
3604        int depth = coords[2];
3605
3606        vec4 result = vec4(0.);
3607
3608        for(int row=0; row<=1; row++) {
3609          for(int col=0; col<=1; col++) {
3610            texC = coords[1] + row;
3611            depth = coords[2] + col;
3612
3613            vec2 uv = (vec2(texC, texR) + halfCR) /
3614                       vec2(${s}.0, ${r}.0);
3615            vec4 values = ${t.texture2D}(A, uv);
3616            float value;
3617            if (depth == 0) {
3618              value = values.r;
3619            } else if (depth == 1) {
3620              value = values.g;
3621            } else if (depth == 2) {
3622              value = values.b;
3623            } else if (depth == 3) {
3624              value = values.a;
3625            }
3626
3627            result[row * 2 + col] = floor(value * 255.0 + 0.5);
3628          }
3629        }
3630
3631        ${t.output} = result;
3632      }
3633    `}}const sz={kernelName:_l,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n;let{pixels:s}=e;const{numChannels:a}=r,i=typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement,o=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,[l,p]=i?[s.videoWidth,s.videoHeight]:[s.width,s.height],c=[p,l],h=[p,l,a];if(o||i){const y=xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");dp!=null&&y===Hx||(Hx=y,dp=document.createElement("canvas").getContext("2d",{willReadFrequently:Hx})),dp.canvas.width=l,dp.canvas.height=p,dp.drawImage(s,0,0,l,p),s=dp.canvas}const d=t.makeTensorInfo(c,"int32");t.texData.get(d.dataId).usage=Ka.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(d.dataId),s);const m=xe().getBool("WEBGL_PACK")?new rz(h):new nz(h),g=t.runWebGLProgram(m,[d],"int32");return t.disposeData(d.dataId),g}};let dp,Hx=xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const az={kernelName:Lo,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:i,preluActivationWeights:o}=e,{strides:l,pad:p,dataFormat:c,dilations:h,dimRoundingMode:d,activation:m,leakyreluAlpha:g}=r,y=Du(c),w=is(s.shape,a.shape,l,h,p,d,!1,y);let v;const N=[],T=i!=null,$=o!=null,_=m==="leakyrelu",L=()=>{const O=[s,a],V=(U,X)=>{if(X==="NCHW"&&U.shape.length===1&&U.shape[0]!==1){const ne=It({inputs:{x:U},backend:t,attrs:{shape:[U.shape[0],1,1]}});return N.push(ne),ne}return U};if(T&&O.push(V(i,c)),$&&O.push(V(o,c)),_){const U=t.makeTensorInfo([],"float32",Bn(g,"float32"));O.push(U),N.push(U)}return O};if(w.filterHeight!==1||w.filterWidth!==1||w.dilationHeight!==1||w.dilationWidth!==1||w.strideHeight!==1||w.strideWidth!==1||w.padInfo.type!=="SAME"&&w.padInfo.type!=="VALID")if(w.strideWidth<=2&&y==="channelsLast"&&xe().getBool("WEBGL_EXP_CONV")){const O=m?jf(m,!0):null,V=new _S(w,T,O,$,_),U=[[w.padInfo.top,w.padInfo.left],[w.strideHeight,w.strideWidth],[w.dilationHeight,w.dilationWidth],[w.inHeight,w.inWidth
3633]],X=L();v=t.runWebGLProgram(V,X,"float32",U)}else if(xe().getBool("WEBGL_CONV_IM2COL"))v=FS({x:s,filter:a,convInfo:w,backend:t,bias:i,activation:m,preluActivationWeights:o,leakyreluAlpha:g});else{const O=m?jf(m,!1):null,V=new RS(w,T,O,$,_),U=L();v=t.runWebGLProgram(V,U,"float32")}else v=DS({x:s,filter:a,convInfo:w,backend:t,bias:i,activation:m,preluActivationWeights:o,leakyreluAlpha:g});const z=It({inputs:{x:v},backend:t,attrs:{shape:w.outShape}});return N.push(v),N.forEach(O=>t.disposeIntermediateTensorInfo(O)),z}},iz={kernelName:ni,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:i,preluActivationWeights:o}=e,{strides:l,pad:p,dilations:c,dimRoundingMode:h,activation:d,leakyreluAlpha:m}=r,g=[];let y=c;y==null&&(y=[1,1]),A(bs(l,y),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${y}'`);const w=is(s.shape,a.shape,l,y,p,h,!0),v=xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&w.strideWidth<=2&&w.outChannels/w.inChannels===1,N=d?jf(d,v):null,T=[s,a],$=i!=null,_=o!=null,L=d==="leakyrelu";if($&&T.push(i),_&&T.push(o),L){const U=t.makeTensorInfo([],"float32",Bn(m,"float32"));T.push(U),g.push(U)}let z;z=v?new BS(w,$,N,_,L):new PS(w,$,N,_,L);const O=[[w.padInfo.top,w.padInfo.left],[w.strideHeight,w.strideWidth],[w.dilationHeight,w.dilationWidth],[w.inHeight,w.inWidth]],V=t.runWebGLProgram(z,T,"float32",O);return g.forEach(U=>t.disposeIntermediateTensorInfo(U)),V}};class oz{constructor(e,t,r,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=r;const a=Xn(r.length);let i=`
3634    int index;`;for(let o=0;o<this.sliceDim;o++)i+=`
3635          index = round(getIndices(coords[0], ${o}));
3636          out_of_bounds = out_of_bounds || index < 0;
3637          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[o]};
3638          flattenIndex += index * ${this.strides[o]};`;this.userCode=`
3639         void main() {
3640          ${a} coords = getOutputCoords();
3641          int flattenIndex = 0;
3642          bool out_of_bounds = false;
3643
3644          ${i}
3645
3646          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
3647        }
3648      `}}const uz={kernelName:$c,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{params:r,indices:s}=e,a=s.shape,i=a[a.length-1],o=j(r.shape),[l,p,c,h]=Wl(r,s),d=It({inputs:{x:s},backend:t,attrs:{shape:[p,i]}}),m=It({inputs:{x:r},backend:t,attrs:{shape:[j(r.shape)/c,c]}});if(t.shouldExecuteOnCPU([r,s])||r.dtype==="string"){const v=t.readSync(s.dataId),N=t.bufferSync(r),T=QF(v,N,r.dtype,p,i,c,h,r.shape,o);return t.makeTensorInfo(l,r.dtype,T.values)}const g=new oz(i,h,[p,c],r.shape),y=t.runWebGLProgram(g,[m,d],m.dtype),w=It({inputs:{x:y},backend:t,attrs:{shape:l}});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(y),w}};class lz{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const r=Xn(this.rank),s=function(a){const i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let l=0;l<a.length;l++)l===2?o.push("index"):o.push(`${i[l]}`);return o.join()}(e);this.userCode=`
3649      void main() {
3650        ${r} resRC = getOutputCoords();
3651        int index = int(getIndices(resRC.x, resRC.z));
3652        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
3653        setOutput(inBounds * getA(${s}));
3654      }
3655    `}}function jS(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,indices:a}=e,{axis:i,batchDims:o}=r,l=Oe(i,s.shape)[0];if(xe().get("DEBUG")){const N=t.readSync(a.dataId),T=s.shape[l];for(let $=0;$<N.length;++$){const _=N[$];A(_<=T-1&&_>=0,()=>`GatherV2: the index value ${_} is not in [0, ${T-1}]`)}}const p=s1(s,a,l,o),c=j(a.shape),h=[],d=It({inputs:{x:s},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),m=It({inputs:{x:a},backend:t,attrs:{shape:[p.batchSize,c/p.batchSize]}});h.push(d),h.push(m);const g=[p.batchSize,p.outerSize,c/p.batchSize,p.sliceSize];if(t.shouldExecuteOnCPU([s,a])||s.dtype==="string"){const N=t.bufferSync(m),T=t.bufferSync(d),$=JF(T,N,g);return h.forEach(_=>t.disposeIntermediateTensorInfo(_)),t.makeTensorInfo(p.outputShape,$.dtype,$.values)}const y=new lz(d.shape,g),w=t.runWebGLProgram(y,[d,m],d.dtype);h.push(w);const v=It({inputs:{x:w},backend:t,attrs:{shape:p.outputShape}});return h.forEach(N=>t.disposeIntermediateTensorInfo(N)),v}const cz={kernelName:xn,backendName:"webgl",kernelFunc:jS},hz=Is({opSnippet:"return float(a > b);",packedOpSnippet:`
3656  return vec4(greaterThan(a, b));
3657`,cpuKernelImpl:eM,dtype:"bool"}),dz={kernelName:ea,backendName:"webgl",kernelFunc:hz},pz=Is({opSnippet:"return float(a >= b);",packedOpSnippet:`
3658  return vec4(greaterThanEqual(a, b));
3659`,dtype:"bool",cpuKernelImpl:tM}),fz={kernelName:Ht,backendName:"webgl",kernelFunc:pz},mz={kernelName:ei,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{input:r}=e;return GS(r,!0,t)}},gz=Cn({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),yz={kernelName:Ci,backendName:"webgl",kernelFunc:gz},bz=Cn({opSnippet:"return float(isinf(x));",dtype:"bool"}),xz={kernelName:ps,backendName:"webgl",kernelFunc:bz},wz=Cn({opSnippet:"return float(isnan(x));",dtype:"bool"}),vz={kernelName:ns,backendName:"webgl",kernelFunc:wz},kz=Is({opSnippet:"return float(a < b);",packedOpSnippet:`
3660  return vec4(lessThan(a, b));
3661`,cpuKernelImpl:nM,dtype:"bool"}),Nz={kernelName:Ls,backendName:"webgl",kernelFunc:kz},Iz=Is({opSnippet:"return float(a <= b);",packedOpSnippet:`
3662  return vec4(lessThanEqual(a, b));
3663`,cpuKernelImpl:rM,dtype:"bool"}),Sz={kernelName:$i,backendName:"webgl",kernelFunc:Iz},Tz={kernelName:ta,backendName:"webgl",kernelFunc:function(n){const{backend:e,attrs:t}=n,{start:r,stop:s,num:a}=t,i=sM(r,s,a);return e.makeTensorInfo([i.length],"float32",i)}},Ez=Cn({opSnippet:cp+`
3664  return x < 0.0 ? 0./0. : log(x);
3665`,packedOpSnippet:`
3666  vec4 result = log(x);
3667  bvec4 isNaN = isnan(x);
3668  result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
3669  result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
3670  result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
3671  result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
3672  return result;
3673`,cpuKernelImpl:aM}),Cz={kernelName:Ft,backendName:"webgl",kernelFunc:Ez},$z=Cn({opSnippet:cp+`
3674  return log(1.0 + x);
3675`}),Az={kernelName:Ai,backendName:"webgl",kernelFunc:$z},Rz=Is({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:`
3676  return vec4(
3677    vec4(greaterThanEqual(a, vec4(1.0))) *
3678    vec4(greaterThanEqual(b, vec4(1.0))));
3679`,dtype:"bool"}),_z={kernelName:Io,backendName:"webgl",kernelFunc:Rz},Dz=Cn({opSnippet:"return float(!(x >= 1.0));"}),Fz={kernelName:dl,backendName:"webgl",kernelFunc:Dz},Mz=Is({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:`
3680  return min(
3681    vec4(greaterThanEqual(a, vec4(1.0))) +
3682    vec4(greaterThanEqual(b, vec4(1.0))),
3683    vec4(1.0));
3684`,dtype:"bool"}),Oz={kernelName:su,backendName:"webgl",kernelFunc:Mz};class Lz{constructor(e,t,r,s,a){this.variableNames=["x"],this.outputShape=[];const i=t,o=e[3]-1;let l;this.outputShape=e;const p=`float(${r}) + float(${s}) * sum`;l=a===.5?`inversesqrt(${p})`:a===1?`1.0/(${p})`:`exp(log(${p}) * float(-${a}));`,this.userCode=`
3685      void main() {
3686        ivec4 coords = getOutputCoords();
3687        int b = coords[0];
3688        int r = coords[1];
3689        int c = coords[2];
3690        int d = coords[3];
3691        float x = getX(b, r, c, d);
3692        float sum = 0.0;
3693        for (int j = -${i}; j <= ${i}; j++) {
3694          int idx = d + j;
3695          if (idx >= 0 && idx <=  ${o}) {
3696            float z = getX(b, r, c, idx);
3697            sum += z * z;
3698          }
3699        }
3700        float val = x * ${l};
3701        setOutput(val);
3702      }
3703    `}}class zz{constructor(e,t,r,s,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const i=t,o=e[3]-1;let l;this.outputShape=e;const p=`float(${r}) + float(${s}) * sum`;l=a===.5?`inversesqrt(${p})`:a===1?`1.0/(${p})`:`exp(log(${p}) * float(-${a}));`,this.userCode=`
3704      void main() {
3705        ivec4 coords = getOutputCoords();
3706        int b = coords.x;
3707        int r = coords.y;
3708        int c = coords.z;
3709        int d = coords.w;
3710
3711        bool hasNextCol = d < ${this.outputShape[3]};
3712        bool hasNextRow = c < ${this.outputShape[2]};
3713
3714        vec4 sum = vec4(0.);
3715        vec4 xFragAtOutputCoords = getX(b, r, c, d);
3716
3717        vec4 xAtOutputCoords = vec4(
3718          getChannel(xFragAtOutputCoords, vec2(c, d)),
3719          hasNextCol ?
3720            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
3721          hasNextRow ?
3722            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
3723          (hasNextRow && hasNextCol) ?
3724            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
3725        );
3726
3727        int firstChannel = d - ${i};
3728        vec2 cache = vec2(0.);
3729        if(firstChannel >= 0){
3730          vec4 firstChannelFrag = getX(b, r, c, firstChannel);
3731          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
3732            if(hasNextRow){
3733              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
3734            }
3735        }
3736
3737        ivec2 depth = ivec2(d, d + 1);
3738        for (int j = - ${i}; j <= ${i}; j++) {
3739          ivec2 idx = depth + j;
3740          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
3741          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
3742
3743          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
3744          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
3745
3746          if(depthInRange || depthPlusOneInRange){
3747            vec4 z = vec4(0.);
3748            vec4 xFragAtCurrentDepth;
3749            z.xz = cache.xy;
3750            if(depthPlusOneInRange && hasNextCol){
3751              xFragAtCurrentDepth = idx.y != d ?
3752                getX(b, r, c, idx.y) : xFragAtOutputCoords;
3753              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
3754              if(hasNextRow){
3755                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
3756              }
3757            }
3758            cache.xy = z.yw;
3759            sum += z * z;
3760          }
3761        }
3762        vec4 result = xAtOutputCoords * ${l};
3763        setOutput(result);
3764      }
3765    `}}const Pz={kernelName:au,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{depthRadius:a,bias:i,alpha:o,beta:l}=r,p=xe().getBool("WEBGL_PACK_NORMALIZATION")?new zz(s.shape,a,i,o,l):new Lz(s.shape,a,i,o,l);return t.runWebGLProgram(p,[s],s.dtype)}};class Bz{constructor(e,t,r,s,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=s,this.beta=a,this.userCode=`
3766      void main() {
3767        ivec4 coords = getOutputCoords();
3768        int b = coords[0];
3769        int r = coords[1];
3770        int c = coords[2];
3771
3772        float result = 0.0;
3773        for (int d = 0; d < ${this.depth}; ++d) {
3774          int depthBegin = int(max(0.0, float(d - ${t})));
3775          int depthEnd = int(min(float(${this.depth}),
3776              float(d + ${t} + 1)));
3777
3778          const int MIN_DEPTH_BEGIN = 0;
3779          const int MAX_DEPTH_END = ${this.depth};
3780
3781          float norm = 0.0;
3782          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
3783            if (k < depthBegin){
3784              continue;
3785            }
3786            else if (k >= depthBegin && k < depthEnd) {
3787              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
3788            }
3789            else {
3790              break;
3791            }
3792          }
3793
3794          norm = float(${s}) * norm + float(${r});
3795
3796          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
3797            if (k < depthBegin){
3798              continue;
3799            }
3800            else if (k >= depthBegin && k < depthEnd){
3801              float dyi = -2.0 * float(${s})
3802                * float(${a})
3803                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
3804                / norm;
3805              if (k == d) {
3806                dyi += pow(norm, -1.0 * ${a});
3807              }
3808              if (k == coords[3]) {
3809                dyi *= getDy(b, r, c, d);
3810                result += dyi;
3811              }
3812            }
3813            else {
3814              break;
3815            }
3816          }
3817      }
3818      setOutput(result);
3819      }
3820    `}}const Vz={kernelName:Ma,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s,y:a,dy:i}=e,{depthRadius:o,bias:l,alpha:p,beta:c}=r,h=new Bz(s.shape,o,l,p,c);return t.runWebGLProgram(h,[s,a,i],s.dtype)}};function KS(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{reductionIndices:a,keepDims:i}=r,o=s.shape.length,l=Oe(a,s.shape);let p=l;const c=Ir(p,o),h=c!=null,d=t.shouldExecuteOnCPU([s]);let m=s;if(h){if(d){const N=t.texData.get(m.dataId).values,T=new Array(o);for(let _=0;_<T.length;_++)T[_]=s.shape[c[_]];const $=zx(N,s.shape,s.dtype,c,T);m=t.makeTensorInfo(T,s.dtype),t.texData.get(m.dataId).values=$}else m=my(s,c,t);p=Or(p.length,o)}xs("max",p,o);const[g,y]=us(m.shape,p);let w,v=g;if(i&&(v=Mr(g,l)),d){const N=t.texData.get(m.dataId).values,T=iM(N,j(y),v,s.dtype);w=t.makeTensorInfo(v,s.dtype),t.texData.get(w.dataId).values=T}else w=function(N,T,$,_){const L=j(T),z=It({inputs:{x:N},attrs:{shape:[j(N.shape)/L,L]},backend:_}),O=Oh(z,N.dtype,"max",_),V=It({inputs:{x:O},attrs:{shape:$},backend:_});return _.disposeIntermediateTensorInfo(z),_.disposeIntermediateTensorInfo(O),V}(m,y,v,t);return h&&t.disposeIntermediateTensorInfo(m),w}const Uz={kernelName:iu,backendName:"webgl",kernelFunc:KS},Wz=Is({opSnippet:Bx+`
3821  return max(a, b);
3822`,packedOpSnippet:`
3823  vec4 result = vec4(max(a, b));
3824  bvec4 isNaNA = isnan(a);
3825  bvec4 isNaNB = isnan(b);
3826  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
3827  `+Mh+`
3828  return result;
3829`,cpuKernelImpl:oM}),Gz={kernelName:To,backendName:"webgl",kernelFunc:Wz},Hz={kernelName:Ac,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e;sp(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;A(bs(i,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`);const p=li(s.shape,a,i,1,o,l);if(p.filterWidth===1&&p.filterHeight===1&&le(p.inShape,p.outShape))return Ra({inputs:{x:s},backend:t});const c=new Kf(p,"max",!1);return t.runWebGLProgram(c,[s],s.dtype)}},jz={kernelName:Oa,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:i,pad:o,dataFormat:l,dimRoundingMode:p}=r,c=_u(s.shape,a,i,[1,1,1],o,p,l),h=new Ux(c,"max",!1);return t.runWebGLProgram(h,[s],s.dtype)}};class Kz{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,a=e.effectiveFilterHeight,i=e.effectiveFilterWidth,o=a-1-e.padInfo.top,l=i-1-e.padInfo.left,p=a*i-1;this.userCode=`
3830      const ivec2 pads = ivec2(${o}, ${l});
3831
3832      void main() {
3833        ivec4 coords = getOutputCoords();
3834        int b = coords[0];
3835        int d = coords[3];
3836
3837        ivec2 dyRCCorner = coords.yz - pads;
3838        int dyRCorner = dyRCCorner.x;
3839        int dyCCorner = dyRCCorner.y;
3840
3841        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
3842        // ? = to be determined. : = across all values in that axis.
3843        float dotProd = 0.0;
3844        for (int wR = 0; wR < ${a};
3845          wR += ${s}) {
3846          float dyR = float(dyRCorner + wR) / ${t}.0;
3847
3848          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
3849            continue;
3850          }
3851          int idyR = int(dyR);
3852
3853          for (int wC = 0; wC < ${i}; wC++) {
3854            float dyC = float(dyCCorner + wC) / ${r}.0;
3855
3856            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
3857                fract(dyC) > 0.0) {
3858              continue;
3859            }
3860            int idyC = int(dyC);
3861
3862            float dyValue = getDy(b, idyR, idyC, d);
3863            int maxPosValue = ${p} - int(getMaxPos(b, idyR, idyC, d));
3864
3865            // Get the current value, check it against the value from the
3866            // position matrix.
3867            int curPosValue = wR * ${i} + wC;
3868            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
3869
3870            dotProd += dyValue * mask;
3871          }
3872        }
3873        setOutput(dotProd);
3874      }
3875    `}}class qz{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,r=e.strideHeight,s=e.strideWidth,a=e.dilationDepth,i=e.dilationHeight,o=e.dilationWidth,l=e.effectiveFilterDepth,p=e.effectiveFilterHeight,c=e.effectiveFilterWidth,h=l-1-e.padInfo.front,d=p-1-e.padInfo.top,m=c-1-e.padInfo.left,g=l*p*c-1;this.userCode=`
3876      const ivec3 pads = ivec3(${h}, ${d}, ${m});
3877
3878      void main() {
3879        ivec5 coords = getOutputCoords();
3880        int batch = coords.x;
3881        int ch = coords.u;
3882
3883        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
3884        int dyDCorner = dyCorner.x;
3885        int dyRCorner = dyCorner.y;
3886        int dyCCorner = dyCorner.z;
3887
3888        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
3889        // dx(xD, xR, xC, ch).
3890        // ? = to be determined. : = across all values in that axis.
3891        float dotProd = 0.0;
3892
3893        for (int wD = 0; wD < ${l};
3894           wD += ${a}) {
3895          float dyD = float(dyDCorner + wD) / ${t}.0;
3896
3897          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
3898            continue;
3899          }
3900          int idyD = int(dyD);
3901
3902          for (int wR = 0; wR < ${p};
3903              wR += ${i}) {
3904            float dyR = float(dyRCorner + wR) / ${r}.0;
3905
3906            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
3907                fract(dyR) > 0.0) {
3908              continue;
3909            }
3910            int idyR = int(dyR);
3911
3912            for (int wC = 0; wC < ${c};
3913                wC += ${o}) {
3914              float dyC = float(dyCCorner + wC) / ${s}.0;
3915
3916              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
3917                  fract(dyC) > 0.0) {
3918                continue;
3919              }
3920              int idyC = int(dyC);
3921
3922              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
3923              int maxPosValue = ${g} -
3924                  int(getMaxPos(batch, idyD, idyR, idyC, ch));
3925
3926              // Get the current value, check it against the value from the
3927              // position matrix.
3928              int curPosValue =
3929                  wD * ${p} * ${c} +
3930                  wR * ${c} + wC;
3931              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
3932
3933              dotProd += dyValue * mask;
3934            }
3935          }
3936        }
3937        setOutput(dotProd);
3938      }
3939    `}}const Xz={kernelName:Rc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,i=a,{filterSize:o,strides:l,pad:p,dimRoundingMode:c}=r,h=_u(i.shape,o,l,[1,1,1],p,c),d=new Ux(h,"max",!0),m=t.runWebGLProgram(d,[i],i.dtype),g=new qz(h),y=t.runWebGLProgram(g,[s,m],i.dtype);return t.disposeIntermediateTensorInfo(m),y}},Yz={kernelName:pl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a,output:i}=e,o=a;sp([a,i],"maxPoolGrad");const{filterSize:l,strides:p,pad:c,dimRoundingMode:h}=r,d=li(o.shape,l,p,1,c,h),m=new Kf(d,"max",!0),g=t.runWebGLProgram(m,[o],o.dtype),y=new Kz(d),w=t.runWebGLProgram(y,[s,g],o.dtype);return t.disposeIntermediateTensorInfo(g),w}},Zz={kernelName:_c,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:r}=n,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=e,l=t;A(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);const p=[1,1];A(bs(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const c=li(r.shape,s,a,p,i),[h,d]=function(m,g,y,w){let v=new Kf(y,"max",!1);const N=w.runWebGLProgram(v,[m],"float32");return v=new Kf(y,"max",!0,!0,g),[N,w.runWebGLProgram(v,[m],"float32")]}(r,o,c,l);return[h,d]}},Qz={kernelName:fl,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:r}=n,{keepDims:s,axis:a}=e,i=t,o=r.shape.length,l=Oe(a,r.shape);let p=l;const c=Ir(p,o),h=c!=null,d=i.shouldExecuteOnCPU([r]),m=[];let g=r;if(h){if(d){const T=i.texData.get(g.dataId).values,$=new Array(o);for(let L=0;L<$.length;L++)$[L]=r.shape[c[L]];const _=zx(T,r.shape,r.dtype,c,$);g=i.makeTensorInfo($,r.dtype),i.texData.get(g.dataId).values=_}else g=my(r,c,i);m.push(g),p=Or(p.length,o)}xs("sum",p,o);const[y,w]=us(g.shape,p);let v=y;s&&(v=Mr(y,l));const N=function(T,$,_,L){const z=j($),O=It({inputs:{x:T},attrs:{shape:[j(T.shape)/z,z]},backend:L}),V=Oh(O,"float32","mean",L),U=It({inputs:{x:V},attrs:{shape:_},backend:L});return L.disposeIntermediateTensorInfo(O),L.disposeIntermediateTensorInfo(V),U}(g,w,v,i);for(const T of m)i.disposeIntermediateTensorInfo(T);return N}},Jz={kernelName:ml,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r,o=s.shape.length,l=Oe(a,s.shape);let p=l;const c=Ir(p,o);let h=s;c!=null&&(h=Xs({inputs:{x:s},backend:t,attrs:{perm:c}}),p=Or(p.length,s.shape.length)),xs("min",p,o);const[d,m]=us(h.shape,p),g=It({inputs:{x:h},backend:t,attrs:{shape:[-1,j(m)]}}),y=Oh(g,g.dtype,"min",t);let w;return w=It(i?{inputs:{x:y},backend:t,attrs:{shape:Mr(d,l)}}
3939:{inputs:{x:y},backend:t,attrs:{shape:d}}),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),c!=null&&t.disposeIntermediateTensorInfo(h),w}},eP=Is({opSnippet:Bx+`
3940  return min(a, b);
3941`,packedOpSnippet:`
3942  vec4 result = vec4(min(a, b));
3943  bvec4 isNaNA = isnan(a);
3944  bvec4 isNaNB = isnan(b);
3945  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
3946  `+Mh+`
3947  return result;
3948`,cpuKernelImpl:uM}),tP={kernelName:Ri,backendName:"webgl",kernelFunc:eP};class nP{constructor(e,t,r){this.variableNames=["x"],this.outputShape=t.map((c,h)=>c[0]+e[h]+c[1]);const s=e.length,a=Xn(s),i=t.map(c=>c[0]).join(","),o=t.map((c,h)=>c[0]+e[h]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),p=r==="reflect"?0:1;this.userCode=s!==1?`
3949      ${a} start = ${a}(${i});
3950      ${a} end = ${a}(${o});
3951
3952      void main() {
3953        ${a} outC = getOutputCoords();
3954        for (int i = 0; i < ${s}; i++) {
3955          if (outC[i] < start[i]) {
3956            outC[i] = start[i] * 2 - outC[i] - ${p};
3957          } else if(outC[i] >= end[i]) {
3958            outC[i] = (end[i] - 1) * 2 - outC[i] + ${p};
3959          }
3960        }
3961        ${a} coords = outC - start;
3962        setOutput(getX(${l}));
3963      }
3964    `:`
3965        int start = ${i};
3966        int end = ${o};
3967
3968        void main() {
3969          int outC = getOutputCoords();
3970          if (outC < start) {
3971            outC = start * 2 - outC - ${p};
3972          } else if(outC >= end) {
3973            outC = (end - 1) * 2 - outC + ${p};
3974          }
3975          setOutput(getX(outC - start));
3976        }
3977      `}}class rP{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((g,y)=>g[0]+e[y]+g[1]);const s=e.length,a=Xn(s),i=t.map(g=>g[0]).join(","),o=t.map((g,y)=>g[0]+e[y]).join(","),l=qs("rc",s),p=qs("source",s),c=`${l[s-1]} < ${this.outputShape[s-1]}`,h=s===1?"source":`vec2(${p.slice(-2).join()})`,d=r==="reflect"?0:1;let m="";if(s===1){const g=`
3978        ${a} source = rc;
3979        if (source < start) {
3980          source = start * 2 - source - ${d};
3981        } else if (source >= end) {
3982          source = (end - 1) * 2 - source + ${d};
3983        }
3984        source -= start;
3985      `;m=`
3986        ${a} rc = outputLoc;
3987        ${g}
3988        result[0] = getChannel(getX(${p.join()}), ${h});
3989        ${l[s-1]} += 1;
3990        if(${c}) {
3991          ${g}
3992          result[1] = getChannel(getX(${p.join()}), ${h});
3993        }
3994      `}else{const g=`
3995        ${a} source = rc;
3996        ${a} lt = ${a}(lessThan(source, start));
3997        ${a} gte = ${a}(greaterThanEqual(source, end));
3998        ${a} orig = 1 - (lt + gte);
3999        source = orig * source +
4000                lt * (start * 2 - source - ${d}) +
4001                gte * ((end - 1) * 2 - source + ${d});
4002        source -= start;
4003      `;m=`
4004        ${a} rc = outputLoc;
4005        ${g}
4006        result[0] = getChannel(getX(${p.join()}), ${h});
4007        ${l[s-1]} += 1;
4008        if(${c}) {
4009          ${g}
4010          result[1] = getChannel(getX(${p.join()}), ${h});
4011        }
4012        rc = outputLoc;
4013        ${l[s-2]} += 1;
4014        if(${l[s-2]} < ${this.outputShape[s-2]}) {
4015          ${g}
4016          result[2] = getChannel(getX(${p.join()}), ${h});
4017          ${l[s-1]} += 1;
4018          if(${c}) {
4019            ${g}
4020            result[3] = getChannel(getX(${p.join()}), ${h});
4021          }
4022        }
4023      `}this.userCode=`
4024      const ${a} start = ${a}(${i});
4025      const ${a} end = ${a}(${o});
4026
4027      void main() {
4028        ${a} outputLoc = getOutputCoords();
4029        vec4 result = vec4(0.);
4030        ${m}
4031        setOutput(result);
4032      }
4033    `}}const sP={kernelName:_i,backendName:"webgl",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:r}=n,{paddings:s,mode:a}=t,i=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rP(r.shape,s,a):new nP(r.shape,s,a);return e.runWebGLProgram(i,[r],r.dtype)}},aP=Is({opSnippet:`if (b == 0.0) return NAN;
4034  return mod(a, b);`,packedOpSnippet:`
4035  vec4 result = mod(a, b);
4036  bvec4 isNaN = equal(b, vec4(0.0));
4037  `+Mh+`
4038  return result;
4039`}),iP={kernelName:Eo,backendName:"webgl",kernelFunc:aP};class oP{constructor(e,t,r){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,r],this.userCode=`
4040      void main() {
4041        ivec2 coords = getOutputCoords();
4042        int batch = coords[0];
4043
4044        float r = random(seed);
4045        float cdf = 0.0;
4046
4047        for (int i = 0; i < ${t-1}; i++) {
4048          cdf += getProbs(batch, i);
4049
4050          if (r < cdf) {
4051            setOutput(float(i));
4052            return;
4053          }
4054        }
4055
4056        // If no other event happened, last event happened.
4057        setOutput(float(${t-1}));
4058      }
4059    `}}const qS=Is({opSnippet:`
4060if (a == b) {
4061  return 1.0;
4062};
4063return a / b;`,packedOpSnippet:`
4064  // vec4 one = vec4(equal(a, b));
4065  // return one + (vec4(1.0) - one) * a / b;
4066  vec4 result = a / b;
4067  if(a.x == b.x) {
4068    result.x = 1.;
4069  }
4070  if(a.y == b.y) {
4071    result.y = 1.;
4072  }
4073  if(a.z == b.z) {
4074    result.z = 1.;
4075  }
4076  if(a.w == b.w) {
4077    result.w = 1.;
4078  }
4079
4080  return result;
4081`,checkOutOfBounds:!0}),uP={kernelName:Ti,backendName:"webgl",kernelFunc:qS},XS="return a - b;",YS=Is({opSnippet:XS,packedOpSnippet:XS,supportsComplex:!0,cpuKernelImpl:$M}),lP={kernelName:Rl,backendName:"webgl",kernelFunc:YS};function ZS(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{dim:a}=r,i=Oe([a],s.shape),o=KS({inputs:{x:s},backend:t,attrs:{reductionIndices:i,keepDims:!1}}),l=Mr(o.shape,i),p=It({inputs:{x:o},backend:t,attrs:{shape:l}}),c=YS({inputs:{a:s,b:p},backend:t}),h=VS({inputs:{x:c},backend:t}),d=gy({inputs:{x:h},backend:t,attrs:{axis:i,keepDims:!1}}),m=It({inputs:{x:d},backend:t,attrs:{shape:l}}),g=qS({inputs:{a:h,b:m},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(m),g}const cP={kernelName:mu,backendName:"webgl",kernelFunc:ZS},hP={kernelName:Dc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{numSamples:a,seed:i,normalized:o}=r,l=o?s:ZS({inputs:{logits:s},backend:t,attrs:{dim:s.shape.length-1}}),p=l.shape[0],c=l.shape[1],h=new oP(p,c,a),d=[[i]],m=t.runWebGLProgram(h,[l],"int32",d);return o||t.disposeIntermediateTensorInfo(l),m}},dP=yi+`
4082  return -x;
4083`,pP={kernelName:Co,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{x:r}=e;if(t.shouldExecuteOnCPU([r])){const a=t.texData.get(r.dataId),[i,o]=cM(a.values,r.shape,r.dtype);return t.makeTensorInfo(o,r.dtype,i)}let s;return s=xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new dc(r.shape,`
4084  vec4 result = -x;
4085  bvec4 isNaN = isnan(x);
4086
4087  result.r = isNaN.r ? x.r : result.r;
4088  result.g = isNaN.g ? x.g : result.g;
4089  result.b = isNaN.b ? x.b : result.b;
4090  result.a = isNaN.a ? x.a : result.a;
4091
4092  return result;
4093`):new Qo(r.shape,dP),t.runWebGLProgram(s,[r],r.dtype)}},fP=ig,mP={kernelName:zs,backendName:"webgl",kernelFunc:function(n){In("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=r,p=t.readSync(s.dataId),c=t.readSync(a.dataId),{selectedIndices:h}=fP(p,c,i,o,l);return t.makeTensorInfo([h.length],"int32",new Int32Array(h))}},gP=og,yP={kernelName:Mt,backendName:"webgl",kernelFunc:function(n){In("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:p}=r,c=t.readSync(s.dataId),h=t.readSync(a.dataId),{selectedIndices:d,validOutputs:m}=gP(c,h,i,o,l,p);return[t.makeTensorInfo([d.length],"int32",new Int32Array(d)),t.makeTensorInfo([],"int32",new Int32Array([m]))]}},bP=ug,xP={kernelName:Fc,backendName:"webgl",kernelFunc:function(n){In("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:p}=r,c=t.readSync(s.dataId),h=t.readSync(a.dataId),d=i,m=o,g=l,y=p,{selectedIndices:w,selectedScores:v}=bP(c,h,d,m,g,y);return[t.makeTensorInfo([w.length],"int32",new Int32Array(w)),t.makeTensorInfo([v.length],"float32",new Float32Array(v))]}};class wP{constructor(e,t,r,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
4094      void main() {
4095        ivec2 coords = getOutputCoords();
4096        int index = round(getIndices(coords.x));
4097        setOutput(mix(float(${s}), float(${r}),
4098                      float(index == coords.y)));
4099      }
4100    `}}const vP={kernelName:ou,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{indices:s}=e,{dtype:a,depth:i,onValue:o,offValue:l}=r,p=j(s.shape),c=new wP(p,i,o,l),h=It({inputs:{x:s},backend:t,attrs:{shape:[p]}}),d=t.runWebGLProgram(c,[h],a);t.disposeIntermediateTensorInfo(h);const m=It({inputs:{x:d},backend:t,attrs:{shape:[...s.shape,i]}});return t.disposeIntermediateTensorInfo(d),m}};function vy(n){const{inputs:e,backend:t}=n,{x:r}=e;if(r.dtype==="complex64"){const s=qf({inputs:{input:r},backend:t}),a=vy({inputs:{x:s},backend:t}
4100),i=xy({inputs:{input:r},backend:t}),o=vy({inputs:{x:i},backend:t}),l=pc({inputs:{real:a,imag:o},backend:t});return t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),l}return Zf({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:t})}const kP={kernelName:ku,backendName:"webgl",kernelFunc:vy},NP={kernelName:gl,backendName:"webgl",kernelFunc:function n(e){const{inputs:t,backend:r}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const a=qf({inputs:{input:s},backend:r}),i=n({inputs:{x:a},backend:r}),o=xy({inputs:{input:s},backend:r}),l=vy({inputs:{x:o},backend:r}),p=pc({inputs:{real:i,imag:l},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),p}return Zf({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:r})}},IP={kernelName:Mc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r;if(e.length===1)return Gx({inputs:{input:e[0]},backend:t,attrs:{dim:s}});const a=e[0].shape,i=e[0].dtype;e.forEach(p=>{ge(a,p.shape,"All tensors passed to stack must have matching shapes"),A(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],l=AS({inputs:e.map(p=>{const c=Gx({inputs:{input:p},backend:t,attrs:{dim:s}});return o.push(c),c}),backend:t,attrs:{axis:s}});return o.forEach(p=>t.disposeIntermediateTensorInfo(p)),l}};class SP{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((p,c)=>p[0]+e[c]+p[1]);const s=e.length,a=Xn(s),i=t.map(p=>p[0]).join(","),o=t.map((p,c)=>p[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);this.userCode=s!==1?`
4101      ${a} start = ${a}(${i});
4102      ${a} end = ${a}(${o});
4103
4104      void main() {
4105        ${a} outC = getOutputCoords();
4106        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
4107          setOutput(value);
4108        } else {
4109          ${a} coords = outC - start;
4110          setOutput(getX(${l}));
4111        }
4112      }
4113    `:`
4114        int start = ${i};
4115        int end = ${o};
4116
4117        void main() {
4118          int outC = getOutputCoords();
4119          if (outC < start || outC >= end) {
4120            setOutput(value);
4121          } else {
4122            setOutput(getX(outC - start));
4123          }
4124        }
4125      `}}class TP{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((y,w)=>y[0]+e[w]+y[1]);const s=e.length,a=Xn(s),i=t.map(y=>y[0]).join(","),o=t.map((y,w)=>y[0]+e[w]).join(","),l=qs("rc",s),p=qs("source",s),c=`${l[s-1]} < ${this.outputShape[s-1]}`,h=s===1?"source":`vec2(${p.slice(-2).join()})`,d=[`${a} rc = outputLoc;`,`${l[s-1]} += 1;
4126       if(${c}) {
4127      `,s===1?"":`}
4128       rc = outputLoc;
4129       ${l[s-2]} += 1;
4130       if(${l[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":`  ${l[s-1]} += 1;
4131         if(${c}) {`],m=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let g="";for(let y=0,w=s===1?2:4;y<w;y++)g+=`
4132        ${d[y]}
4133        if (${m}) {
4134          result[${y}] = float(value);
4135        } else {
4136          ${a} source = rc - start;
4137          result[${y}] = getChannel(getX(${p.join()}), ${h});
4138        }
4139      `;g+=s===1?"} ":"}}",this.userCode=`
4140      const ${a} start = ${a}(${i});
4141      const ${a} end = ${a}(${o});
4142
4143      void main() {
4144        ${a} outputLoc = getOutputCoords();
4145        vec4 result = vec4(0.);
4146        ${g}
4147        setOutput(result);
4148      }
4149    `}}const QS=n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{paddings:a,constantValue:i}=r;if(j(s.shape)===0){const p=a.map((c,h)=>c[0]+s.shape[h]+c[1]);return Zf({backend:t,attrs:{shape:p,value:i,dtype:s.dtype}})}const o=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new TP(s.shape,a,i):new SP(s.shape,a,i),l=[[i]];return t.runWebGLProgram(o,[s],s.dtype,l)},EP={kernelName:yl,backendName:"webgl",kernelFunc:QS},CP=Is({opSnippet:`
4150  if(a < 0.0 && floor(b) < b){
4151    return NAN;
4152  }
4153  if (b == 0.0) {
4154    return 1.0;
4155  }
4156  return (round(mod(b, 2.0)) != 1) ?
4157      pow(abs(a), b) : sign(a) * pow(abs(a), b);
4158`,packedOpSnippet:`
4159  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
4160  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
4161  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
4162  vec4 result = multiplier * pow(abs(a), b);
4163
4164  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
4165  bvec4 isExpZero = equal(b, vec4(0.0));
4166  result.r = isExpZero.r ? 1.0 : result.r;
4167  result.g = isExpZero.g ? 1.0 : result.g;
4168  result.b = isExpZero.b ? 1.0 : result.b;
4169  result.a = isExpZero.a ? 1.0 : result.a;
4170
4171  bvec4 isNaN1 = lessThan(a, vec4(0.0));
4172  bvec4 isNaN2 = lessThan(floor(b), b);
4173  bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
4174  `+Mh+`
4175  return result;
4176`}),$P={kernelName:bl,backendName:"webgl",kernelFunc:CP},AP={kernelName:Fi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:i}=r,o=s.shape.length,l=[],p=Oe(a,s.shape);let c=p;const h=Ir(c,o);let d,m=s;
4176if(h!=null&&(m=Xs({inputs:{x:s},backend:t,attrs:{perm:h}}),c=Or(c.length,o),l.push(m)),xs("prod",c,o),t.shouldExecuteOnCPU([m])){const g=t.texData.get(m.dataId).values,{outVals:y,outShape:w,outDtype:v}=dM(m.shape,m.dtype,g,c);d=t.makeTensorInfo(w,v,y)}else{const[g,y]=us(m.shape,c),w=j(y),v=It({inputs:{x:m},backend:t,attrs:{shape:[-1,w]}}),N=Oh(v,Kc(s.dtype),"prod",t);d=It({inputs:{x:N},backend:t,attrs:{shape:g}}),l.push(v),l.push(N)}if(i){l.push(d);const g=Mr(d.shape,p);d=It({inputs:{x:d},backend:t,attrs:{shape:g}})}return l.forEach(g=>t.disposeIntermediateTensorInfo(g)),d}},RP={kernelName:uu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=e,{outputRaggedRank:o}=r,l=s.map(v=>t.readSync(v.dataId)),p=s.map(v=>v.shape),c=t.readSync(a.dataId),h=t.readSync(i.dataId),[d,m,g]=pM(l,p,c,a.shape,a.dtype,h,i.shape,o),y=d.map(v=>t.makeTensorInfo([v.length],"int32",v)),w=t.makeTensorInfo(g,a.dtype,m);return y.concat([w])}},_P={kernelName:Ao,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{starts:r,limits:s,deltas:a}=e,i=t.readSync(r.dataId),o=t.readSync(s.dataId),l=t.readSync(a.dataId),[p,c]=fM(i,r.shape,r.dtype,o,s.shape,l,a.shape);return[t.makeTensorInfo([p.length],"int32",p),t.makeTensorInfo([c.length],r.dtype,c)]}},DP={kernelName:Mi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=e,{rowPartitionTypes:l}=r,p=t.readSync(s.dataId),c=t.readSync(a.dataId),h=t.readSync(i.dataId),d=o.map(w=>t.readSync(w.dataId)),m=o.map(w=>w.shape),[g,y]=mM(p,s.shape,c,a.shape,a.dtype,h,i.shape,d,m,l);return t.makeTensorInfo(g,a.dtype,y)}},JS=n=>{const{backend:e,attrs:t}=n,{start:r,stop:s,step:a,dtype:i}=t,o=gM(r,s,a,i);return e.makeTensorInfo([o.length],i,o)},FP={kernelName:Ts,backendName:"webgl",kernelFunc:JS},MP=Cn({opSnippet:"return 1.0 / x;"}),OP={kernelName:Ro,backendName:"webgl",kernelFunc:MP},LP=Cn({opSnippet:yi+`
4177  return (x < 0.0) ? 0.0 : x;
4178`,packedOpSnippet:`
4179  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
4180  bvec4 isNaN = isnan(x);
4181
4182  result.r = isNaN.r ? x.r : result.r;
4183  result.g = isNaN.g ? x.g : result.g;
4184  result.b = isNaN.b ? x.b : result.b;
4185  result.a = isNaN.a ? x.a : result.a;
4186
4187  return result;
4188`}),zP={kernelName:Oi,backendName:"webgl",kernelFunc:LP},PP=Cn({opSnippet:yi+`
4189  return (x < 0.0) ? 0.0 : min(6.0, x);
4190`,packedOpSnippet:`
4191  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
4192  bvec4 isNaN = isnan(x);
4193
4194  result.r = isNaN.r ? x.r : result.r;
4195  result.g = isNaN.g ? x.g : result.g;
4196  result.b = isNaN.b ? x.b : result.b;
4197  result.a = isNaN.a ? x.a : result.a;
4198
4199  return result;
4200`}),BP={kernelName:Do,backendName:"webgl",kernelFunc:PP};class VP{constructor(e,t,r,s,a){this.variableNames=["A"],this.outputShape=[];const[i,o,l,p]=e;this.outputShape=[i,t,r,p];const c=[s&&t>1?o-1:o,s&&r>1?l-1:l],h=[s&&t>1?t-1:t,s&&r>1?r-1:r];let d;d=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
4201      const vec2 effectiveInputOverOutputRatioRC = vec2(
4202          ${c[0]/h[0]},
4203          ${c[1]/h[1]});
4204      const vec2 inputShapeRC = vec2(${o}.0, ${l}.0);
4205
4206      void main() {
4207        ivec4 coords = getOutputCoords();
4208        int b = coords[0];
4209        int d = coords[3];
4210        ivec2 yRC = coords.yz;
4211
4212        // Fractional source index.
4213        vec2 sourceFracIndexRC = ${d};
4214
4215        // Compute the four integer indices.
4216        ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
4217        ivec2 sourceCeilRC = ivec2(
4218          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
4219
4220        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
4221        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
4222        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
4223        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
4224
4225        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
4226
4227        float top = topLeft + (topRight - topLeft) * fracRC.y;
4228        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
4229        float newValue = top + (bottom - top) * fracRC.x;
4230
4231        setOutput(newValue);
4232      }
4233    `}}class UP{constructor(e,t,r,s,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,o,l,p]=e;this.outputShape=[i,t,r,p];const c=[s&&t>1?o-1:o,s&&r>1?l-1:l],h=[s&&t>1?t-1:t,s&&r>1?r-1:r];let d;d=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
4234      const vec3 effectiveInputOverOutputRatioRC = vec3(
4235          ${c[0]/h[0]},
4236          ${c[1]/h[1]},
4237          ${c[1]/h[1]});
4238      const vec3 inputShapeRC = vec3(${o}.0, ${l}.0,
4239                                     ${l}.0);
4240
4241      float getAValue(int b, int r, int c, int d) {
4242        return getChannel(getA(b, r, c, d), vec2(c, d));
4243      }
4244
4245      void main() {
4246        ivec4 coords = getOutputCoords();
4247        int b = coords[0];
4248        int d = coords[3];
4249        // Calculate values for next column in yRC.z.
4250        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
4251
4252        // Fractional source index.
4253        vec3 sourceFracIndexRC = ${d};
4254
4255        // Compute the four integer indices.
4256        ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
4257        ivec3 sourceCeilRC = ivec3(
4258          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
4259
4260        // Should we calculate next column and row elements in 2x2 packed cell.
4261        bool hasNextCol = d < ${p-1};
4262        bool hasNextRow = coords.z < ${r-1}
vendor: 2,018 bytes, lines 4262-4310
4262;
4263
4264        // In parallel, construct four corners for all four components in
4265        // packed 2x2 cell.
4266        vec4 topLeft = vec4(
4267          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
4268          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
4269                     : 0.0,
4270          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
4271                     : 0.0,
4272          (hasNextRow && hasNextCol) ?
4273            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
4274
4275        vec4 bottomLeft = vec4(
4276          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
4277          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
4278                     : 0.0,
4279          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
4280                     : 0.0,
4281          (hasNextRow && hasNextCol) ?
4282            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
4283
4284        vec4 topRight = vec4(
4285          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
4286          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
4287                     : 0.0,
4288          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
4289                     : 0.0,
4290          (hasNextRow && hasNextCol) ?
4291            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
4292
4293        vec4 bottomRight = vec4(
4294          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
4295          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
4296                     : 0.0,
4297          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
4298                     : 0.0,
4299          (hasNextRow && hasNextCol) ?
4300            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
4301
4302        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
4303
4304        vec4 top = mix(topLeft, topRight, fracRC.yyzz);
4305        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
4306        vec4 newValue = mix(top, bottom, fracRC.x);
4307
4308        setOutput(newValue);
4309      }
4310    `}
vendor: 5,904 bytes, lines 4310-4443
4310}const WP={kernelName:vl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,halfPixelCenters:i,size:o}=r,[l,p]=o,c=xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new UP(s.shape,l,p,a,i):new VP(s.shape,l,p,a,i);return t.runWebGLProgram(c,[s],"float32")}};class GP{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,a]=t,[,i,o]=e,l=[r&&i>1?s-1:s,r&&o>1?a-1:a],p=[r&&i>1?i-1:i,r&&o>1?o-1:o],c=l[0]/p[0],h=l[1]/p[1],d=1/c,m=1/h,g=2*Math.ceil(d)+2,y=2*Math.ceil(m)+2;this.userCode=`
4311      void main() {
4312        ivec4 coords = getOutputCoords();
4313        int b = coords[0];
4314        int d = coords[3];
4315        int r = coords[1];
4316        int c = coords[2];
4317
4318        float accumulator = 0.0;
4319
4320        const float heightScale = float(${c});
4321        const float widthScale = float(${h});
4322
4323        const float invHeightScale = float(${d});
4324        const float invWidthScale = float(${m});
4325
4326        const int winHeight = int(${g});
4327        const int winWidth = int(${y});
4328
4329        // Compute bounds for where in dy we will look
4330        float startRLerp = floor(float(r) * invHeightScale);
4331        int startDyR = int(startRLerp - float(winHeight / 2));
4332
4333        float startCLerp = floor(float(c) * invWidthScale);
4334        int startDyC = int(startCLerp - float(winWidth / 2));
4335
4336        // Loop over dy
4337        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
4338          int dyR = dyROffset + startDyR;
4339
4340          // Guard against the window exceeding the bounds of dy
4341          if (dyR < 0 || dyR >= ${i}) {
4342            continue;
4343          }
4344
4345          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
4346            int dyC = dyCOffset + startDyC;
4347
4348            // Guard against the window exceeding the bounds of dy
4349            if (dyC < 0 || dyC >= ${o}) {
4350              continue;
4351            }
4352
4353            float dxR = float(dyR) * heightScale;
4354            int topDxRIndex = int(floor(dxR));
4355            int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
4356            float dxRLerp = dxR - float(topDxRIndex);
4357            float inverseDxRLerp = 1.0 - dxRLerp;
4358
4359            float dxC = float(dyC) * widthScale;
4360            int leftDxCIndex = int(floor(dxC));
4361            int rightDxCIndex = int(min(ceil(dxC), ${a-1}.0));
4362            float dxCLerp = dxC - float(leftDxCIndex);
4363            float inverseDxCLerp = 1.0 - dxCLerp;
4364
4365            if (r == topDxRIndex && c == leftDxCIndex) {
4366              // topLeft
4367              accumulator +=
4368                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
4369            }
4370
4371            if (r == topDxRIndex && c == rightDxCIndex) {
4372              // topRight
4373              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
4374            }
4375
4376            if (r == bottomDxRIndex && c == leftDxCIndex) {
4377              // bottomLeft
4378              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
4379            }
4380
4381            if (r == bottomDxRIndex && c == rightDxCIndex) {
4382              // bottomRight
4383              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
4384            }
4385          }
4386        }
4387        // End loop over dy
4388
4389        setOutput(accumulator);
4390      }
4391    `}}const HP={kernelName:kl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:i}=r,o=new GP(a.shape,s.shape,i);return t.runWebGLProgram(o,[a],a.dtype)}};class jP{constructor(e,t,r,s,a){this.variableNames=["A"],this.outputShape=[];const[i,o,l,p]=e;this.outputShape=[i,t,r,p];const c=[s&&t>1?o-1:o,s&&r>1?l-1:l],h=[s&&t>1?t-1:t,s&&r>1?r-1:r],d=s?"0.5":"0.0";let m;m=a?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
4392      const vec2 effectiveInputOverOutputRatioRC = vec2(
4393          ${c[0]/h[0]},
4394          ${c[1]/h[1]});
4395      const vec2 inputShapeRC = vec2(${o}.0, ${l}.0);
4396
4397      void main() {
4398        ivec4 coords = getOutputCoords();
4399        int b = coords[0];
4400        int d = coords[3];
4401        ivec2 yRC = coords.yz;
4402
4403        // Fractional source index.
4404        vec2 sourceFracIndexRC = ${m};
4405
4406        // Compute the coordinators of nearest neighbor point.
4407        ivec2 sourceNearestRC = ivec2(
4408          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
4409        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
4410
4411        setOutput(newValue);
4412      }
4413    `}}class KP{constructor(e,t,r,s,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,o,l,p]=e;this.outputShape=[i,t,r,p];const c=[s&&t>1?o-1:o,s&&r>1?l-1:l],h=[s&&t>1?t-1:t,s&&r>1?r-1:r],d=s?"0.5":"0.0";let m;m=a?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
4414      const vec3 effectiveInputOverOutputRatioRC = vec3(
4415          ${c[0]/h[0]},
4416          ${c[1]/h[1]},
4417          ${c[1]/h[1]});
4418      const vec3 inputShapeRC = vec3(${o}.0, ${l}.0,
4419                                     ${l}.0);
4420
4421      float getAValue(int b, int r, int c, int d) {
4422        return getChannel(getA(b, r, c, d), vec2(c, d));
4423      }
4424
4425      void main() {
4426        ivec4 coords = getOutputCoords();
4427        int b = coords[0];
4428        int d = coords[3];
4429        // Calculate values for next column in yRC.z.
4430        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
4431
4432        // Fractional source index.
4433        vec3 sourceFracIndexRC = ${m};
4434
4435        // Compute the coordinators of nearest neighbor point.
4436        ivec3 sourceNearestRC = ivec3(
4437          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
4438
4439        // Should we calculate next column and row elements in 2x2 packed cell.
4440        bool hasNextCol = d < ${p-1};
4441        bool hasNextRow = coords.z < ${r-1};
4442
4443        vec4 newValue = vec4(
4444          getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
4445          hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
4446                     : 0.0,
4447          hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
4448                     : 0.0,
4449          (hasNextRow && hasNextCol) ?
4450            getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
4451
4452        setOutput(newValue);
4453      }
4454    `}}const qP={kernelName:Es,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,halfPixelCenters:i,size:o}=r,[l,p]=o,c=xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new KP(s.shape,l,p,a,i):new jP(s.shape,l,p,a,i);return t.runWebGLProgram(c,[s],s.dtype)}};class XP{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,a]=t,[,i,o]=e,l=[r&&i>1?s-1:s,r&&o>1?a-1:a],p=[r&&i>1?i-1:i,r&&o>1?o-1:o],c=l[0]/p[0],h=l[1]/p[1],d=1/c,m=1/h,g=2*Math.ceil(d)+2,y=2*Math.ceil(m)+2;this.userCode=`
4455      void main() {
4456        ivec4 coords = getOutputCoords();
4457        int b = coords[0];
4458        int d = coords[3];
4459        int r = coords[1];
4460        int c = coords[2];
4461
4462        float accumulator = 0.0;
4463
4464        const float heightScale = float(${c});
4465        const float widthScale = float(${h});
4466
4467        const float invHeightScale = float(${d});
4468        const float invWidthScale = float(${m});
4469
4470        const int winHeight = int(${g});
4471        const int winWidth = int(${y});
4472
4473        // Compute bounds for where in dy we will look
4474        float startRLerp = floor(float(r) * invHeightScale);
4475        int startDyR = int(floor(startRLerp - float(winHeight / 2)));
4476
4477        float startCLerp = floor(float(c) * invWidthScale);
4478        int startDyC = int(floor(startCLerp - float(winWidth / 2)));
4479
4480        // Loop over dy
4481        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
4482          int dyR = dyROffset + startDyR;
4483
4484          // Guard against the window exceeding the bounds of dy
4485          if (dyR < 0 || dyR >= ${i}) {
4486            continue;
4487          }
4488
4489          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
4490            int dyC = dyCOffset + startDyC;
4491
4492            // Guard against the window exceeding the bounds of dy
4493            if (dyC < 0 || dyC >= ${o}) {
4494              continue;
4495            }
4496
4497            float sourceFracRow =
4498              float(${l[0]}) *
4499                (float(dyR) / float(${p[0]}));
4500
4501            float sourceFracCol =
4502                float(${l[1]}) *
4503                  (float(dyC) / float(${p[1]}));
4504
4505            int sourceNearestRow = int(min(
4506                float(int(${s}) - 1),
4507                ${r} ? float(round(sourceFracRow)) :
4508                                  float(floor(sourceFracRow))));
4509
4510            int sourceNearestCol = int(min(
4511                float(int(${a}) - 1),
4512                ${r} ? float(round(sourceFracCol)) :
4513                                  float(floor(sourceFracCol))));
4514
4515            if (r == sourceNearestRow && c == sourceNearestCol) {
4516              accumulator += getDy(b, dyR, dyC, d);
4517            }
4518          }
4519        }
4520        // End loop over dy
4521
4522        setOutput(accumulator);
4523      }
4524    `}}const YP={kernelName:wl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:i}=r,o=new XP(a.shape,s.shape,i);return t.runWebGLProgram(o,[a],a.dtype)}};class ZP{constructor(e,t){this.variableNames=["x"];const r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=e,r===1)return void(this.userCode=`
4525        void main() {
4526          int coord = getOutputCoords();
4527          setOutput(getX(${e[0]} - coord - 1));
4528        }
4529      `);const s=e.map((i,o)=>(l=>t.indexOf(l)!==-1&&e[l]!==1?`${e[l]} - coords[${l}] - 1`:`coords[${l}]`)(o)).join(","),a=Xn(r);this.userCode=`
4530      void main() {
4531        ${a} coords = getOutputCoords();
4532        setOutput(getX(${s}));
4533      }
4534    `}}class QP{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=e;const s=qs("rc",r),a=`${s[r-1]} + 1 < ${this.outputShape[r-1]}`,i=`${s[r-2]} + 1 < ${this.outputShape[r-2]}`,o=Xn(r);function l(p){const c=e.map((h,d)=>function(m,g){return t.indexOf(m)!==-1&&e[m]!==1?`${e[m]} - ${g[m]} - 1`:`${g[m]}`}(d,p));return`getChannel(getX(${c.join(",")}), vec2(${c.slice(-2).join(",")}))`}this.userCode=r===1?`
4535        void main(){
4536          int rc = getOutputCoords();
4537          vec4 result = vec4(0.);
4538          result.r = getChannel(getX(${e[0]} - rc - 1),
4539            ${e[0]} - rc - 1);
4540          if(${a}){
4541              result.g = getChannel(getX(${e[0]} - (rc  + 1) - 1),
4542                ${e[0]} - (rc  + 1) - 1);
4543          }
4544          setOutput(result);
4545        }
4546      `:`
4547        void main() {
4548          ${o} rc = getOutputCoords();
4549          vec4 result = vec4(0.);
4550          result.r = ${function(p){return l(p)}(s.slice())};
4551          if(${a}){
4552            result.g = ${function(p){return p[r-1]="("+p[r-1]+" + 1)",l(p)}(s.slice())};
4553          }
4554          if(${i}) {
4555            result.b = ${function(p){return p[r-2]="("+p[r-2]+" + 1)",l(p)}(s.slice())};
4556            if(${a}) {
4557              result.a = ${function(p){return p[r-1]="("+p[r-1]+" + 1)",p[r-2]="("+p[r-2]+" + 1)",l(p)}(s.slice())};
4558            }
4559          }
4560          setOutput(result);
4561        }
4562    `}}const JP={kernelName:Nl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dims:a}=r,i=s.shape.length,o=Oe(a,s.shape);if(i===0)return Ra({inputs:{x:s},backend:t});const l=xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new QP(s.shape,o):new ZP(s.shape,o);return t.runWebGLProgram(l,[s],s.dtype)}};class eB{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const r=e[1],s=e[2];this.outputShape=e;let a="";a=typeof t=="number"?`float outputValue = ${t.toFixed(2)};`:`
4563        vec3 fill = vec3(${t.join(",")});
4564        float outputValue = fill[coords[3]];`,this.userCode=`
4565        void main() {
4566          ivec4 coords = getOutputCoords();
4567          int x = coords[2];
4568          int y = coords[1];
4569          float coordXFloat = (float(x) - params[0]) * params[3] -
4570            (float(y) - params[1]) * params[2];
4571          float coordYFloat = (float(x) - params[0]) * params[2] +
4572            (float(y) - params[1]) * params[3];
4573          int coordX = int(round(coordXFloat + params[0]));
4574          int coordY = int(round(coordYFloat + params[1]));
4575          ${a}
4576          if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${r}) {
4577            outputValue = getImage(coords[0], coordY, coordX, coords[3]);
4578          }
4579          setOutput(outputValue);
4580        }
4581    `}}const tB={kernelName:Xh,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:r}=n,{radians:s,fillValue:a,center:i}=e,o=t,l=new eB(r.shape,a),[p,c]=V0(i,r.shape[1],r.shape[2]),h=[[p,c,Math.sin(s),Math.cos(s)]];return o.runWebGLProgram(l,[r],r.dtype,h)}},nB=Cn({opSnippet:`
4582  // OpenGL ES does not support round function.
4583  // The algorithm is based on banker's rounding.
4584  float base = floor(x);
4585  if ((x - base) < 0.5) {
4586    return floor(x);
4587  } else if ((x - base) > 0.5) {
4588    return ceil(x);
4589  } else {
4590    if (mod(base, 2.0) == 0.0) {
4591      return base;
4592    } else {
4593      return base + 1.0;
4594    }
4595  }
4596`}),rB={kernelName:Fo,backendName:"webgl",kernelFunc:nB},sB=Cn({opSnippet:"return inversesqrt(x);",cpuKernelImpl:yM}),aB={kernelName:lu,backendName:"webgl",kernelFunc:sB};class jx{constructor(e,t,r,s,a,i,o=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;const p=Xn(a.length),c=Xn(i.length);let h="";r===1?h="i":r===2&&(h="i, j");const d=`getIndices(${h})`;let m="";s===1?m="i":s===2&&(m="i, coords[1]");const g=`getUpdates(${m})`;let y="";l&&(y="coords[0], coords[1]");const w=`getDefaultValue(${y})`,v=t>1?"strides[j]":"strides";this.userCode=`
4597        ${p} strides = ${p}(${a});
4598
4599        void main() {
4600          ${c} coords = getOutputCoords();
4601          float sum = 0.0;
4602          bool found = false;
4603          for (int i = 0; i < ${e}; i++) {
4604            int flattenedIndex = 0;
4605            for (int j = 0; j < ${t}; j++) {
4606              int index = round(${d});
4607              flattenedIndex += index * ${v};
4608            }
4609            if (flattenedIndex == coords[0]) {
4610              sum += ${g};
4611              found = true;
4612            }
4613          }
4614          setOutput(mix(${w}, sum, float(found)));
4615        }
4616      `}}class iB{constructor(e,t,r,s,a,i,o=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=i;const p=Xn(a.length),c=Xn(i.length);let h="";r===1?h="i":r===2&&(h="i, j");const d=`getIndices(${h})`;let m="";s===1?m="i":s===2&&(m="i, coords[1]");const g=`getUpdates(${m})`;let y="";l&&(y="coords[0], coords[1]");const w=`getDefaultValue(${y})`,v=t>1?"strides[j]":"strides",N=t>1?"strides[j + 1]":"strides";this.userCode=`
4617        ${p} strides = ${p}(${a});
4618
4619        void main() {
4620          ${c} coords = getOutputCoords();
4621          vec4 sum = vec4(0.);
4622          vec4 found = vec4(0.);
4623          for (int i = 0; i < ${e}; i+=2) {
4624            ivec2 flattenedIndex = ivec2(0);
4625            for (int j = 0; j < ${t}; j+=2) {
4626              ivec4 index = round(${d});
4627              flattenedIndex += index.xz * ${v};
4628              if (j + 1 < ${t}) {
4629                flattenedIndex += index.yw * ${N};
4630              }
4631            }
4632            if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
4633                flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
4634              vec4 updVals = ${g};
4635              if (flattenedIndex[0] == coords[0]) {
4636                sum.xy += updVals.xy;
4637                found.xy = vec2(1.);
4638              } else if (flattenedIndex[0] == coords[0] + 1) {
4639                sum.zw += updVals.xy;
4640                found.zw = vec2(1.);
4641              }
4642              if (flattenedIndex[1] == coords[0]) {
4643                sum.xy += updVals.zw;
4644                found.xy = vec2(1.);
4645              } else if (flattenedIndex[1] == coords[0] + 1) {
4646                sum.zw += updVals.zw;
4647                found.zw = vec2(1.);
4648              }
4649            }
4650          }
4651          setOutput(mix(${w}, sum, found));
4652        }
4653      `}}const oB={kernelName:Oc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s,updates:a}=e,{shape:i}=r,{sliceRank:o,numUpdates:l,sliceSize:p,strides:c,outputSize:h}=Dr(0,s,i),d=[h/p,p];if(h===0)return t.makeTensorInfo(i,s.dtype);const m=It({inputs:{x:s},backend:t,attrs:{shape:[l,o]}}),g=It({inputs:{x:a},backend:t,attrs:{shape:[l,p]}}),y=t.makeTensorInfo([],"float32",new Float32Array([0]));let w;w=xe().getBool("WEBGL_PACK")?new iB(l,o,m.shape.length,g.shape.length,c,d):new jx(l,o,m.shape.length,g.shape.length,c,d);
4653const v=t.runWebGLProgram(w,[g,m,y],g.dtype),N=It({inputs:{x:v},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(v),t.disposeIntermediateTensorInfo(y),N}};class uB{constructor(e,t,r,s){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,r];const a=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=xe().getNumber("WEBGL_VERSION")===2?"while (left < right) {":a,o=s==="left"?"<":"<=";this.userCode=`
4654       int findBound(int batch, float value) {
4655         int left = 0;
4656         int right = numInputs;
4657         int mid;
4658         ${i}
4659           mid = (left + right) / 2;
4660           if (getSortedSequence(batch, mid) ${o} value) {
4661             left = mid + 1;
4662           } else {
4663             right = mid;
4664           }
4665         }
4666         return right;
4667       }
4668
4669       void main() {
4670         ivec2 coords = getOutputCoords();
4671         int batch = coords[0];
4672         int valueIndex = coords[1];
4673
4674         float value = getValues(batch, valueIndex);
4675
4676         setOutput(float(findBound(batch, value)));
4677       }
4678     `}}const lB={kernelName:cu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{sortedSequence:s,values:a}=e,{side:i}=r,o=new uB(s.shape[0],s.shape[1],a.shape[1],i),l=[[s.shape[1]]];return t.runWebGLProgram(o,[s,a],"int32",l)}};class cB{constructor(e,t,r){let s,a;if(this.variableNames=["c","a","b"],this.outputShape=t,r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)a="resRC",s="resRC";else{const o=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],p=[];for(let c=0;c<t.length;c++)p.push(`${o[c]}`),c<e&&l.push(`${o[c]}`);s=l.join(),a=p.join()}const i=Xn(r);this.userCode=`
4679      void main() {
4680        ${i} resRC = getOutputCoords();
4681        float cVal = getC(${s});
4682        if (cVal >= 1.0) {
4683          setOutput(getA(${a}));
4684        } else {
4685          setOutput(getB(${a}));
4686        }
4687      }
4688    `}}const hB={kernelName:Il,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{condition:r,t:s,e:a}=e,i=new cB(r.shape.length,s.shape,s.shape.length);return t.runWebGLProgram(i,[r,s,a],Cs(s.dtype,a.dtype))}},dB=Cn({opSnippet:`
4689  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
4690  // see: https://arxiv.org/abs/1706.02515
4691  float scaleAlpha = ${cg};
4692  float scale = ${hg};
4693  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
4694`}),pB={kernelName:Sl,backendName:"webgl",kernelFunc:dB},fB=Cn({opSnippet:cp+`
4695  return 1.0 / (1.0 + exp(-1.0 * x));
4696`,packedOpSnippet:`
4697  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
4698  bvec4 isNaN = isnan(x);
4699
4700  result.r = isNaN.r ? x.r : result.r;
4701  result.g = isNaN.g ? x.g : result.g;
4702  result.b = isNaN.b ? x.b : result.b;
4703  result.a = isNaN.a ? x.a : result.a;
4704
4705  return result;
4706`,cpuKernelImpl:xM}),mB={kernelName:du,backendName:"webgl",kernelFunc:fB},gB=Cn({opSnippet:`
4707  if (isnan(x)) { return 0.0; }
4708  return sign(x);
4709`}),yB={kernelName:hu,backendName:"webgl",kernelFunc:gB},bB=Cn({opSnippet:cp+`
4710  return sin(x);
4711`,packedOpSnippet:`
4712  vec4 result = sin(x);
4713  bvec4 isNaN = isnan(x);
4714  ${Mh}
4715  return result;
4716`}),xB={kernelName:zi,backendName:"webgl",kernelFunc:bB},wB=Cn({opSnippet:`
4717  float e2x = exp(x);
4718  return (e2x - 1.0 / e2x) / 2.0;
4719`}),vB={kernelName:Mo,backendName:"webgl",kernelFunc:wB},kB=Cn({opSnippet:`
4720  float epsilon = 1.1920928955078125e-7;
4721  float threshold = log(epsilon) + 2.0;
4722
4723  bool too_large = x > -threshold;
4724  bool too_small = x < threshold;
4725
4726  float result;
4727  float exp_x = exp(x);
4728
4729  if (too_large){
4730    result = x;
4731  }
4732  else if (too_small){
4733    result = exp_x;
4734  }
4735  else{
4736    result = log(exp_x + 1.0);
4737  }
4738  return result;
4739`}),NB={kernelName:pu,backendName:"webgl",kernelFunc:kB},IB={kernelName:Tl,backendName:"webgl",kernelFunc:n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,paddings:i}=r;A(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const o=a.reduce((v,N)=>v*N),l=[[0,0]];l.push(...i);for(let v=1+a.length;v<s.shape.length;++v)l.push([0,0]);
4739const p=[],c=QS({inputs:{x:s},backend:t,attrs:{paddings:l,constantValue:0}}),h=pf(c.shape,a,o,!1),d=ff(h.length,a.length,!1),m=mf(c.shape,a,o,!1),g=It({inputs:{x:c},backend:t,attrs:{shape:h}}),y=Xs({inputs:{x:g},backend:t,attrs:{perm:d}}),w=It({inputs:{x:y},backend:t,attrs:{shape:m}});return p.push(c),p.push(g),p.push(y),p.forEach(v=>t.disposeIntermediateTensorInfo(v)),w}},SB={kernelName:Cl,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{indices:r,values:s,denseShape:a,defaultValue:i}=e;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
4740         ${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
4741         ${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
4742         ${s.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
4743        ${i.shape}`);const o=t.readSync(r.dataId),l=t.readSync(s.dataId),p=t.readSync(a.dataId),c=t.readSync(i.dataId)[0],[h,d,m,g,y]=vM(o,r.shape,r.dtype,l,s.dtype,p,c);return[t.makeTensorInfo(d,r.dtype,h),t.makeTensorInfo([d[0]],s.dtype,m),t.makeTensorInfo([g.length],"bool",new Uint8Array(g.map(w=>Number(w)))),t.makeTensorInfo([y.length],r.dtype,new Int32Array(y))]}},TB={kernelName:$l,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{inputIndices:r,inputShape:s,newShape:a}=e;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(t.readSync(s.dataId)),o=t.readSync(r.dataId),l=Array.from(t.readSync(a.dataId)),[p,c,h]=kM(o,r.shape,r.dtype,i,l);return[t.makeTensorInfo(c,r.dtype,p),t.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},EB={kernelName:qh,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
4744              ${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
4745              ${a.shape}`);const i=t.readSync(r.dataId),o=t.readSync(s.dataId),l=t.readSync(a.dataId),[p,c]=aS(i,r.shape,r.dtype,o,l,!0);return t.makeTensorInfo(c,r.dtype,p)}},CB={kernelName:gu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
4746             ${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
4747             ${a.shape}`);const i=t.readSync(r.dataId),o=t.readSync(s.dataId),l=t.readSync(a.dataId),[p,c]=aS(i,r.shape,r.dtype,o,l);return t.makeTensorInfo(c,r.dtype,p)}},$B={kernelName:yu,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{sparseIndices:s,sparseValues:a,defaultValue:i}=e,{outputShape:o}=r,{sliceRank:l,numUpdates:p,sliceSize:c,strides:h,outputSize:d}=Dr(0,s,o),m=!1;if(a.dtype==="string"){const v=t.bufferSync(s),N=t.bufferSync(a),T=gr(t.readSync(i.dataId)[0]),$=bM(v,N,o,d,c,p,l,h,T,m);return t.makeTensorInfo(o,$.dtype,$.values)}const g=new jx(p,l,s.shape.length,a.shape.length,h,[d,1],m),y=t.runWebGLProgram(g,[a,s,i],a.dtype),w=It({inputs:{x:y},backend:t,attrs:{shape:o}});return t.disposeIntermediateTensorInfo(y),w}},AB={kernelName:El,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{numOrSizeSplits:a,axis:i}=r,o=Oe(i,s.shape)[0],l=r1(s,a,o),p=s.shape.length,c=new Array(p).fill(0),h=s.shape.slice();return l.map(d=>{const m=[...h];m[o]=d;const g=hp({inputs:{x:s},backend:t,attrs:{begin:c,size:m}});return c[o]+=d,g})}},eT="return sqrt(x);",RB=Cn({opSnippet:eT,packedOpSnippet:eT,cpuKernelImpl:NM}),_B={kernelName:fu,backendName:"webgl",kernelFunc:RB},DB=Cn({opSnippet:"return x * x;"}),FB={kernelName:zc,backendName:"webgl",kernelFunc:DB}
4747,tT="return (a - b) * (a - b);",MB=Is({opSnippet:tT,packedOpSnippet:tT}),OB={kernelName:bu,backendName:"webgl",kernelFunc:MB},LB={kernelName:Al,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");const a=Pu(t.readSync(s.dataId)),i=IM(a,"string",r);return t.makeTensorInfo(s.shape,"string",i)}},zB={kernelName:ra,backendName:"webgl",kernelFunc:function({inputs:n,attrs:e,backend:t}){const{x:r}=n,s=yi+`
4748    return x > 0.0 ? 1.0 : float(${e.alpha});
4749  `,a=new Qo(r.shape,s);return t.runWebGLProgram(a,[r],r.dtype)}};class PB{constructor(e,t,r){this.variableNames=["x"],this.outputShape=r;const s=r.length,a=Xn(r.length),i=Xn(r.length);let o="";if(s===1)o="coords * strides + begin";else{let l=0;o=r.map((p,c)=>(l++,r.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${l-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
4750      ${a} begin = ${a}(${e});
4751      ${a} strides = ${a}(${t});
4752
4753      void main() {
4754        ${i} coords = getOutputCoords();
4755        setOutput(getX(${o}));
4756      }
4757    `}}const BB={kernelName:Pi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,end:i,strides:o,beginMask:l,endMask:p,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=r,{finalShapeSparse:m,finalShape:g,isIdentity:y,sliceDim0:w,isSimpleSlice:v,begin:N,end:T,strides:$}=pr(s.shape,a,i,o,l,p,c,h,d);let _;if(y)_=It({inputs:{x:s},backend:t,attrs:{shape:g}});else if(w||v){A(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const z=u(N,T,$),O=hp({inputs:{x:s},backend:t,attrs:{begin:N,size:z}});_=It({inputs:{x:O},backend:t,attrs:{shape:g}}),t.disposeIntermediateTensorInfo(O)}else if(t.shouldExecuteOnCPU([s])){const z=t.readSync(s.dataId),O=ln(s.shape,s.dtype,z),V=SM(m,O,$,N);_=t.makeTensorInfo(g,s.dtype,V.values)}else{const z=new PB(N,$,m);_=t.runWebGLProgram(z,[s],s.dtype)}const L=It({inputs:{x:_},backend:t,attrs:{shape:g}});return t.disposeIntermediateTensorInfo(_),L}},VB={kernelName:rs,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:p}=r,{data:c,dataSplits:h}=e,d=t.readSync(c.dataId),m=t.readSync(h.dataId),[g,y]=TM(d,m,s,a,i,o,l,p);return[t.makeTensorInfo([g.length],"string",g),t.makeTensorInfo(h.shape,"int32",y)]}},UB={kernelName:Bi,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{skipEmpty:s}=r,{input:a,delimiter:i}=e;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=t.readSync(a.dataId),l=t.readSync(i.dataId)[0],[p,c,h]=EM(o,l,s),d=c.length;return[t.makeTensorInfo([d,2],"int32",p),t.makeTensorInfo([d],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(h))]}},WB={kernelName:ss,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{numBuckets:s}=r,{input:a}=e;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=t.readSync(a.dataId),o=CM(i,s);return t.makeTensorInfo(a.shape,"int32",o)}},GB=Cn({opSnippet:"return tan(x);"}),HB={kernelName:xu,backendName:"webgl",kernelFunc:GB},jB=Cn({opSnippet:`
4758  float e2x = exp(-2.0 * abs(x));
4759  return sign(x) * (1.0 - e2x) / (1.0 + e2x);
4760`}),KB={kernelName:wu,backendName:"webgl",kernelFunc:jB},qB={kernelName:Li,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{tensor:s,indices:a,updates:i}=e,{sliceRank:o,numUpdates:l,sliceSize:p,strides:c,outputSize:h}=Dr(0,a,s.shape),d=[h/p,p];if(h===0)return t.makeTensorInfo(s.shape,a.dtype);const m=It({inputs:{x:a},backend:t,attrs:{shape:[l,o]}}),g=It({inputs:{x:i},backend:t,attrs:{shape:[l,p]}}),y=It({inputs:{x:s},backend:t,attrs:{shape:d}}),w=new jx(l,o,m.shape.length,g.shape.length,c,d,!1,!0),v=t.runWebGLProgram(w,[g,m,y],y.dtype),N=It
vendor: 6,582 bytes, lines 4760-4839
4760({inputs:{x:v},backend:t,attrs:{shape:s.shape}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(v),N}};class XB{constructor(e,t){this.variableNames=["A"];const r=new Array(e.length);for(let i=0;i<r.length;i++)r[i]=e[i]*t[i];this.outputShape=r,this.rank=r.length;const s=Xn(this.rank),a=function(i){const o=i.length;if(o>5)throw Error(`Tile for rank ${o} is not yet supported`);if(o===1)return`imod(resRC, ${i[0]})`;const l=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],p=[];for(let c=0;c<i.length;c++)p.push(`imod(${l[c]}, ${i[c]})`);return p.join()}(e);this.userCode=`
4761      void main() {
4762        ${s} resRC = getOutputCoords();
4763        setOutput(getA(${a}));
4764      }
4765    `}}function nT(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){const o=t.readSync(s.dataId),l=s.dtype==="string"?o.map(h=>gr(h)):o,p=ln(s.shape,s.dtype,l),c=AM(p,a);return t.makeTensorInfo(c.shape,c.dtype,c.values)}const i=new XB(s.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}const YB={kernelName:vu,backendName:"webgl",kernelFunc:nT};class ZB{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
4766       void main() {
4767         ivec2 coords = getOutputCoords();
4768         int batch = coords[0];
4769         int elemIdx = coords[1];
4770
4771         // We compare elements pair-wise within a group of size 2 * inc.
4772         // The comparing rule for each group alternates between ascending
4773         // and descending. Within each group, we compare each pair at
4774         // positions i and i+inc. To decide whether an element at position i
4775         // is x0 or x1, we mod it by 2 * inc, if the result is smaller than
4776         // inc, it is in the first half of the group, we denote it as x0,
4777         // otherwise we denote it as x1.
4778         // For example, as shown in the Bitonic top K paper referenced above,
4779         // Figure5(a) shows that element[1] is in the
4780         // second half of the group when group size is 2, but it is in the
4781         // first half of the group when group size is 4.
4782
4783         bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
4784         int i = isFirstInPair ? elemIdx : elemIdx - inc;
4785
4786         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
4787         int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
4788         float x0 = i0 < n ? getX(batch, i0) : negativeInf;
4789         float x1 = i1 < n ? getX(batch, i1) : negativeInf;
4790
4791         // Denotes which direction indices are in (ascending or descending).
4792         bool reverse = imod(elemIdx, 2 * dir) >= dir;
4793         bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
4794         if (reverse == isGreater) { // Elements in opposite order of direction
4795           int iTemp = i0;
4796           i0 = i1;
4797           i1 = iTemp;
4798         }
4799         if (isFirstInPair) {
4800            setOutput(float(i0));
4801         } else {
4802            setOutput(float(i1));
4803         }
4804       }
4805     `}}class QB{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
4806    void main() {
4807         // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
4808         ivec2 coords = getOutputCoords();
4809         int batch = coords[0];
4810         int elemIdx = coords[1];
4811
4812         // The output size is half of the previous size.
4813         // If the previous sequence is | | | | _ _ _ _  | | | |  _ _ _ _ (k=4),
4814         // we only need to output the indices at positions |, the indices at
4815         // positions _ can be thrown away, see Figure5(b) After Phase 2
4816         // (Merge phase) in the Bitonic Top K paper referenced above.
4817         // For example, the paper shows we only need to output the orange bars.
4818         // The output sequence should look like this | | | | | | | |.
4819         // Because the sequence is halved, to map the output index back
4820         // to the previous sequence to find the corresponding value,
4821         // we need to double the index. When we double the index,
4822         // we basically interpolate a position, so 2i looks like
4823         // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
4824         // of each 2k positions by - elemIdx % k. E.g. for output at
4825         // index 4,5,6,7, we want to get the corresponding element at
4826         // original index 8,9,10,11, for output at index 8,9,10,11,
4827         // we want to get the corresponding element at original index
4828         // 16,17,18,19, so on and so forth.
4829
4830         int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
4831         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
4832         int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
4833
4834         float x0 = getX(batch, i0);
4835         float x1 = i1 < n ? getX(batch, i1) : x0;
4836
4837         setOutput(x0 >= x1 ? float(i0) : float(i1));
4838       }
4839     `}}function Lh(n,e){e!==null&&n.disposeIntermediateTensorInfo(e)}function rT(n){let e=1;for(;e<n;)e*=2;return e}const JB={kernelName:Pc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{k:a,sorted:i}=r,o=xe().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=xe().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),p=s.shape,c=p[p.length-1];if(t.shouldExecuteOnCPU([s])||c<o||a>l){const V=t.readSync(s.dataId),[U,X]=RM(V,p,s.dtype,a,i);return[t.makeTensorInfo(U.shape,U.dtype,U.values),t.makeTensorInfo(X.shape,X.dtype,X.values)]}if(a===0)return p[p.length-1]=0,[t.makeTensorInfo(p,s.dtype,[]),t.makeTensorInfo(p,"int32",[])];if(c===1)return[s,Zf({attrs:{shape:p,dtype:"int32",value:0},backend:t})];const h=t.texData.get(s.dataId),d=h!==null&&h.isPacked,m=d?t.unpackTensor(s):s,g=j(p)/c,y=It({inputs:{x:m},attrs:{shape:[g,c]},backend:t});d&&Lh(t,m);const w=rT(a),v=rT(c);let N=null;const T=()=>N===null?[y,y]:[y,N],$=(V,U,X)=>{const ne=T(),ae=new ZB(X),Ie=[[c],[N===null?1:0],[Number.NEGATIVE_INFINITY],[V],[U]],me=N;N=t.runWebGLProgram(ae,ne,"int32",Ie),Lh(t,me)};for(let V=1;V<w;V*=2){const U=2*V;for(let X=V;X>=1;X/=2)$(U,X,[g,v])}for(let V=v;V>w;V/=2){const U=T(),X=new QB([g,V/2]),ne=[[c],[N===null?1:0],[w]],ae=N;N=t.runWebGLProgram(X,U,"int32",ne),Lh(t,ae);const Ie=w/2,me=2*Ie;for(let we=Ie;we>=1;we/=2)$(me,we,N.shape)}let _=N;N=hp({inputs:{x:N},backend:t,attrs:{begin:0,size:[g,a]}}),Lh(t,_);
4839let L=jS({inputs:{x:y,indices:N},backend:t,attrs:{axis:1,batchDims:1}});Lh(t,y);const z=p.slice(0,-1);z.push(a),_=N,N=It({inputs:{x:N},attrs:{shape:z},backend:t}),Lh(t,_);const O=L;return L=It({inputs:{x:L},attrs:{shape:z},backend:t}),Lh(t,O),[L,N]}};class e6{constructor(e,t,r,s,a,i){this.variableNames=["Image","Transforms"],this.outputShape=i;const o=r==="nearest"?1:2;let l;switch(s){case"constant":default:l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4}this.userCode=`
4840            float mapCoord(float outCoord, float len) {
4841              float inCoord = outCoord;
4842              if(${l} == 2) {
4843                if (inCoord < 0.0) {
4844                  if (len <= 1.0) {
4845                    inCoord = 0.0;
4846                  } else {
4847                    float sz2 = 2.0 * len;
4848                    if (inCoord < sz2) {
4849                      inCoord = sz2 * float(int(float(-inCoord / sz2))) +
4850                      inCoord;
4851                    }
4852                    inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
4853                  }
4854                } else if (inCoord > len - 1.0) {
4855                  if (len <= 1.0) {
4856                    inCoord = 0.0;
4857                  } else {
4858                    float sz2 = 2.0 * len;
4859                    inCoord -= sz2 * float(int(float(inCoord / sz2)));
4860                    if (inCoord >= len) {
4861                      inCoord = sz2 - inCoord - 1.0;
4862                    }
4863                  }
4864                }
4865                return clamp(inCoord, 0.0, len - 1.0);
4866              } else if (${l} == 3) {
4867                if (inCoord < 0.0) {
4868                  if (len <= 1.0) {
4869                    inCoord = 0.0;
4870                  } else {
4871                    float sz = len - 1.0;
4872                    inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
4873                  }
4874                } else if (inCoord > len - 1.0) {
4875                  if (len <= 1.0) {
4876                    inCoord = 0.0;
4877                  } else {
4878                    float sz = len - 1.0;
4879                    inCoord -= len * float(int(float(inCoord / sz)));
4880                  }
4881                }
4882                return clamp(inCoord, 0.0, len - 1.0);
4883              } else if (${l} == 4) {
4884                return clamp(outCoord, 0.0, len - 1.0);
4885              } else {
4886                return outCoord;
4887              }
4888            }
4889
4890            float readWithFillValue(int batch, int coordY, int coordX,
4891              int channel) {
4892              float outputValue;
4893              if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
4894                  outputValue = getImage(batch, coordY, coordX, channel);
4895              } else {
4896                outputValue = float(${a});
4897              }
4898              return outputValue;
4899            }
4900
4901            void main() {
4902              ivec4 coords = getOutputCoords();
4903              float outputValue;
4904              int batch = coords[0];
4905              int x = coords[2];
4906              int y = coords[1];
4907              int channel = coords[3];
4908              float xf = float(x);
4909              float yf = float(y);
4910              float a1 = getTransforms(batch, 0);
4911              float a2 = getTransforms(batch, 1);
4912              float a3 = getTransforms(batch, 2);
4913              float b1 = getTransforms(batch, 3);
4914              float b2 = getTransforms(batch, 4);
4915              float b3 = getTransforms(batch, 5);
4916              float c1 = getTransforms(batch, 6);
4917              float c2 = getTransforms(batch, 7);
4918              float projection = c1 * xf + c2 * yf + 1.0;
4919              if (projection == 0.0) {
4920                outputValue = float(${a});
4921              } else {
4922                float inX = (a1 * xf + a2 * yf + a3) / projection;
4923                float inY = (b1 * xf + b2 * yf + b3) / projection;
4924                float mapX = mapCoord(inX, float(${t}));
4925                float mapY = mapCoord(inY, float(${e}));
4926
4927                if (${o} == 1) {
4928                  int coordY = int(round(mapY));
4929                  int coordX = int(round(mapX));
4930                  outputValue = readWithFillValue(batch, coordY, coordX,
4931                    channel);
4932                } else {
4933                  float yFloor = floor(mapY);
4934                  float xFloor = floor(mapX);
4935                  float yCeil = yFloor + 1.0;
4936                  float xCeil = xFloor + 1.0;
4937                  float valueYFloor = (xCeil - mapX) *
4938                  readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
4939                  (mapX - xFloor) *
4940                  readWithFillValue(batch, int(yFloor), int(xCeil), channel);
4941                  float valueYCeil = (xCeil - mapX) *
4942                  readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
4943                  (mapX - xFloor) *
4944                  readWithFillValue(batch, int(yCeil), int(xCeil), channel);
4945                  outputValue = (yCeil - mapY) * valueYFloor +
4946                  (mapY - yFloor) * valueYCeil;
4947                }
4948              }
4949              setOutput(outputValue);
4950            }
4951        `}}const t6={kernelName:Bc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{image:s,transforms:a}=e,{interpolation:i,fillMode:o,fillValue:l,outputShape:p}=r,[c,h,d,m]=s.shape,[g,y]=p??[h,d],w=new e6(h,d,i,o,l,[c,g,y,m]);return t.runWebGLProgram(w,[s,a],"float32")}},n6={kernelName:Vc,backendName:"webgl",kernelFunc:function(n){const{inputs:e,attrs:t,backend:r}=n,{axis:s}=t,{x:a}=e;sp(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=r.readSync(a.dataId),{outputValues:o,outputShape:l,indices:p}=_M(i,s,a.shape,a.dtype);return[r.makeTensorInfo(l,a.dtype,o),r.makeTensorInfo([p.length],"int32",p)]}},r6={kernelName:na,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{value:s}=e;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s,o=i.shape.length,l=s.shape[a],p=new Array(o-1);let c=0;for(let y=0;y<o;y++)y!==a&&(p[c++]=i.shape[y]);const h=[],d=new Array(o).fill(0),m=i.shape.slice();m[a]=1;const g=new Array(l);for(let y=0;y<g.length;y++){d[a]=y;const w=hp({inputs:{x:i},backend:t,attrs:{begin:d,size:m}}),v=It({inputs:{x:w},backend:t,attrs:{shape:p}});g[y]=v,h.push(w)}return h.forEach(y=>t.disposeIntermediateTensorInfo(y)),g}};class s6{constructor(e,t){this.variableNames=["x","segmentIds"];const r=e.windowSize,s=e.batchSize,a=e.inSize,i=e.numSegments,o=i*Math.ceil(a/r);this.outputShape=[s,o];const l=4*Math.floor(r/4),p=r%4,c=`
4952        sumValue += dot(values, segFilter);
4953    `;let h="";a%r>0&&(h=`
4954        if (inIdx < 0 || inIdx >= ${a}) {
4955          return initializationValue;
4956        }
4957      `);let d="";a%r>0&&(d=`
4958        if (inIdx < 0 || inIdx >= ${a}) {
4959          return -1.0;
4960        }
4961      `),this.userCode=`
4962      const float initializationValue = 0.0;
4963
4964      float getValue(int batch, int inIdx) {
4965        ${h}
4966        return getX(batch, inIdx);
4967      }
4968
4969      float getSegmentIdAtIndex(int inIdx) {
4970        ${d}
4971        return getSegmentIds(inIdx);
4972      }
4973
4974      void main() {
4975        ivec2 coords = getOutputCoords();
4976        int batch = coords[0];
4977        int outIdx = coords[1];
4978        int inOffset = int(floor(float(outIdx) / float(
4979          ${i})) * float(${r}));
4980        int currentSeg = int(mod(float(outIdx), float(${i})));
4981
4982        float sumValue = 0.0;
4983
4984        for (int i = 0; i < ${l}; i += 4) {
4985          int inIdx = inOffset + i;
4986          vec4 values = vec4(
4987            getValue(batch, inIdx),
4988            getValue(batch, inIdx + 1),
4989            getValue(batch, inIdx + 2),
4990            getValue(batch, inIdx + 3)
4991          );
4992
4993          vec4 segFilter = vec4(
4994            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
4995            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
4996            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
4997            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
4998          );
4999
5000          ${c}
5001        }
5002
5003        int inIdx = inOffset + ${l};
5004        if (${p===1}) {
5005          vec4 values = vec4(
5006            getValue(batch, inIdx),
5007            initializationValue,
5008            initializationValue,
5009            initializationValue
5010          );
5011
5012          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
5013
5014          vec4 segFilter = vec4(
5015            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
5016            0,
5017            0,
5018            0
5019          );
5020
5021          ${c}
5022        } else if (${p===2}) {
5023          vec4 values = vec4(
5024            getValue(batch, inIdx),
5025            getValue(batch, inIdx + 1),
5026            initializationValue,
5027            initializationValue
5028          );
5029
5030          vec4 segFilter = vec4(
5031            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
5032            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
5033              0,
5034              0
5035          );
5036
5037          ${c}
5038        } else if (${p===3}) {
5039          vec4 values = vec4(
5040            getValue(batch, inIdx),
5041            getValue(batch, inIdx + 1),
5042            getValue(batch, inIdx + 2),
5043            initializationValue
5044          );
5045
5046          vec4 segFilter = vec4(
5047            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
5048            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
5049            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
5050            0
5051          );
5052
5053          ${c}
5054        }
5055        setOutput(sumValue);
5056      }
5057    `}}const a6={kernelName:mr,backendName:"webgl",kernelFunc:function(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,segmentIds:a}=e,{numSegments:i}=r,o=s.shape.length,l=[];let p=0;const c=Ir([p],o);let h=s;
5057c!=null&&(h=Xs({inputs:{x:s},backend:t,attrs:{perm:c}}),l.push(h),p=Or(1,o)[0]);const d=E2(h.shape,p,i),m=j([h.shape[p]]),g=It({inputs:{x:h},backend:t,attrs:{shape:[-1,m]}});l.push(g);const y=Kc(s.dtype),w=(T,$,_,L,z)=>{const O=T.shape[0],V=T.shape[1],U=T2(V,z),X=new s6({windowSize:U,inSize:V,batchSize:O,numSegments:z},$),ne=t.compileAndRun(X,[T,_],L);if(l.push(ne),ne.shape[1]===z)return ne;const ae=JS({backend:t,attrs:{start:0,stop:z,step:1,dtype:"float32"}}),Ie=nT({inputs:{x:ae},backend:t,attrs:{reps:[V/U]}});return l.push(ae),l.push(Ie),w(ne,$,Ie,L,z)},v=It({inputs:{x:w(g,"unsortedSegmentSum",a,y,i)},backend:t,attrs:{shape:d}});let N=v;if(c!=null){l.push(v);const T=Kl(c);N=Xs({inputs:{x:N},backend:t,attrs:{perm:T}})}return l.forEach(T=>t.disposeIntermediateTensorInfo(T)),N}},i6=[QM,JM,tO,rO,aO,uO,lO,cO,pO,fO,gO,bO,wO,kO,IO,SO,TO,$O,AO,RO,FO,zO,PO,BO,VO,GO,jO,XO,UM,ZO,tL,sL,lL,hL,dL,pL,fL,gL,bL,wL,vL,kL,NL,SL,TL,$L,AL,_L,FL,ML,LL,zL,BL,UL,WL,GL,jL,KL,XL,ZL,JL,tz,sz,az,iz,uz,cz,dz,fz,VM,mz,eL,yz,xz,vz,WM,Nz,Sz,Tz,Cz,Az,_z,Fz,Oz,Pz,Vz,Uz,Gz,Hz,jz,Xz,Yz,Zz,Qz,Jz,tP,sP,iP,hP,HM,pP,mP,yP,xP,UO,vP,NP,IP,EP,$P,GM,AP,RP,_P,DP,FP,WO,uP,OP,zP,BP,jM,WP,HP,qP,YP,JP,tB,rB,aB,oB,lB,hB,pB,mB,yB,xB,vB,LO,cP,NB,IB,SB,TB,EB,CB,$B,AB,_B,FB,OB,LB,zB,BB,VB,UB,WB,lP,YM,HB,KB,qB,YB,JB,t6,ZM,n6,r6,a6,kP];for(const n of i6)Wc(n);const o6={"tfjs-core":Qx,"tfjs-backend-cpu":jN,"tfjs-backend-webgl":dS,"tfjs-data":Kk,"tfjs-layers":Lg,"tfjs-converter":Ck,tfjs:"4.22.0"}},983:(Et,ye,Z)=>{Z.r(ye),Z.d(ye,{default:()=>ht});var Xe=Z(512),Vt=Z.n(Xe);function ht(){return Vt()('/*! For license information please see index.worker.js.LICENSE.txt */\n(()=>{var e={31:function(e,t,n){var r;!function(e,s){function a(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;
5057r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function o(e,t){var n=new a(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.xorwow=o}(0,e=n.nmd(e),n.amdD)},44:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,o)}u((r=r.apply(e,t||[])).next())})},s=this&&this.__generator||function(e,t){var n,r,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var i,o=a(n(382)),u="idle";self.onmessage=function(e){return r(void 0,void 0,void 0,function(){var t,n,r,a;return s(this,function(s){switch(s.label){case 0:switch(t=e.data,n=t.type,r=t.payload,n){case"init":return[3,1];case"step":return[3,3];case"click":return[3,6]}return[3,7];case 1:return[4,(i=new o.default).initialize()];case 2:return s.sent(),self.postMessage({type:"ready"}),u="idle",[3,8];case 3:return"idle"!==u?[3,5]:(u="inference",self.postMessage({type:"statusUpdate",status:u}),[4,i.step(r.frame,r.timestamp)]);case 4:a=s.sent(),r.timestamp,self.postMessage({type:"stepResult",result:a}),u="idle",self.postMessage({type:"statusUpdate",status:u}),s.label=5;case 5:return[3,8];case 6:return u="calib",self.postMessage({type:"statusUpdate",status:u}),i.handleClick(r.x,r.y),u="idle",self.postMessage({type:"statusUpdate",status:u}),[3,8];case 7:return console.warn("[WebEyeTrackWorker] Unknown message type: ".concat(n)),[3,8];case 8:return[2]}})})}},45:function(e,t,n){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&s(t,e,n[i]);return a(t,e),t}),o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,o)}u((r=r.apply(e,t||[])).next())})},u=this&&this.__generator||function(e,t){var n,r,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;
5057function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var l=i(n(951)),c=function(){function e(){this.model=null}return e.prototype.loadModel=function(){return o(this,void 0,void 0,function(){var e,t,n;return u(this,function(r){switch(r.label){case 0:e="".concat(self.location.origin,"/web/model.json"),r.label=1;case 1:return r.trys.push([1,3,,4]),t=this,[4,l.loadLayersModel(e)];case 2:return t.model=r.sent(),console.log("✅ BlazeGaze model loaded successfully"),[3,4];case 3:throw n=r.sent(),console.error("❌ Error loading BlazeGaze model from path:",e),console.error(n),n;case 4:return this.model.getLayer("cnn_encoder").trainable=!1,[2]}})})},e.prototype.predict=function(e,t,n){if(!this.model)throw new Error("Model not loaded. Call loadModel() first.");var r=[e,t,n],s=this.model.predict(r);return Array.isArray(s)?s[0]:s},e}();t.default=c},67:function(e,t,n){var r;!function(e,s){function a(e){var t=this;t.next=function(){var e,n,r=t.x,s=t.i;return e=r[s],n=(e^=e>>>7)^e<<24,n^=(e=r[s+1&7])^e>>>10,n^=(e=r[s+3&7])^e>>>3,n^=(e=r[s+4&7])^e<<7,e=r[s+7&7],n^=(e^=e<<13)^e<<9,r[s]=n,t.i=s+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new a(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&(r.x&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.xorshift7=o}(0,e=n.nmd(e),n.amdD)},108:()=>{},180:function(e,t,n){var r;!function(e,s){function a(e){var t,n=this,r=(t=4022871197,function(e){e=String(e);for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new a(e),r=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,r&&("object"==typeof r&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.alea=o}(0,e=n.nmd(e),n.amdD)},181:function(e,t,n){var r;!function(e,s){function a(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;
5057r++)t.x^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function o(e,t){var n=new a(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.xor128=o}(0,e=n.nmd(e),n.amdD)},234:()=>{},298:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeSVD=function(e){var t=console.warn;console.warn=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];var r=e[0];"string"==typeof r&&r.includes("autoTranspose")||t.apply(console,e)};var n=new r.SVD(e,{autoTranspose:!1});return console.warn=t,n};var r=n(673)},382:function(e,t,n){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&s(t,e,n[i]);return a(t,e),t}),o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,o)}u((r=r.apply(e,t||[])).next())})},u=this&&this.__generator||function(e,t){var n,r,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var c=i(n(951)),h=n(673),d=l(n(45)),p=l(n(743)),f=n(985),m=n(670),g=function(){function e(e,t){void 0===e&&(e=5),void 0===t&&(t=60),this.faceWidthComputed=!1,this.faceWidthCm=-1,this.perspectiveMatrixSet=!1,this.perspectiveMatrix=new h.Matrix(4,4),this.intrinsicsMatrixSet=!1,this.intrinsicsMatrix=new h.Matrix(3,3),this.affineMatrix=null,this.loaded=!1,this.latestMouseClick=null,this.latestGazeResult=null,this.calibData={supportX:[],supportY:[],timestamps:[],ptType:["calib"]},this.maxPoints=5,this.clickTTL=60,this.blazeGaze=new d.default,this.faceLandmarkerClient=new p.default,this.kalmanFilter=new m.KalmanFilter2D,this.maxPoints=e,this.clickTTL=t}return e.prototype.initialize=function(){return o(this,void 0,void 0,function(){return u(this,function(e){switch(e.label){case 0:return[4,this.faceLandmarkerClient.initialize()];case 1:return e.sent(),[4,this.blazeGaze.loadModel()];case 2:return e.sent(),this.loaded=!0,[2]}})})},e.prototype.pruneCalibData=function(){var e=this;c.tidy(function(){e.calibData.supportX.length>e.maxPoints&&(e.calibData.supportX=e.calibData.supportX.slice(-e.maxPoints),e.calibData.supportY=e.calibData.supportY.slice(-e.maxPoints),e.calibData.timestamps=e.calibData.timestamps.slice(-e.maxPoints),e.calibData.ptType=e.calibData.ptType.slice(-e.maxPoints));var t=Date.now(),n=1e3*e.clickTTL,r=e.calibData.timestamps.map(function(r,s){return t-r<=n||"click"!==e.calibData.ptType[s]?s:-1}).filter(function(e){return-1!==e});e.calibData.supportX=r.map(function(t){return e.calibData.supportX[t]}),e.calibData.supportY=r.map(function(t){return e.calibData.supportY[t]}),e.calibData.timestamps=r.map(function(t){return e.calibData.timestamps[t]}),e.calibData.ptType=r.map(function(t){return e.calibData.ptType[t]})})},e.prototype.handleClick=function(e,t){var n,r,s;return console.log("🖱️ Global click at: (".concat(e,", ").concat(t,"), ").concat(this.loaded)),this.latestMouseClick&&Date.now()-this.latestMouseClick.timestamp<1e3?(console.log("🖱️ Click ignored due to debounce"),void(this.latestMouseClick={x:e,y:t,timestamp:Date.now()})):this.latestMouseClick&&Math.abs(e-this.latestMouseClick.x)<.05&&Math.abs(t-this.latestMouseClick.y)<.05?(console.log("🖱️ Click ignored due to proximity to last click"),void(this.latestMouseClick={x:e,y:t,timestamp:Date.now()})):(this.latestMouseClick={x:e,y:t,timestamp:Date.now()},void(this.loaded&&this.latestGazeResult&&this.adapt([null===(n=this.latestGazeResult)||void 0===n?void 0:n.eyePatch],[null===(r=this.latestGazeResult)||void 0===r?void 0:r.headVector],[null===(s=this.latestGazeResult)||void 0===s?void 0:s.faceOrigin3D],[[e,t]])))},e.prototype.computeFaceOrigin3D=function(e,t,n,r){var s,a,i;!1===this.faceWidthComputed&&(this.faceWidthCm=(0,f.estimateFaceWidth)(n),this.faceWidthComputed=!0);var o=(0,f.faceReconstruction)(this.perspectiveMatrix,t,r,this.intrinsicsMatrix,this.faceWidthCm,e.width,e.height,null!==(i=null===(a=null===(s=this.latestGazeResult)||void 0===s?void 0:s.faceOrigin3D)||void 0===a?void 0:a[2])&&void 0!==i?i:60),u=(o[0],o[1]);return(0,f.computeFaceOrigin3D)(u)},e.prototype.prepareInput=function(e,t){var n=e.width,r=e.height;if(!this.perspectiveMatrixSet){var s=n/r;this.perspectiveMatrix=(0,f.createPerspectiveMatrix)(s),this.perspectiveMatrixSet=!0}this.intrinsicsMatrixSet||(this.intrinsicsMatrix=(0,f.createIntrinsicsMatrix)(n,r));var a=t.faceLandmarks[0],i=a.map(function(e){return[Math.floor(e.x*n),Math.floor(e.y*r)]}),o=(0,f.translateMatrix)(t.facialTransformationMatrixes[0]),u=(0,f.obtainEyePatch)(e,i),l=this.computeFaceOrigin3D(e,a.map(function(e){return[e.x,e.y]}),i,o);return[u,(0,f.getHeadVector)(o),l]},e.prototype.adapt=function(e,t,n,r,s,a,i){var o=this;void 0===s&&(s=1),void 0===a&&(a=1e-5),void 0===i&&(i="calib"),this.pruneCalibData();var u,l,h,d,p=c.train.adam(a,.85,.9,1e-8),m=function(e,t,n,r){return{supportX:{eyePatches:c.stack(e.map(function(e){return c.browser.fromPixels(e)}
5057),0).toFloat().div(c.scalar(255)),headVectors:c.tensor(t,[t.length,3],"float32"),faceOrigins3D:c.tensor(n,[n.length,3],"float32")},supportY:c.tensor(r,[r.length,2],"float32")}}(e,t,n,r),g=m.supportX,y=m.supportY;if(this.calibData.supportX.push(g),this.calibData.supportY.push(y),this.calibData.timestamps.push(Date.now()),this.calibData.ptType.push(i),this.calibData.supportX.length>1?(u=c.concat(this.calibData.supportX.map(function(e){return e.eyePatches}),0),l=c.concat(this.calibData.supportX.map(function(e){return e.headVectors}),0),h=c.concat(this.calibData.supportX.map(function(e){return e.faceOrigins3D}),0),d=c.concat(this.calibData.supportY,0)):(u=g.eyePatches,l=g.headVectors,h=g.faceOrigins3D,d=y),u.shape[0]>3){var b=c.tidy(function(){return o.blazeGaze.predict(u,l,h)}).arraySync(),x=d.arraySync(),w=(0,f.computeAffineMatrixML)(b,x);this.affineMatrix=c.tensor2d(w,[2,3],"float32")}c.tidy(function(){for(var e=0;e<s;e++){var t=c.variableGrads(function(){var e=o.blazeGaze.predict(u,l,h),t=o.affineMatrix?(0,f.applyAffineMatrix)(o.affineMatrix,e):e;return c.losses.meanSquaredError(d,t).asScalar()}),n=t.grads,r=t.value;p.applyGradients(n),r.data().then(function(e){return console.log("Loss = ".concat(e[0].toFixed(4)))})}})},e.prototype.step=function(e,t){return o(this,void 0,void 0,function(){var n,r,s,a,i,o,l,h,d,p,m,g,y,b,x,w,v,k,I,S=this;return u(this,function(u){switch(u.label){case 0:return n=performance.now(),[4,this.faceLandmarkerClient.processFrame(e)];case 1:return r=u.sent(),s=performance.now(),r&&r.faceLandmarks&&0!==r.faceLandmarks.length?(a=this.prepareInput(e,r),i=a[0],o=a[1],l=a[2],h=performance.now(),d="open",p=(0,f.computeEAR)(r.faceLandmarks[0],"left"),m=(0,f.computeEAR)(r.faceLandmarks[0],"right"),(p<.2||m<.2)&&(d="closed"),"closed"===d?[2,{facialLandmarks:r.faceLandmarks[0],faceRt:r.facialTransformationMatrixes[0],faceBlendshapes:r.faceBlendshapes,eyePatch:i,headVector:o,faceOrigin3D:l,metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:d,normPog:[0,0],durations:{faceLandmarker:s-n,prepareInput:h-s,blazeGaze:0,kalmanFilter:0,total:h-n},timestamp:t}]:(g=c.tidy(function(){var e=c.browser.fromPixels(i).toFloat().expandDims(0),t=e.div(c.scalar(255)),n=c.tensor2d(o,[1,3]),r=c.tensor2d(l,[1,3]),s=S.blazeGaze.predict(t,n,r);c.dispose([e,t,n,r]);var a=performance.now();if(S.affineMatrix&&(s=(0,f.applyAffineMatrix)(S.affineMatrix,s)),!s||0===s.shape.length)throw new Error("BlazeGaze model did not return valid output");return[s,a]}),y=g[0],b=g[1],x=y.arraySync(),c.dispose(y),w=this.kalmanFilter.step(x[0]),v=performance.now(),w[0]=Math.max(-.5,Math.min(.5,w[0])),w[1]=Math.max(-.5,Math.min(.5,w[1])),k={faceLandmarker:s-n,prepareInput:h-s,blazeGaze:b-h,kalmanFilter:v-b,total:v-n},I={facialLandmarks:r.faceLandmarks[0],faceRt:r.facialTransformationMatrixes[0],faceBlendshapes:r.faceBlendshapes,eyePatch:i,headVector:o,faceOrigin3D:l,metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:d,normPog:w,durations:k,timestamp:t},this.latestGazeResult=I,[2,I])):[2,{facialLandmarks:[],faceRt:{rows:0,columns:0,data:[]},faceBlendshapes:[],eyePatch:new ImageData(1,1),headVector:[0,0,0],faceOrigin3D:[0,0,0],metric_transform:{rows:3,columns:3,data:[1,0,0,1,0,0,1,0,0]},gazeState:"closed",normPog:[0,0],durations:{faceLandmarker:s-n,prepareInput:0,blazeGaze:0,kalmanFilter:0,total:0},timestamp:t}]}})})},e}();t.default=g},391:(e,t,n)=>{var r=n(180),s=n(181),a=n(31),i=n(67),o=n(833),u=n(717),l=n(801);l.alea=r,l.xor128=s,l.xorwow=a,l.xorshift7=i,l.xor4096=o,l.tychei=u,e.exports=l},530:()=>{},551:()=>{},570:e=>{e.exports=n;var t=null;try{t=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(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var s={},a={};function i(e,t){var n,r,i;return t?(i=0<=(e>>>=0)&&e<256)&&(r=a[e])?r:(n=u(e,(0|e)<0?-1:0,!0),i&&(a[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(r=s[e])?r:(n=u(e,e<0?-1:0,!1),i&&(s[e]=n),n)}function o(e,t){if(isNaN(e))return t?y:g;if(t){if(e<0)return y;if(e>=p)return k}else{if(e<=-f)return I;if(e+1>=f)return v}return e<0?o(-e,t).neg():u(e%d|0,e/d|0,t)}function u(e,t,r){return new n(e,t,r)}n.fromInt=i,n.fromNumber=o,n.fromBits=u;var l=Math.pow;
vendor: 4,172 bytes, line 5057
5057function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return g;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return c(e.substring(1),t,n).neg();for(var s=o(l(n,8)),a=g,i=0;i<e.length;i+=8){var u=Math.min(8,e.length-i),h=parseInt(e.substring(i,i+u),n);if(u<8){var d=o(l(n,u));a=a.mul(d).add(o(h))}else a=(a=a.mul(s)).add(o(h))}return a.unsigned=t,a}function h(e,t){return"number"==typeof e?o(e,t):"string"==typeof e?c(e,t):u(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=h;var d=4294967296,p=d*d,f=p/2,m=i(1<<24),g=i(0);n.ZERO=g;var y=i(0,!0);n.UZERO=y;var b=i(1);n.ONE=b;var x=i(1,!0);n.UONE=x;var w=i(-1);n.NEG_ONE=w;var v=u(-1,2147483647,!1);n.MAX_VALUE=v;var k=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=k;var I=u(0,-2147483648,!1);n.MIN_VALUE=I;var S=n.prototype;S.toInt=function(){return this.unsigned?this.low>>>0:this.low},S.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},S.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(I)){var t=o(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var s=o(l(e,6),this.unsigned),a=this,i="";;){var u=a.div(s),c=(a.sub(u.mul(s)).toInt()>>>0).toString(e);if((a=u).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},S.getHighBits=function(){return this.high},S.getHighBitsUnsigned=function(){return this.high>>>0},S.getLowBits=function(){return this.low},S.getLowBitsUnsigned=function(){return this.low>>>0},S.getNumBitsAbs=function(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},S.isZero=function(){return 0===this.high&&0===this.low},S.eqz=S.isZero,S.isNegative=function(){return!this.unsigned&&this.high<0},S.isPositive=function(){return this.unsigned||this.high>=0},S.isOdd=function(){return!(1&~this.low)},S.isEven=function(){return!(1&this.low)},S.equals=function(e){return r(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},S.eq=S.equals,S.notEquals=function(e){return!this.eq(e)},S.neq=S.notEquals,S.ne=S.notEquals,S.lessThan=function(e){return this.comp(e)<0},S.lt=S.lessThan,S.lessThanOrEqual=function(e){return this.comp(e)<=0},S.lte=S.lessThanOrEqual,S.le=S.lessThanOrEqual,S.greaterThan=function(e){return this.comp(e)>0},S.gt=S.greaterThan,S.greaterThanOrEqual=function(e){return this.comp(e)>=0},S.gte=S.greaterThanOrEqual,S.ge=S.greaterThanOrEqual,S.compare=function(e){if(r(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},S.comp=S.compare,S.negate=function(){return!this.unsigned&&this.eq(I)?I:this.not().add(b)},S.neg=S.negate,S.add=function(e){r(e)||(e=h(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,a=65535&this.low,i=e.high>>>16,o=65535&e.high,l=e.low>>>16,c=0,d=0,p=0,f=0;return p+=(f+=a+(65535&e.low))>>>16,d+=(p+=s+l)>>>16,c+=(d+=n+o)>>>16,c+=t+i,u((p&=65535)<<16|(f&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},S.subtract=function(e){return r(e)||(e=h(e)),this.add(e.neg())},S.sub=S.subtract,S.multiply=function(e){if(this.isZero())return g;if(r(e)||(e=h(e)),t)return u(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(I))return e.isOdd()?I:g;if(e.eq(I))return this.isOdd()?I:g;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return o(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=65535&this.high,a=this.low>>>16,i=65535&this.low,l=e.high>>>16,c=65535&e.high,d=e.low>>>16,p=65535&e.low,f=0,y=0,b=0,x=0;return b+=(x+=i*p)>>>16,y+=(b+=a*p)>>>
505716,b&=65535,y+=(b+=i*d)>>>16,f+=(y+=s*p)>>>16,y&=65535,f+=(y+=a*d)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*p+s*d+a*c+i*l,u((b&=65535)<<16|(x&=65535),(f&=65535)<<16|(y&=65535),this.unsigned)},S.mul=S.multiply,S.divide=function(e){if(r(e)||(e=h(e)),e.isZero())throw Error("division by zero");var n,s,a;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?u((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return y;if(e.gt(this.shru(1)))return x;a=y}else{if(this.eq(I))return e.eq(b)||e.eq(w)?I:e.eq(I)?b:(n=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?b:w:(s=this.sub(e.mul(n)),a=n.add(s.div(e)));if(e.eq(I))return this.unsigned?y:g;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();a=g}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),c=i<=48?1:l(2,i-48),d=o(n),p=d.mul(e);p.isNegative()||p.gt(s);)p=(d=o(n-=c,this.unsigned)).mul(e);d.isZero()&&(d=b),a=a.add(d),s=s.sub(p)}return a},S.div=S.divide,S.modulo=function(e){return r(e)||(e=h(e)),t?u((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},S.mod=S.modulo,S.rem=S.modulo,S.not=function(){return u(~this.low,~this.high,this.unsigned)},S.and=function(e){return r(e)||(e=h(e)),u(this.low&e.low,this.high&e.high,this.unsigned)},S.or=function(e){return r(e)||(e=h(e)),u(this.low|e.low,this.high|e.high,this.unsigned)},S.xor=function(e){return r(e)||(e=h(e)),u(this.low^e.low,this.high^e.high,this.unsigned)},S.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):u(0,this.low<<e-32,this.unsigned)},S.shl=S.shiftLeft,S.shiftRight=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):u(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},S.shr=S.shiftRight,S.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?u(this.low>>>e|t<<32-e,t>>>e,this.unsigned):u(32===e?t:t>>>e-32,0,this.unsigned)},S.shru=S.shiftRightUnsigned,S.shr_u=S.shiftRightUnsigned,S.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},S.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},S.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},S.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},S.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},590:()=>{},670:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KalmanFilter2D=void 0;var r=n(673),s=function(){function e(e,t,n){void 0===e&&(e=1),void 0===t&&(t=1e-4),void 0===n&&(n=.01),this.x=r.Matrix.zeros(4,1),this.F=new r.Matrix([[1,0,e,0],[0,1,0,e],[0,0,1,0],[0,0,0,1]]),this.H=new r.Matrix([[1,0,0,0],[0,1,0,0]]),this.R=r.Matrix.eye(2).mul(n),this.Q=r.Matrix.eye(4).mul(t),this.P=r.Matrix.eye(4)}return e.prototype.predict=function(){return this.x=this.F.mmul(this.x),this.P=this.F.mmul(this.P).mmul(this.F.transpose()).add(this.Q),this.x.subMatrix(0,1,0,0).to1DArray()},e.prototype.update=function(e){var t=new r.Matrix([[e[0]],[e[1]]]).sub(this.H.mmul(this.x)),n=this.H.mmul(this.P).mmul(this.H.transpose()).add(this.R),s=this.P.mmul(this.H.transpose()).mmul((0,r.inverse)(n));this.x=this.x.add(s.mmul(t));var a=r.Matrix.eye(4);return this.P=a.sub(s.mmul(this.H)).mmul(this.P),this.x.subMatrix(0,1,0,0).to1DArray()},e.prototype.step=function(e){return this.predict(),this.update(e)},e}();t.KalmanFilter2D=s},673:(e,t,n)=>{"use strict";
vendor: 5,064 bytes, line 5057
5057Object.defineProperty(t,"__esModule",{value:!0});var r=n(788),s=n(718);const a=" ".repeat(2),i=" ".repeat(4);function o(e,t={}){const{maxRows:n=15,maxColumns:r=10,maxNumSize:s=8,padMinus:o="auto"}=t;return`${e.constructor.name} {\\n${a}[\\n${i}${function(e,t,n,r,s){const{rows:a,columns:o}=e,l=Math.min(a,t),c=Math.min(o,n),h=[];if("auto"===s){s=!1;e:for(let t=0;t<l;t++)for(let n=0;n<c;n++)if(e.get(t,n)<0){s=!0;break e}}for(let t=0;t<l;t++){let n=[];for(let a=0;a<c;a++)n.push(u(e.get(t,a),r,s));h.push(`${n.join(" ")}`)}return c!==o&&(h[h.length-1]+=` ... ${o-n} more columns`),l!==a&&h.push(`... ${a-t} more rows`),h.join(`\\n${i}`)}(e,n,r,s,o)}\\n${a}]\\n${a}rows: ${e.rows}\\n${a}columns: ${e.columns}\\n}`}function u(e,t,n){return(e>=0&&n?` ${l(e,t-1)}`:l(e,t)).padEnd(t)}function l(e,t){let n=e.toString();if(n.length<=t)return n;let r=e.toFixed(t);if(r.length>t&&(r=e.toFixed(Math.max(0,t-(r.length-t)))),r.length<=t&&!r.startsWith("0.000")&&!r.startsWith("-0.000"))return r;let s=e.toExponential(t);return s.length>t&&(s=e.toExponential(Math.max(0,t-(s.length-t)))),s.slice(0)}function c(e,t,n){let r=n?e.rows:e.rows-1;if(t<0||t>r)throw new RangeError("Row index out of range")}function h(e,t,n){let r=n?e.columns:e.columns-1;if(t<0||t>r)throw new RangeError("Column index out of range")}function d(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.columns)throw new RangeError("vector size must be the same as the number of columns");return t}function p(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.rows)throw new RangeError("vector size must be the same as the number of rows");return t}function f(e,t){if(!r.isAnyArray(t))throw new TypeError("row indices must be an array");for(let n=0;n<t.length;n++)if(t[n]<0||t[n]>=e.rows)throw new RangeError("row indices are out of range")}function m(e,t){if(!r.isAnyArray(t))throw new TypeError("column indices must be an array");for(let n=0;n<t.length;n++)if(t[n]<0||t[n]>=e.columns)throw new RangeError("column indices are out of range")}function g(e,t,n,r,s){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(b("startRow",t),b("endRow",n),b("startColumn",r),b("endColumn",s),t>n||r>s||t<0||t>=e.rows||n<0||n>=e.rows||r<0||r>=e.columns||s<0||s>=e.columns)throw new RangeError("Submatrix indices are out of range")}function y(e,t=0){let n=[];for(let r=0;r<e;r++)n.push(t);return n}function b(e,t){if("number"!=typeof t)throw new TypeError(`${e} must be a number`)}function x(e){if(e.isEmpty())throw new Error("Empty matrix has no elements to index")}class w{static from1DArray(e,t,n){if(e*t!==n.length)throw new RangeError("data length does not match given dimensions");let r=new I(e,t);for(let s=0;s<e;s++)for(let e=0;e<t;e++)r.set(s,e,n[s*t+e]);return r}static rowVector(e){let t=new I(1,e.length);for(let n=0;n<e.length;n++)t.set(0,n,e[n]);return t}static columnVector(e){let t=new I(e.length,1);for(let n=0;n<e.length;n++)t.set(n,0,e[n]);return t}static zeros(e,t){return new I(e,t)}static ones(e,t){return new I(e,t).fill(1)}static rand(e,t,n={}){if("object"!=typeof n)throw new TypeError("options must be an object");const{random:r=Math.random}=n;let s=new I(e,t);for(let n=0;n<e;n++)for(let e=0;e<t;e++)s.set(n,e,r());return s}static randInt(e,t,n={}){if("object"!=typeof n)throw new TypeError("options must be an object");const{min:r=0,max:s=1e3,random:a=Math.random}=n;if(!Number.isInteger(r))throw new TypeError("min must be an integer");if(!Number.isInteger(s))throw new TypeError("max must be an integer");if(r>=s)throw new RangeError("min must be smaller than max");let i=s-r,o=new I(e,t);for(let n=0;n<e;n++)for(let e=0;e<t;e++){let t=r+Math.round(a()*i);o.set(n,e,t)}return o}static eye(e,t,n){void 0===t&&(t=e),void 0===n&&(n=1);let r=Math.min(e,t),s=this.zeros(e,t);for(let e=0;e<r;e++)s.set(e,e,n);return s}static diag(e,t,n){let r=e.length;void 0===t&&(t=r),void 0===n&&(n=t);let s=Math.min(r,t,n),a=this.zeros(t,n);for(let t=0;t<s;t++)a.set(t,t,e[t]);return a}static min(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let n=e.rows,r=e.columns,s=new I(n,r);for(let a=0;a<n;a++)for(let n=0;n<r;n++)s.set(a,n,Math.min(e.get(a,n),t.get(a,n)));return s}static max(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let n=e.rows,r=e.columns,s=new this(n,r);for(let a=0;a<n;a++)for(let n=0;n<r;n++)s.set(a,n,Math.max(e.get(a,n),t.get(a,n)));return s}static checkMatrix(e){return w.isMatrix(e)?e:new I(e)}static isMatrix(e){return null!=e&&"Matrix"===e.klass}get size(){return this.rows*this.columns}apply(e){if("function"!=typeof e)throw new TypeError("callback must be a function");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.call(this,t,n);return this}to1DArray(){let e=[];for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.push(this.get(t,n));return e}to2DArray(){let e=[];for(let t=0;t<this.rows;t++){e.push([]);for(let n=0;n<this.columns;n++)e[t].push(this.get(t,n))}return e}toJSON(){return this.to2DArray()}isRowVector(){return 1===this.rows}isColumnVector(){return 1===this.columns}isVector(){return 1===this.rows||1===this.columns}
vendor: 7,655 bytes, line 5057
5057isSquare(){return this.rows===this.columns}isEmpty(){return 0===this.rows||0===this.columns}isSymmetric(){if(this.isSquare()){for(let e=0;e<this.rows;e++)for(let t=0;t<=e;t++)if(this.get(e,t)!==this.get(t,e))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let e=0;e<this.rows;e++)if(0!==this.get(e,e))return!1;return!0}isEchelonForm(){let e=0,t=0,n=-1,r=!0,s=!1;for(;e<this.rows&&r;){for(t=0,s=!1;t<this.columns&&!1===s;)0===this.get(e,t)?t++:1===this.get(e,t)&&t>n?(s=!0,n=t):(r=!1,s=!0);e++}return r}isReducedEchelonForm(){let e=0,t=0,n=-1,r=!0,s=!1;for(;e<this.rows&&r;){for(t=0,s=!1;t<this.columns&&!1===s;)0===this.get(e,t)?t++:1===this.get(e,t)&&t>n?(s=!0,n=t):(r=!1,s=!0);for(let n=t+1;n<this.rows;n++)0!==this.get(e,n)&&(r=!1);e++}return r}echelonForm(){let e=this.clone(),t=0,n=0;for(;t<e.rows&&n<e.columns;){let r=t;for(let s=t;s<e.rows;s++)e.get(s,n)>e.get(r,n)&&(r=s);if(0===e.get(r,n))n++;else{e.swapRows(t,r);let s=e.get(t,n);for(let r=n;r<e.columns;r++)e.set(t,r,e.get(t,r)/s);for(let r=t+1;r<e.rows;r++){let s=e.get(r,n)/e.get(t,n);e.set(r,n,0);for(let a=n+1;a<e.columns;a++)e.set(r,a,e.get(r,a)-e.get(t,a)*s)}t++,n++}}return e}reducedEchelonForm(){let e=this.echelonForm(),t=e.columns,n=e.rows,r=n-1;for(;r>=0;)if(0===e.maxRow(r))r--;else{let s=0,a=!1;for(;s<n&&!1===a;)1===e.get(r,s)?a=!0:s++;for(let n=0;n<r;n++){let a=e.get(n,s);for(let i=s;i<t;i++){let t=e.get(n,i)-a*e.get(r,i);e.set(n,i,t)}}r--}return e}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{rows:t=1,columns:n=1}=e;if(!Number.isInteger(t)||t<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new TypeError("columns must be a positive integer");let r=new I(this.rows*t,this.columns*n);for(let e=0;e<t;e++)for(let t=0;t<n;t++)r.setSubMatrix(this,this.rows*e,this.columns*t);return r}fill(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,e);return this}neg(){return this.mulS(-1)}getRow(e){c(this,e);let t=[];for(let n=0;n<this.columns;n++)t.push(this.get(e,n));return t}getRowVector(e){return I.rowVector(this.getRow(e))}setRow(e,t){c(this,e),t=d(this,t);for(let n=0;n<this.columns;n++)this.set(e,n,t[n]);return this}swapRows(e,t){c(this,e),c(this,t);for(let n=0;n<this.columns;n++){let r=this.get(e,n);this.set(e,n,this.get(t,n)),this.set(t,n,r)}return this}getColumn(e){h(this,e);let t=[];for(let n=0;n<this.rows;n++)t.push(this.get(n,e));return t}getColumnVector(e){return I.columnVector(this.getColumn(e))}setColumn(e,t){h(this,e),t=p(this,t);for(let n=0;n<this.rows;n++)this.set(n,e,t[n]);return this}swapColumns(e,t){h(this,e),h(this,t);for(let n=0;n<this.rows;n++){let r=this.get(n,e);this.set(n,e,this.get(n,t)),this.set(n,t,r)}return this}addRowVector(e){e=d(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e[n]);return this}subRowVector(e){e=d(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e[n]);return this}mulRowVector(e){e=d(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e[n]);return this}divRowVector(e){e=d(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e[n]);return this}addColumnVector(e){e=p(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e[t]);return this}subColumnVector(e){e=p(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e[t]);return this}mulColumnVector(e){e=p(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e[t]);return this}divColumnVector(e){e=p(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e[t]);return this}mulRow(e,t){c(this,e);for(let n=0;n<this.columns;n++)this.set(e,n,this.get(e,n)*t);return this}mulColumn(e,t){h(this,e);for(let n=0;n<this.rows;n++)this.set(n,e,this.get(n,e)*t);return this}max(e){if(this.isEmpty())return NaN;switch(e){case"row":{const e=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)>e[t]&&(e[t]=this.get(t,n));return e}case"column":{const e=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)>e[n]&&(e[n]=this.get(t,n));return e}case void 0:{let e=this.get(0,0);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)>e&&(e=this.get(t,n));return e}default:throw new Error(`invalid option: ${e}`)}}maxIndex(){x(this);let e=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let r=0;r<this.columns;r++)this.get(n,r)>e&&(e=this.get(n,r),t[0]=n,t[1]=r);return t}min(e){if(this.isEmpty())return NaN;switch(e){case"row":{const e=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)<e[t]&&(e[t]=this.get(t,n));return e}case"column":{const e=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)<e[n]&&(e[n]=this.get(t,n));return e}case void 0:{let e=this.get(0,0);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.get(t,n)<e&&(e=this.get(t,n));return e}default:throw new Error(`invalid option: ${e}`)}}minIndex(){x(this);let e=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let r=0;r<this.columns;r++)this.get(n,r)<e&&(e=this.get(n,r),t[0]=n,t[1]=r);return t}maxRow(e){if(c(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let n=1;n<this.columns;n++)this.get(e,n)>t&&(t=this.get(e,n));return t}maxRowIndex(e){c(this,e),x(this);let t=this.get(e,0),n=[e,0];for(let r=1;r<this.columns;r++)this.get(e,r)>t&&(t=this.get(e,r),n[1]=r);return n}minRow(e){if(c(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let n=1;n<this.columns;n++)this.get(e,n)<t&&(t=this.get(e,n));return t}minRowIndex(e){c(this,e),x(this);let t=this.get(e,0),n=[e,0];for(let r=1;r<this.columns;r++)this.get(e,r)<t&&(t=this.get(e,r),n[1]=r);return n}maxColumn(e){if(h(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let n=1;n<this.rows;n++)this.get(n,e)>t&&(t=this.get(n,e));return t}maxColumnIndex(e){h(this,e),x(this);let t=this.get(0,e),n=[0,e];for(let r=1;r<this.rows;r++)this.get(r,e)>t&&(t=this.get(r,e),n[0]=r);return n}minColumn(e){if(h(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let n=1;n<this.rows;n++)this.get(n,e)<t&&(t=this.get(n,e));return t}minColumnIndex(e){h(this,e),x(this);let t=this.get(0,e),n=[0,e];for(let r=1;r<this.rows;r++)this.get(r,e)<t&&(t=this.get(r,e),n[0]=r);return n}diag(){let e=Math.min(this.rows,this.columns),t=[];for(let n=0;n<e;n++)t.push(this.get(n,n));return t}norm(e="frobenius"){switch(e){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${e}`)}}cumulativeSum(){let e=0;for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e+=this.get(t,n),this.set(t,n,e);return this}dot(e){w.isMatrix(e)&&(e=e.to1DArray());let t=this.to1DArray();if(t.length!==e.length)throw new RangeError("vectors do not have the same size");let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}mmul(e){e=I.checkMatrix(e);let t=this.rows,n=this.columns,r=e.columns,s=new I(t,r),a=new Float64Array(n);for(let i=0;i<r;i++){for(let t=0;t<n;t++)a[t]=e.get(t,i);for(let e=0;e<t;e++){let t=0;for(let r=0;r<n;r++)t+=this.get(e,r)*a[r];s.set(e,i,t)}}return s}
vendor: 4,363 bytes, line 5057
5057mpow(e){if(!this.isSquare())throw new RangeError("Matrix must be square");if(!Number.isInteger(e)||e<0)throw new RangeError("Exponent must be a non-negative integer");let t=I.eye(this.rows),n=this;for(let r=e;r>=1;r/=2)1&r&&(t=t.mmul(n)),n=n.mmul(n);return t}strassen2x2(e){e=I.checkMatrix(e);let t=new I(2,2);const n=this.get(0,0),r=e.get(0,0),s=this.get(0,1),a=e.get(0,1),i=this.get(1,0),o=e.get(1,0),u=this.get(1,1),l=e.get(1,1),c=(n+u)*(r+l),h=(i+u)*r,d=n*(a-l),p=u*(o-r),f=(n+s)*l,m=c+p-f+(s-u)*(o+l),g=d+f,y=h+p,b=c-h+d+(i-n)*(r+a);return t.set(0,0,m),t.set(0,1,g),t.set(1,0,y),t.set(1,1,b),t}strassen3x3(e){e=I.checkMatrix(e);let t=new I(3,3);const n=this.get(0,0),r=this.get(0,1),s=this.get(0,2),a=this.get(1,0),i=this.get(1,1),o=this.get(1,2),u=this.get(2,0),l=this.get(2,1),c=this.get(2,2),h=e.get(0,0),d=e.get(0,1),p=e.get(0,2),f=e.get(1,0),m=e.get(1,1),g=e.get(1,2),y=e.get(2,0),b=e.get(2,1),x=e.get(2,2),w=(n-a)*(-d+m),v=(-n+a+i)*(h-d+m),k=(a+i)*(-h+d),S=n*h,N=(-n+u+l)*(h-p+g),T=(-n+u)*(p-g),E=(u+l)*(-h+p),C=(-s+l+c)*(m+y-b),$=(s-c)*(m-b),A=s*y,R=(l+c)*(-y+b),_=(-s+i+o)*(g+y-x),M=(s-o)*(g-x),F=(i+o)*(-y+x),D=S+A+r*f,O=(n+r+s-a-i-l-c)*m+v+k+S+C+A+R,L=S+N+E+(n+r+s-i-o-u-l)*g+A+_+F,z=w+i*(-h+d+f-m-g-y+x)+v+S+A+_+M,P=w+v+k+S+o*b,B=A+_+M+F+a*p,V=S+N+T+l*(-h+p+f-m-g-y+b)+C+$+A,U=C+$+A+R+u*d,W=S+N+T+E+c*x;return t.set(0,0,D),t.set(0,1,O),t.set(0,2,L),t.set(1,0,z),t.set(1,1,P),t.set(1,2,B),t.set(2,0,V),t.set(2,1,U),t.set(2,2,W),t}mmulStrassen(e){e=I.checkMatrix(e);let t=this.clone(),n=t.rows,r=t.columns,s=e.rows,a=e.columns;function i(e,t,n){let r=e.rows,s=e.columns;if(r===t&&s===n)return e;{let r=w.zeros(t,n);return r=r.setSubMatrix(e,0,0),r}}r!==s&&console.warn(`Multiplying ${n} x ${r} and ${s} x ${a} matrix: dimensions do not match.`);let o=Math.max(n,s),u=Math.max(r,a);return t=i(t,o,u),function e(t,n,r,s){if(r<=512||s<=512)return t.mmul(n);r%2==1&&s%2==1?(t=i(t,r+1,s+1),n=i(n,r+1,s+1)):r%2==1?(t=i(t,r+1,s),n=i(n,r+1,s)):s%2==1&&(t=i(t,r,s+1),n=i(n,r,s+1));let a=parseInt(t.rows/2,10),o=parseInt(t.columns/2,10),u=t.subMatrix(0,a-1,0,o-1),l=n.subMatrix(0,a-1,0,o-1),c=t.subMatrix(0,a-1,o,t.columns-1),h=n.subMatrix(0,a-1,o,n.columns-1),d=t.subMatrix(a,t.rows-1,0,o-1),p=n.subMatrix(a,n.rows-1,0,o-1),f=t.subMatrix(a,t.rows-1,o,t.columns-1),m=n.subMatrix(a,n.rows-1,o,n.columns-1),g=e(w.add(u,f),w.add(l,m),a,o),y=e(w.add(d,f),l,a,o),b=e(u,w.sub(h,m),a,o),x=e(f,w.sub(p,l),a,o),v=e(w.add(u,c),m,a,o),k=e(w.sub(d,u),w.add(l,h),a,o),I=e(w.sub(c,f),w.add(p,m),a,o),S=w.add(g,x);S.sub(v),S.add(I);let N=w.add(b,v),T=w.add(y,x),E=w.sub(g,y);E.add(b),E.add(k);let C=w.zeros(2*S.rows,2*S.columns);return C=C.setSubMatrix(S,0,0),C=C.setSubMatrix(N,S.rows,0),C=C.setSubMatrix(T,0,S.columns),C=C.setSubMatrix(E,S.rows,S.columns),C.subMatrix(0,r-1,0,s-1)}(t,e=i(e,o,u),o,u)}scaleRows(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:n=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let r=new I(this.rows,this.columns);for(let e=0;e<this.rows;e++){const a=this.getRow(e);a.length>0&&s(a,{min:t,max:n,output:a}),r.setRow(e,a)}return r}scaleColumns(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:n=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let r=new I(this.rows,this.columns);for(let e=0;e<this.columns;e++){const a=this.getColumn(e);a.length&&s(a,{min:t,max:n,output:a}),r.setColumn(e,a)}return r}flipRows(){const e=Math.ceil(this.columns/2);for(let t=0;t<this.rows;t++)for(let n=0;n<e;n++){let e=this.get(t,n),r=this.get(t,this.columns-1-n);this.set(t,n,r),this.set(t,this.columns-1-n,e)}return this}flipColumns(){const e=Math.ceil(this.rows/2);for(let t=0;t<this.columns;t++)for(let n=0;n<e;n++){let e=this.get(n,t),r=this.get(this.rows-1-n,t);this.set(n,t,r),this.set(this.rows-1-n,t,e)}return this}kroneckerProduct(e){e=I.checkMatrix(e);let t=this.rows,n=this.columns,r=e.rows,s=e.columns,a=new I(t*r,n*s);for(let i=0;i<t;i++)for(let t=0;t<n;t++)for(let n=0;n<r;n++)for(let o=0;o<s;o++)a.set(r*i+n,s*t+o,this.get(i,t)*e.get(n,o));return a}
vendor: 7,971 bytes, line 5057
5057kroneckerSum(e){if(e=I.checkMatrix(e),!this.isSquare()||!e.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let t=this.rows,n=e.rows,r=this.kroneckerProduct(I.eye(n,n)),s=I.eye(t,t).kroneckerProduct(e);return r.add(s)}transpose(){let e=new I(this.columns,this.rows);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.set(n,t,this.get(t,n));return e}sortRows(e=v){for(let t=0;t<this.rows;t++)this.setRow(t,this.getRow(t).sort(e));return this}sortColumns(e=v){for(let t=0;t<this.columns;t++)this.setColumn(t,this.getColumn(t).sort(e));return this}subMatrix(e,t,n,r){g(this,e,t,n,r);let s=new I(t-e+1,r-n+1);for(let a=e;a<=t;a++)for(let t=n;t<=r;t++)s.set(a-e,t-n,this.get(a,t));return s}subMatrixRow(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.columns-1),t>n||t<0||t>=this.columns||n<0||n>=this.columns)throw new RangeError("Argument out of range");let r=new I(e.length,n-t+1);for(let s=0;s<e.length;s++)for(let a=t;a<=n;a++){if(e[s]<0||e[s]>=this.rows)throw new RangeError(`Row index out of range: ${e[s]}`);r.set(s,a-t,this.get(e[s],a))}return r}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||t<0||t>=this.rows||n<0||n>=this.rows)throw new RangeError("Argument out of range");let r=new I(n-t+1,e.length);for(let s=0;s<e.length;s++)for(let a=t;a<=n;a++){if(e[s]<0||e[s]>=this.columns)throw new RangeError(`Column index out of range: ${e[s]}`);r.set(a-t,s,this.get(a,e[s]))}return r}setSubMatrix(e,t,n){if((e=I.checkMatrix(e)).isEmpty())return this;g(this,t,t+e.rows-1,n,n+e.columns-1);for(let r=0;r<e.rows;r++)for(let s=0;s<e.columns;s++)this.set(t+r,n+s,e.get(r,s));return this}selection(e,t){f(this,e),m(this,t);let n=new I(e.length,t.length);for(let r=0;r<e.length;r++){let s=e[r];for(let e=0;e<t.length;e++){let a=t[e];n.set(r,e,this.get(s,a))}}return n}trace(){let e=Math.min(this.rows,this.columns),t=0;for(let n=0;n<e;n++)t+=this.get(n,n);return t}clone(){return this.constructor.copy(this,new I(this.rows,this.columns))}static copy(e,t){for(const[n,r,s]of e.entries())t.set(n,r,s);return t}sum(e){switch(e){case"row":return function(e){let t=y(e.rows);for(let n=0;n<e.rows;++n)for(let r=0;r<e.columns;++r)t[n]+=e.get(n,r);return t}(this);case"column":return function(e){let t=y(e.columns);for(let n=0;n<e.rows;++n)for(let r=0;r<e.columns;++r)t[r]+=e.get(n,r);return t}(this);case void 0:return function(e){let t=0;for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)t+=e.get(n,r);return t}(this);default:throw new Error(`invalid option: ${e}`)}}product(e){switch(e){case"row":return function(e){let t=y(e.rows,1);for(let n=0;n<e.rows;++n)for(let r=0;r<e.columns;++r)t[n]*=e.get(n,r);return t}(this);case"column":return function(e){let t=y(e.columns,1);for(let n=0;n<e.rows;++n)for(let r=0;r<e.columns;++r)t[r]*=e.get(n,r);return t}(this);case void 0:return function(e){let t=1;for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)t*=e.get(n,r);return t}(this);default:throw new Error(`invalid option: ${e}`)}}mean(e){const t=this.sum(e);switch(e){case"row":for(let e=0;e<this.rows;e++)t[e]/=this.columns;return t;case"column":for(let e=0;e<this.columns;e++)t[e]/=this.rows;return t;case void 0:return t/this.size;default:throw new Error(`invalid option: ${e}`)}}variance(e,t={}){if("object"==typeof e&&(t=e,e=void 0),"object"!=typeof t)throw new TypeError("options must be an object");const{unbiased:n=!0,mean:s=this.mean(e)}=t;if("boolean"!=typeof n)throw new TypeError("unbiased must be a boolean");switch(e){case"row":if(!r.isAnyArray(s))throw new TypeError("mean must be an array");return function(e,t,n){const r=e.rows,s=e.columns,a=[];for(let i=0;i<r;i++){let r=0,o=0,u=0;for(let t=0;t<s;t++)u=e.get(i,t)-n[i],r+=u,o+=u*u;t?a.push((o-r*r/s)/(s-1)):a.push((o-r*r/s)/s)}return a}(this,n,s);case"column":if(!r.isAnyArray(s))throw new TypeError("mean must be an array");return function(e,t,n){const r=e.rows,s=e.columns,a=[];for(let i=0;i<s;i++){let s=0,o=0,u=0;for(let t=0;t<r;t++)u=e.get(t,i)-n[i],s+=u,o+=u*u;t?a.push((o-s*s/r)/(r-1)):a.push((o-s*s/r)/r)}return a}(this,n,s);case void 0:if("number"!=typeof s)throw new TypeError("mean must be a number");return function(e,t,n){const r=e.rows,s=e.columns,a=r*s;let i=0,o=0,u=0;for(let t=0;t<r;t++)for(let r=0;r<s;r++)u=e.get(t,r)-n,i+=u,o+=u*u;return t?(o-i*i/a)/(a-1):(o-i*i/a)/a}(this,n,s);default:throw new Error(`invalid option: ${e}`)}}standardDeviation(e,t){"object"==typeof e&&(t=e,e=void 0);const n=this.variance(e,t);if(void 0===e)return Math.sqrt(n);for(let e=0;e<n.length;e++)n[e]=Math.sqrt(n[e]);return n}center(e,t={}){if("object"==typeof e&&(t=e,e=void 0),"object"!=typeof t)throw new TypeError("options must be an object");const{center:n=this.mean(e)}=t;switch(e){case"row":if(!r.isAnyArray(n))throw new TypeError("center must be an array");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)-t[n])}(this,n),this;case"column":if(!r.isAnyArray(n))throw new TypeError("center must be an array");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)-t[r])}(this,n),this;case void 0:if("number"!=typeof n)throw new TypeError("center must be a number");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)-t)}(this,n),this;default:throw new Error(`invalid option: ${e}`)}}scale(e,t={}){if("object"==typeof e&&(t=e,e=void 0),"object"!=typeof t)throw new TypeError("options must be an object");let n=t.scale;switch(e){case"row":if(void 0===n)n=function(e){const t=[];for(let n=0;n<e.rows;n++){let r=0;for(let t=0;t<e.columns;t++)r+=e.get(n,t)**2/(e.columns-1);t.push(Math.sqrt(r))}return t}(this);else if(!r.isAnyArray(n))throw new TypeError("scale must be an array");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)/t[n])}(this,n),this;case"column":if(void 0===n)n=function(e){const t=[];for(let n=0;n<e.columns;n++){let r=0;for(let t=0;t<e.rows;t++)r+=e.get(t,n)**2/(e.rows-1);t.push(Math.sqrt(r))}return t}(this);else if(!r.isAnyArray(n))throw new TypeError("scale must be an array");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)/t[r])}(this,n),this;case void 0:if(void 0===n)n=function(e){const t=e.size-1;let n=0;for(let r=0;r<e.columns;r++)for(let s=0;s<e.rows;s++)n+=e.get(s,r)**2/t;return Math.sqrt(n)}(this);else if("number"!=typeof n)throw new TypeError("scale must be a number");return function(e,t){for(let n=0;n<e.rows;n++)for(let r=0;r<e.columns;r++)e.set(n,r,e.get(n,r)/t)}(this,n),this;default:throw new Error(`invalid option: ${e}`)}}toString(e){return o(this,e)}[Symbol.iterator](){return this.entries()}*entries(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield[e,t,this.get(e,t)]}*values(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield this.get(e,t)}}function v(e,t){return e-t}function k(e){return e.every(e=>"number"==typeof e)}w.prototype.klass="Matrix","undefined"!=typeof Symbol&&(w.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return o(this)}),w.random=w.rand,w.randomInt=w.randInt,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct;class I extends w{data;#e(e,t){if(this.data=[],!(Number.isInteger(t)&&t>=0))throw new TypeError("nColumns must be a positive integer");for(let n=0;n<e;n++)this.data.push(new Float64Array(t));this.rows=e,this.columns=t}constructor(e,t){if(super(),I.isMatrix(e))this.#e(e.rows,e.columns),I.copy(e,this);else if(Number.isInteger(e)&&e>=0)this.#e(e,t);else{if(!r.isAnyArray(e))throw new TypeError("First argument must be a positive number or an array");{const n=e;if("number"!=typeof(t=(e=n.length)?n[0].length:0))throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let r=0;r<e;r++){if(n[r].length!==t)throw new RangeError("Inconsistent array dimensions");
vendor: 15,790 bytes, line 5057
5057if(!k(n[r]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(n[r]))}this.rows=e,this.columns=t}}}set(e,t,n){return this.data[e][t]=n,this}get(e,t){return this.data[e][t]}removeRow(e){return c(this,e),this.data.splice(e,1),this.rows-=1,this}addRow(e,t){return void 0===t&&(t=e,e=this.rows),c(this,e,!0),t=Float64Array.from(d(this,t)),this.data.splice(e,0,t),this.rows+=1,this}removeColumn(e){h(this,e);for(let t=0;t<this.rows;t++){const n=new Float64Array(this.columns-1);for(let r=0;r<e;r++)n[r]=this.data[t][r];for(let r=e+1;r<this.columns;r++)n[r-1]=this.data[t][r];this.data[t]=n}return this.columns-=1,this}addColumn(e,t){void 0===t&&(t=e,e=this.columns),h(this,e,!0),t=p(this,t);for(let n=0;n<this.rows;n++){const r=new Float64Array(this.columns+1);let s=0;for(;s<e;s++)r[s]=this.data[n][s];for(r[s++]=t[n];s<this.columns+1;s++)r[s]=this.data[n][s-1];this.data[n]=r}return this.columns+=1,this}}!function(e,t){e.prototype.add=function(e){return"number"==typeof e?this.addS(e):this.addM(e)},e.prototype.addS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e);return this},e.prototype.addM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e.get(t,n));return this},e.add=function(e,n){return new t(e).add(n)},e.prototype.sub=function(e){return"number"==typeof e?this.subS(e):this.subM(e)},e.prototype.subS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e);return this},e.prototype.subM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e.get(t,n));return this},e.sub=function(e,n){return new t(e).sub(n)},e.prototype.subtract=e.prototype.sub,e.prototype.subtractS=e.prototype.subS,e.prototype.subtractM=e.prototype.subM,e.subtract=e.sub,e.prototype.mul=function(e){return"number"==typeof e?this.mulS(e):this.mulM(e)},e.prototype.mulS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e);return this},e.prototype.mulM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e.get(t,n));return this},e.mul=function(e,n){return new t(e).mul(n)},e.prototype.multiply=e.prototype.mul,e.prototype.multiplyS=e.prototype.mulS,e.prototype.multiplyM=e.prototype.mulM,e.multiply=e.mul,e.prototype.div=function(e){return"number"==typeof e?this.divS(e):this.divM(e)},e.prototype.divS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e);return this},e.prototype.divM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e.get(t,n));return this},e.div=function(e,n){return new t(e).div(n)},e.prototype.divide=e.prototype.div,e.prototype.divideS=e.prototype.divS,e.prototype.divideM=e.prototype.divM,e.divide=e.div,e.prototype.mod=function(e){return"number"==typeof e?this.modS(e):this.modM(e)},e.prototype.modS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)%e);return this},e.prototype.modM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)%e.get(t,n));return this},e.mod=function(e,n){return new t(e).mod(n)},e.prototype.modulus=e.prototype.mod,e.prototype.modulusS=e.prototype.modS,e.prototype.modulusM=e.prototype.modM,e.modulus=e.mod,e.prototype.and=function(e){return"number"==typeof e?this.andS(e):this.andM(e)},e.prototype.andS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)&e);return this},e.prototype.andM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)&e.get(t,n));return this},e.and=function(e,n){return new t(e).and(n)},e.prototype.or=function(e){return"number"==typeof e?this.orS(e):this.orM(e)},e.prototype.orS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)|e);return this},e.prototype.orM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)|e.get(t,n));return this},e.or=function(e,n){return new t(e).or(n)},e.prototype.xor=function(e){return"number"==typeof e?this.xorS(e):this.xorM(e)},e.prototype.xorS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)^e);return this},e.prototype.xorM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)^e.get(t,n));return this},e.xor=function(e,n){return new t(e).xor(n)},e.prototype.leftShift=function(e){return"number"==typeof e?this.leftShiftS(e):this.leftShiftM(e)},e.prototype.leftShiftS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)<<e);return this},e.prototype.leftShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)<<e.get(t,n));return this},e.leftShift=function(e,n){return new t(e).leftShift(n)},e.prototype.signPropagatingRightShift=function(e){return"number"==typeof e?this.signPropagatingRightShiftS(e):this.signPropagatingRightShiftM(e)},e.prototype.signPropagatingRightShiftS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)>>e);return this},e.prototype.signPropagatingRightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)>>e.get(t,n));return this},e.signPropagatingRightShift=function(e,n){return new t(e).signPropagatingRightShift(n)},e.prototype.rightShift=function(e){return"number"==typeof e?this.rightShiftS(e):this.rightShiftM(e)},e.prototype.rightShiftS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)>>>e);return this},e.prototype.rightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)>>>e.get(t,n));return this},e.rightShift=function(e,n){return new t(e).rightShift(n)},e.prototype.zeroFillRightShift=e.prototype.rightShift,e.prototype.zeroFillRightShiftS=e.prototype.rightShiftS,e.prototype.zeroFillRightShiftM=e.prototype.rightShiftM,e.zeroFillRightShift=e.rightShift,e.prototype.not=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,~this.get(e,t));return this},e.not=function(e){return new t(e).not()},e.prototype.abs=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.abs(this.get(e,t)));return this},e.abs=function(e){return new t(e).abs()},e.prototype.acos=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.acos(this.get(e,t)));return this},e.acos=function(e){return new t(e).acos()},e.prototype.acosh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.acosh(this.get(e,t)));return this},e.acosh=function(e){return new t(e).acosh()},e.prototype.asin=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.asin(this.get(e,t)));return this},e.asin=function(e){return new t(e).asin()},e.prototype.asinh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.asinh(this.get(e,t)));return this},e.asinh=function(e){return new t(e).asinh()},e.prototype.atan=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.atan(this.get(e,t)));return this},e.atan=function(e){return new t(e).atan()},e.prototype.atanh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.atanh(this.get(e,t)));return this},e.atanh=function(e){return new t(e).atanh()},e.prototype.cbrt=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.cbrt(this.get(e,t)));return this},e.cbrt=function(e){return new t(e).cbrt()},e.prototype.ceil=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.ceil(this.get(e,t)));return this},e.ceil=function(e){return new t(e).ceil()},e.prototype.clz32=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.clz32(this.get(e,t)));return this},e.clz32=function(e){return new t(e).clz32()},e.prototype.cos=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.cos(this.get(e,t)));return this},e.cos=function(e){return new t(e).cos()},e.prototype.cosh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.cosh(this.get(e,t)));return this},e.cosh=function(e){return new t(e).cosh()},e.prototype.exp=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.exp(this.get(e,t)));return this},e.exp=function(e){return new t(e).exp()},e.prototype.expm1=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.expm1(this.get(e,t)));return this},e.expm1=function(e){return new t(e).expm1()},e.prototype.floor=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.floor(this.get(e,t)));return this},e.floor=function(e){return new t(e).floor()},e.prototype.fround=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.fround(this.get(e,t)));return this},e.fround=function(e){return new t(e).fround()},e.prototype.log=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.log(this.get(e,t)));return this},e.log=function(e){return new t(e).log()},e.prototype.log1p=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.log1p(this.get(e,t)));return this},e.log1p=function(e){return new t(e).log1p()},e.prototype.log10=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.log10(this.get(e,t)));return this},e.log10=function(e){return new t(e).log10()},e.prototype.log2=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.log2(this.get(e,t)));return this},e.log2=function(e){return new t(e).log2()},e.prototype.round=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.round(this.get(e,t)));return this},e.round=function(e){return new t(e).round()},e.prototype.sign=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.sign(this.get(e,t)));return this},e.sign=function(e){return new t(e).sign()},e.prototype.sin=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.sin(this.get(e,t)));return this},e.sin=function(e){return new t(e).sin()},e.prototype.sinh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.sinh(this.get(e,t)));return this},e.sinh=function(e){return new t(e).sinh()},e.prototype.sqrt=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.sqrt(this.get(e,t)));return this},e.sqrt=function(e){return new t(e).sqrt()},e.prototype.tan=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.tan(this.get(e,t)));return this},e.tan=function(e){return new t(e).tan()},e.prototype.tanh=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.tanh(this.get(e,t)));return this},e.tanh=function(e){return new t(e).tanh()},e.prototype.trunc=function(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)this.set(e,t,Math.trunc(this.get(e,t)));return this},e.trunc=function(e){return new t(e).trunc()},e.pow=function(e,n){return new t(e).pow(n)},e.prototype.pow=function(e){return"number"==typeof e?this.powS(e):this.powM(e)},e.prototype.powS=function(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)**e);return this},e.prototype.powM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)**e.get(t,n));return this}}(w,I);class S extends w{#t;get size(){return this.#t.size}get rows(){return this.#t.rows}get columns(){return this.#t.columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(e){return I.isMatrix(e)&&"SymmetricMatrix"===e.klassType}static zeros(e){return new this(e)}static ones(e){return new this(e).fill(1)}constructor(e){if(super(),I.isMatrix(e)){if(!e.isSymmetric())throw new TypeError("not symmetric data");this.#t=I.copy(e,new I(e.rows,e.rows))}else if(Number.isInteger(e)&&e>=0)this.#t=new I(e,e);else if(this.#t=new I(e),!this.isSymmetric())throw new TypeError("not symmetric data")}clone(){const e=new S(this.diagonalSize);for(const[t,n,r]of this.upperRightEntries())e.set(t,n,r);return e}toMatrix(){return new I(this)}get(e,t){return this.#t.get(e,t)}set(e,t,n){return this.#t.set(e,t,n),this.#t.set(t,e,n),this}removeCross(e){return this.#t.removeRow(e),this.#t.removeColumn(e),this}addCross(e,t){void 0===t&&(t=e,e=this.diagonalSize);const n=t.slice();return n.splice(e,1),this.#t.addRow(e,n),this.#t.addColumn(e,t),this}applyMask(e){if(e.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const t=[];for(const[n,r]of e.entries())r||t.push(n);t.reverse();for(const e of t)this.removeCross(e);return this}toCompact(){const{diagonalSize:e}=this,t=new Array(e*(e+1)/2);for(let n=0,r=0,s=0;s<t.length;s++)t[s]=this.get(r,n),++n>=e&&(n=++r);return t}static fromCompact(e){const t=e.length,n=(Math.sqrt(8*t+1)-1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(e)}`);const r=new S(n);for(let s=0,a=0,i=0;i<t;i++)r.set(s,a,e[i]),++s>=n&&(s=++a);return r}*upperRightEntries(){for(let e=0,t=0;e<this.diagonalSize;void 0){const n=this.get(e,t);yield[e,t,n],++t>=this.diagonalSize&&(t=++e)}}*upperRightValues(){for(let e=0,t=0;e<this.diagonalSize;void 0){const n=this.get(e,t);yield n,++t>=this.diagonalSize&&(t=++e)}}}S.prototype.klassType="SymmetricMatrix";class N extends S{static isDistanceMatrix(e){return S.isSymmetricMatrix(e)&&"DistanceMatrix"===e.klassSubType}constructor(e){if(super(e),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(e,t,n){return e===t&&(n=0),super.set(e,t,n)}addCross(e,t){return void 0===t&&(t=e,e=this.diagonalSize),(t=t.
vendor: 11,964 bytes, line 5057
5057slice())[e]=0,super.addCross(e,t)}toSymmetricMatrix(){return new S(this)}clone(){const e=new N(this.diagonalSize);for(const[t,n,r]of this.upperRightEntries())t!==n&&e.set(t,n,r);return e}toCompact(){const{diagonalSize:e}=this,t=new Array((e-1)*e/2);for(let n=1,r=0,s=0;s<t.length;s++)t[s]=this.get(r,n),++n>=e&&(n=1+ ++r);return t}static fromCompact(e){const t=e.length;if(0===t)return new this(0);const n=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(e)}`);const r=new this(n);for(let s=1,a=0,i=0;i<t;i++)r.set(s,a,e[i]),++s>=n&&(s=1+ ++a);return r}}N.prototype.klassSubType="DistanceMatrix";class T extends w{constructor(e,t,n){super(),this.matrix=e,this.rows=t,this.columns=n}}class E extends T{constructor(e,t,n){f(e,t),m(e,n),super(e,t.length,n.length),this.rowIndices=t,this.columnIndices=n}set(e,t,n){return this.matrix.set(this.rowIndices[e],this.columnIndices[t],n),this}get(e,t){return this.matrix.get(this.rowIndices[e],this.columnIndices[t])}}class C extends w{constructor(e,t={}){const{rows:n=1}=t;if(e.length%n!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=n,this.columns=e.length/n,this.data=e}set(e,t,n){let r=this._calculateIndex(e,t);return this.data[r]=n,this}get(e,t){let n=this._calculateIndex(e,t);return this.data[n]}_calculateIndex(e,t){return e*this.columns+t}}class $ extends w{constructor(e){super(),this.data=e,this.rows=e.length,this.columns=e[0].length}set(e,t,n){return this.data[e][t]=n,this}get(e,t){return this.data[e][t]}}class A{constructor(e){let t,n,r,s,a,i,o,u,l,c=(e=$.checkMatrix(e)).clone(),h=c.rows,d=c.columns,p=new Float64Array(h),f=1;for(t=0;t<h;t++)p[t]=t;for(u=new Float64Array(h),n=0;n<d;n++){for(t=0;t<h;t++)u[t]=c.get(t,n);for(t=0;t<h;t++){for(l=Math.min(t,n),a=0,r=0;r<l;r++)a+=c.get(t,r)*u[r];u[t]-=a,c.set(t,n,u[t])}for(s=n,t=n+1;t<h;t++)Math.abs(u[t])>Math.abs(u[s])&&(s=t);if(s!==n){for(r=0;r<d;r++)i=c.get(s,r),c.set(s,r,c.get(n,r)),c.set(n,r,i);o=p[s],p[s]=p[n],p[n]=o,f=-f}if(n<h&&0!==c.get(n,n))for(t=n+1;t<h;t++)c.set(t,n,c.get(t,n)/c.get(n,n))}this.LU=c,this.pivotVector=p,this.pivotSign=f}isSingular(){let e=this.LU,t=e.columns;for(let n=0;n<t;n++)if(0===e.get(n,n))return!0;return!1}solve(e){e=I.checkMatrix(e);let t=this.LU;if(t.rows!==e.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let n,r,s,a=e.columns,i=e.subMatrixRow(this.pivotVector,0,a-1),o=t.columns;for(s=0;s<o;s++)for(n=s+1;n<o;n++)for(r=0;r<a;r++)i.set(n,r,i.get(n,r)-i.get(s,r)*t.get(n,s));for(s=o-1;s>=0;s--){for(r=0;r<a;r++)i.set(s,r,i.get(s,r)/t.get(s,s));for(n=0;n<s;n++)for(r=0;r<a;r++)i.set(n,r,i.get(n,r)-i.get(s,r)*t.get(n,s))}return i}get determinant(){let e=this.LU;if(!e.isSquare())throw new Error("Matrix must be square");let t=this.pivotSign,n=e.columns;for(let r=0;r<n;r++)t*=e.get(r,r);return t}get lowerTriangularMatrix(){let e=this.LU,t=e.rows,n=e.columns,r=new I(t,n);for(let s=0;s<t;s++)for(let t=0;t<n;t++)s>t?r.set(s,t,e.get(s,t)):s===t?r.set(s,t,1):r.set(s,t,0);return r}get upperTriangularMatrix(){let e=this.LU,t=e.rows,n=e.columns,r=new I(t,n);for(let s=0;s<t;s++)for(let t=0;t<n;t++)s<=t?r.set(s,t,e.get(s,t)):r.set(s,t,0);return r}get pivotPermutationVector(){return Array.from(this.pivotVector)}}function R(e,t){let n=0;return Math.abs(e)>Math.abs(t)?(n=t/e,Math.abs(e)*Math.sqrt(1+n*n)):0!==t?(n=e/t,Math.abs(t)*Math.sqrt(1+n*n)):0}class _{constructor(e){let t,n,r,s,a=(e=$.checkMatrix(e)).clone(),i=e.rows,o=e.columns,u=new Float64Array(o);for(r=0;r<o;r++){let e=0;for(t=r;t<i;t++)e=R(e,a.get(t,r));if(0!==e){for(a.get(r,r)<0&&(e=-e),t=r;t<i;t++)a.set(t,r,a.get(t,r)/e);for(a.set(r,r,a.get(r,r)+1),n=r+1;n<o;n++){for(s=0,t=r;t<i;t++)s+=a.get(t,r)*a.get(t,n);for(s=-s/a.get(r,r),t=r;t<i;t++)a.set(t,n,a.get(t,n)+s*a.get(t,r))}}u[r]=-e}this.QR=a,this.Rdiag=u}solve(e){e=I.checkMatrix(e);let t=this.QR,n=t.rows;if(e.rows!==n)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let r,s,a,i,o=e.columns,u=e.clone(),l=t.columns;for(a=0;a<l;a++)for(s=0;s<o;s++){for(i=0,r=a;r<n;r++)i+=t.get(r,a)*u.get(r,s);for(i=-i/t.get(a,a),r=a;r<n;r++)u.set(r,s,u.get(r,s)+i*t.get(r,a))}for(a=l-1;a>=0;a--){for(s=0;s<o;s++)u.set(a,s,u.get(a,s)/this.Rdiag[a]);for(r=0;r<a;r++)for(s=0;s<o;s++)u.set(r,s,u.get(r,s)-u.get(a,s)*t.get(r,a))}return u.subMatrix(0,l-1,0,o-1)}isFullRank(){let e=this.QR.columns;for(let t=0;t<e;t++)if(0===this.Rdiag[t])return!1;return!0}get upperTriangularMatrix(){let e,t,n=this.QR,r=n.columns,s=new I(r,r);for(e=0;e<r;e++)for(t=0;t<r;t++)e<t?s.set(e,t,n.get(e,t)):e===t?s.set(e,t,this.Rdiag[e]):s.set(e,t,0);return s}get orthogonalMatrix(){let e,t,n,r,s=this.QR,a=s.rows,i=s.columns,o=new I(a,i);for(n=i-1;n>=0;n--){for(e=0;e<a;e++)o.set(e,n,0);for(o.set(n,n,1),t=n;t<i;t++)if(0!==s.get(n,n)){for(r=0,e=n;e<a;e++)r+=s.get(e,n)*o.get(e,t);for(r=-r/s.get(n,n),e=n;e<a;e++)o.set(e,t,o.get(e,t)+r*s.get(e,n))}}return o}}class M{constructor(e,t={}){if((e=$.checkMatrix(e)).isEmpty())throw new Error("Matrix must be non-empty");let n=e.rows,r=e.columns;const{computeLeftSingularVectors:s=!0,computeRightSingularVectors:a=!0,autoTranspose:i=!1}=t;let o,u=Boolean(s),l=Boolean(a),c=!1;if(n<r)if(i){o=e.transpose(),n=o.rows,r=o.columns,c=!0;let t=u;u=l,l=t}else o=e.clone(),console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose");else o=e.clone();let h=Math.min(n,r),d=Math.min(n+1,r),p=new Float64Array(d),f=new I(n,h),m=new I(r,r),g=new Float64Array(r),y=new Float64Array(n),b=new Float64Array(d);for(let e=0;e<d;e++)b[e]=e;let x=Math.min(n-1,r),w=Math.max(0,Math.min(r-2,n)),v=Math.max(x,w);for(let e=0;e<v;e++){if(e<x){p[e]=0;for(let t=e;t<n;t++)p[e]=R(p[e],o.get(t,e));if(0!==p[e]){o.get(e,e)<0&&(p[e]=-p[e]);for(let t=e;t<n;t++)o.set(t,e,o.get(t,e)/p[e]);o.set(e,e,o.get(e,e)+1)}p[e]=-p[e]}for(let t=e+1;t<r;t++){if(e<x&&0!==p[e]){let r=0;for(let s=e;s<n;s++)r+=o.get(s,e)*o.get(s,t);r=-r/o.get(e,e);for(let s=e;s<n;s++)o.set(s,t,o.get(s,t)+r*o.get(s,e))}g[t]=o.get(e,t)}if(u&&e<x)for(let t=e;t<n;t++)f.set(t,e,o.get(t,e));if(e<w){g[e]=0;for(let t=e+1;t<r;t++)g[e]=R(g[e],g[t]);if(0!==g[e]){g[e+1]<0&&(g[e]=0-g[e]);for(let t=e+1;t<r;t++)g[t]/=g[e];g[e+1]+=1}if(g[e]=-g[e],e+1<n&&0!==g[e]){for(let t=e+1;t<n;t++)y[t]=0;for(let t=e+1;t<n;t++)for(let n=e+1;n<r;n++)y[t]+=g[n]*o.get(t,n);for(let t=e+1;t<r;t++){let r=-g[t]/g[e+1];for(let s=e+1;s<n;s++)o.set(s,t,o.get(s,t)+r*y[s])}}if(l)for(let t=e+1;t<r;t++)m.set(t,e,g[t])}}let k=Math.min(r,n+1);if(x<r&&(p[x]=o.get(x,x)),n<k&&(p[k-1]=0),w+1<k&&(g[w]=o.get(w,k-1)),g[k-1]=0,u){for(let e=x;e<h;e++){for(let t=0;t<n;t++)f.set(t,e,0);f.set(e,e,1)}for(let e=x-1;e>=0;e--)if(0!==p[e]){for(let t=e+1;t<h;t++){let r=0;for(let s=e;s<n;s++)r+=f.get(s,e)*f.get(s,t);r=-r/f.get(e,e);for(let s=e;s<n;s++)f.set(s,t,f.get(s,t)+r*f.get(s,e))}for(let t=e;t<n;t++)f.set(t,e,-f.get(t,e));f.set(e,e,1+f.get(e,e));for(let t=0;t<e-1;t++)f.set(t,e,0)}else{for(let t=0;t<n;t++)f.set(t,e,0);f.set(e,e,1)}}if(l)for(let e=r-1;e>=0;e--){if(e<w&&0!==g[e])for(let t=e+1;t<r;t++){let n=0;for(let s=e+1;s<r;s++)n+=m.get(s,e)*m.get(s,t);n=-n/m.get(e+1,e);for(let s=e+1;s<r;s++)m.set(s,t,m.get(s,t)+n*m.get(s,e))}for(let t=0;t<r;t++)m.set(t,e,0);m.set(e,e,1)}let S=k-1,N=Number.EPSILON;for(;k>0;){let e,t;for(e=k-2;e>=-1&&-1!==e;e--){const t=Number.MIN_VALUE+N*Math.abs(p[e]+Math.abs(p[e+1]));if(Math.abs(g[e])<=t||Number.isNaN(g[e])){g[e]=0;break}}if(e===k-2)t=4;else{let n;for(n=k-1;n>=e&&n!==e;n--){let t=(n!==k?Math.abs(g[n]):0)+(n!==e+1?Math.abs(g[n-1]):0);if(Math.abs(p[n])<=N*t){p[n]=0;break}}n===e?t=3:n===k-1?t=1:(t=2,e=n)}switch(e++,t){case 1:{let t=g[k-2];g[k-2]=0;for(let n=k-2;n>=e;n--){let s=R(p[n],t),a=p[n]/s,i=t/s;if(p[n]=s,n!==e&&(t=-i*g[n-1],g[n-1]=a*g[n-1]),l)for(let e=0;e<r;e++)s=a*m.get(e,n)+i*m.get(e,k-1),m.set(e,k-1,-i*m.get(e,n)+a*m.get(e,k-1)),m.set(e,n,s)}break}case 2:{let t=g[e-1];g[e-1]=0;for(let r=e;r<k;r++){let s=R(p[r],t),a=p[r]/s,i=t/s;if(p[r]=s,t=-i*g[r],g[r]=a*g[r],u)for(let t=0;t<n;t++)s=a*f.get(t,r)+i*f.get(t,e-1),f.set(t,e-1,-i*f.get(t,r)+a*f.get(t,e-1)),f.set(t,r,s)}break}case 3:{const t=Math.max(Math.abs(p[k-1]),Math.abs(p[k-2]),Math.abs(g[k-2]),Math.abs(p[e]),Math.abs(g[e])),s=p[k-1]/t,a=p[k-2]/t,i=g[k-2]/t,o=p[e]/t,c=g[e]/t,h=((a+s)*(a-s)+i*i)/2,d=s*i*(s*i);let y=0;0===h&&0===d||(y=h<0?0-Math.sqrt(h*h+d):Math.sqrt(h*h+d),y=d/(h+y));let b=(o+s)*(o-s)+y,x=o*c;for(let t=e;t<k-1;t++){let s=R(b,x);0===s&&(s=Number.MIN_VALUE);let a=b/s,i=x/s;if(t!==e&&(g[t-1]=s),b=a*p[t]+i*g[t],g[t]=a*g[t]-i*p[t],x=i*p[t+1],p[t+1]=a*p[t+1],l)for(let e=0;e<r;e++)s=a*m.get(e,t)+i*m.get(e,t+1),m.set(e,t+1,-i*m.get(e,t)+a*m.get(e,t+1)),m.set(e,t,s);if(s=R(b,x),0===s&&(s=Number.MIN_VALUE),a=b/s,i=x/s,p[t]=s,b=a*g[t]+i*p[t+1],p[t+1]=-i*g[t]+a*p[t+1],x=i*g[t+1],g[t+1]=a*g[t+1],u&&t<n-1)for(let e=0;e<n;e++)s=a*f.get(e,t)+i*f.get(e,t+1),f.set(e,t+1,-i*f.get(e,t)+a*f.get(e,t+1)),f.set(e,t,s)}g[k-2]=b;break}case 4:if(p[e]<=0&&(p[e]=p[e]<0?-p[e]:0,l))for(let t=0;t<=S;t++)m.set(t,e,-m.get(t,e));for(;e<S&&!(p[e]>=p[e+1]);){let t=p[e];if(p[e]=p[e+1],p[e+1]=t,l&&e<r-1)for(let n=0;n<r;n++)t=m.get(n,e+1),m.set(n,e+1,m.get(n,e)),m.set(n,e,t);if(u&&e<n-1)for(let r=0;r<n;r++)t=f.get(r,e+1),f.set(r,e+1,f.get(r,e)),f.set(r,e,t);e++}k--}}if(c){let e=m;m=f,f=e}this.m=n,this.n=r,this.s=p,this.U=f,this.V=m}solve(e){let t=e,n=this.threshold,r=this.s.length,s=I.zeros(r,r);for(let e=0;e<r;e++)Math.abs(this.s[e])<=n?s.set(e,e,0):s.set(e,e,1/this.s[e]);let a=this.U,i=this.rightSingularVectors,o=i.mmul(s),u=i.rows,l=a.rows,c=I.zeros(u,l);for(let e=0;e<u;e++)for(let t=0;t<l;t++){let n=0;for(let s=0;s<r;s++)n+=o.get(e,s)*a.get(t,s);c.set(e,t,n)}return c.mmul(t)}solveForDiagonal(e){return this.solve(I.diag(e))}inverse(){let e=this.V,t=this.threshold,n=e.rows,r=e.columns,s=new I(n,this.s.length);for(let a=0;a<n;a++)for(let n=0;n<r;n++)Math.abs(this.s[n])>t&&s.set(a,n,e.get(a,n)/this.s[n]);let a=this.U,i=a.rows,o=a.columns,u=new I(n,i);for(let e=0;e<n;e++)for(let t=0;t<i;t++){let n=0;for(let r=0;r<o;r++)n+=s.get(e,r)*a.get(t,r);u.set(e,t,n)}return u}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let e=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,t=0,n=this.s;for(let r=0,s=n.length;r<s;r++)n[r]>e&&t++;return t}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return I.diag(this.s)}}function F(e,t,n=!1){return e=$.checkMatrix(e),t=$.checkMatrix(t),n?new M(e).solve(t):e.isSquare()?new A(e).solve(t):new _(e).solve(t)}function D(e,t){let n=[];for(let r=0;r<e;r++)r!==t&&n.push(r);return n}function O(e,t,n,r=1e-9,s=1e-9){if(e>s)return new Array(t.rows+1).fill(0);{let e=t.addRow(n,[0]);for(let t=0;t<e.rows;t++)Math.abs(e.get(t,0))<r&&e.set(t,0,0);return e.to1DArray()}}class L{constructor(e,t={}){const{assumeSymmetric:n=!1}=t;if(!(e=$.checkMatrix(e)).isSquare())throw new Error("Matrix is not a square matrix");if(e.isEmpty())throw new Error("Matrix must be non-empty");let r,s,a=e.columns,i=new I(a,a),o=new Float64Array(a),u=new Float64Array(a),l=e,c=!1;if(c=!!n||e.isSymmetric(),c){for(r=0;r<a;r++)for(s=0;s<a;s++)i.set(r,s,l.get(r,s));!function(e,t,n,r){let s,a,i,o,u,l,c,h;for(u=0;u<e;u++)n[u]=r.get(e-1,u);for(o=e-1;o>0;o--){for(h=0,i=0,l=0;l<o;l++)h+=Math.abs(n[l]);if(0===h)for(t[o]=n[o-1],u=0;u<o;u++)n[u]=r.get(o-1,u),r.set(o,u,0),r.set(u,o,0);else{for(l=0;l<o;l++)n[l]/=h,i+=n[l]*n[l];for(s=n[o-1],a=Math.sqrt(i),s>0&&(a=-a),t[o]=h*a,i-=s*a,n[o-1]=s-a,u=0;u<o;u++)t[u]=0;for(u=0;u<o;u++){for(s=n[u],r.set(u,o,s),a=t[u]+r.get(u,u)*s,l=u+1;l<=o-1;l++)a+=r.get(l,u)*n[l],t[l]+=r.get(l,u)*s;t[u]=a}for(s=0,u=0;u<o;u++)t[u]/=i,s+=t[u]*n[u];for(c=s/(i+i),u=0;u<o;u++)t[u]-=c*n[u];for(u=0;
vendor: 10,618 bytes, line 5057
5057u<o;u++){for(s=n[u],a=t[u],l=u;l<=o-1;l++)r.set(l,u,r.get(l,u)-(s*t[l]+a*n[l]));n[u]=r.get(o-1,u),r.set(o,u,0)}}n[o]=i}for(o=0;o<e-1;o++){if(r.set(e-1,o,r.get(o,o)),r.set(o,o,1),i=n[o+1],0!==i){for(l=0;l<=o;l++)n[l]=r.get(l,o+1)/i;for(u=0;u<=o;u++){for(a=0,l=0;l<=o;l++)a+=r.get(l,o+1)*r.get(l,u);for(l=0;l<=o;l++)r.set(l,u,r.get(l,u)-a*n[l])}}for(l=0;l<=o;l++)r.set(l,o+1,0)}for(u=0;u<e;u++)n[u]=r.get(e-1,u),r.set(e-1,u,0);r.set(e-1,e-1,1),t[0]=0}(a,u,o,i),function(e,t,n,r){let s,a,i,o,u,l,c,h,d,p,f,m,g,y,b,x;for(i=1;i<e;i++)t[i-1]=t[i];t[e-1]=0;let w=0,v=0,k=Number.EPSILON;for(l=0;l<e;l++){for(v=Math.max(v,Math.abs(n[l])+Math.abs(t[l])),c=l;c<e&&!(Math.abs(t[c])<=k*v);)c++;if(c>l)do{for(s=n[l],h=(n[l+1]-s)/(2*t[l]),d=R(h,1),h<0&&(d=-d),n[l]=t[l]/(h+d),n[l+1]=t[l]*(h+d),p=n[l+1],a=s-n[l],i=l+2;i<e;i++)n[i]-=a;for(w+=a,h=n[c],f=1,m=f,g=f,y=t[l+1],b=0,x=0,i=c-1;i>=l;i--)for(g=m,m=f,x=b,s=f*t[i],a=f*h,d=R(h,t[i]),t[i+1]=b*d,b=t[i]/d,f=h/d,h=f*n[i]-b*s,n[i+1]=a+b*(f*s+b*n[i]),u=0;u<e;u++)a=r.get(u,i+1),r.set(u,i+1,b*r.get(u,i)+f*a),r.set(u,i,f*r.get(u,i)-b*a);h=-b*x*g*y*t[l]/p,t[l]=b*h,n[l]=f*h}while(Math.abs(t[l])>k*v);n[l]=n[l]+w,t[l]=0}for(i=0;i<e-1;i++){for(u=i,h=n[i],o=i+1;o<e;o++)n[o]<h&&(u=o,h=n[o]);if(u!==i)for(n[u]=n[i],n[i]=h,o=0;o<e;o++)h=r.get(o,i),r.set(o,i,r.get(o,u)),r.set(o,u,h)}}(a,u,o,i)}else{let e=new I(a,a),t=new Float64Array(a);for(s=0;s<a;s++)for(r=0;r<a;r++)e.set(r,s,l.get(r,s));!function(e,t,n,r){let s,a,i,o,u,l,c,h=e-1;for(l=1;l<=h-1;l++){for(c=0,o=l;o<=h;o++)c+=Math.abs(t.get(o,l-1));if(0!==c){for(i=0,o=h;o>=l;o--)n[o]=t.get(o,l-1)/c,i+=n[o]*n[o];for(a=Math.sqrt(i),n[l]>0&&(a=-a),i-=n[l]*a,n[l]=n[l]-a,u=l;u<e;u++){for(s=0,o=h;o>=l;o--)s+=n[o]*t.get(o,u);for(s/=i,o=l;o<=h;o++)t.set(o,u,t.get(o,u)-s*n[o])}for(o=0;o<=h;o++){for(s=0,u=h;u>=l;u--)s+=n[u]*t.get(o,u);for(s/=i,u=l;u<=h;u++)t.set(o,u,t.get(o,u)-s*n[u])}n[l]=c*n[l],t.set(l,l-1,c*a)}}for(o=0;o<e;o++)for(u=0;u<e;u++)r.set(o,u,o===u?1:0);for(l=h-1;l>=1;l--)if(0!==t.get(l,l-1)){for(o=l+1;o<=h;o++)n[o]=t.get(o,l-1);for(u=l;u<=h;u++){for(a=0,o=l;o<=h;o++)a+=n[o]*r.get(o,u);for(a=a/n[l]/t.get(l,l-1),o=l;o<=h;o++)r.set(o,u,r.get(o,u)+a*n[o])}}}(a,e,t,i),function(e,t,n,r,s){let a,i,o,u,l,c,h,d,p,f,m,g,y,b,x,w=e-1,v=e-1,k=Number.EPSILON,I=0,S=0,N=0,T=0,E=0,C=0,$=0,A=0;for(a=0;a<e;a++)for((a<0||a>v)&&(n[a]=s.get(a,a),t[a]=0),i=Math.max(a-1,0);i<e;i++)S+=Math.abs(s.get(a,i));for(;w>=0;){for(u=w;u>0&&(C=Math.abs(s.get(u-1,u-1))+Math.abs(s.get(u,u)),0===C&&(C=S),!(Math.abs(s.get(u,u-1))<k*C));)u--;if(u===w)s.set(w,w,s.get(w,w)+I),n[w]=s.get(w,w),t[w]=0,w--,A=0;else if(u===w-1){if(h=s.get(w,w-1)*s.get(w-1,w),N=(s.get(w-1,w-1)-s.get(w,w))/2,T=N*N+h,$=Math.sqrt(Math.abs(T)),s.set(w,w,s.get(w,w)+I),s.set(w-1,w-1,s.get(w-1,w-1)+I),d=s.get(w,w),T>=0){for($=N>=0?N+$:N-$,n[w-1]=d+$,n[w]=n[w-1],0!==$&&(n[w]=d-h/$),t[w-1]=0,t[w]=0,d=s.get(w,w-1),C=Math.abs(d)+Math.abs($),N=d/C,T=$/C,E=Math.sqrt(N*N+T*T),N/=E,T/=E,i=w-1;i<e;i++)$=s.get(w-1,i),s.set(w-1,i,T*$+N*s.get(w,i)),s.set(w,i,T*s.get(w,i)-N*$);for(a=0;a<=w;a++)$=s.get(a,w-1),s.set(a,w-1,T*$+N*s.get(a,w)),s.set(a,w,T*s.get(a,w)-N*$);for(a=0;a<=v;a++)$=r.get(a,w-1),r.set(a,w-1,T*$+N*r.get(a,w)),r.set(a,w,T*r.get(a,w)-N*$)}else n[w-1]=d+N,n[w]=d+N,t[w-1]=$,t[w]=-$;w-=2,A=0}else{if(d=s.get(w,w),p=0,h=0,u<w&&(p=s.get(w-1,w-1),h=s.get(w,w-1)*s.get(w-1,w)),10===A){for(I+=d,a=0;a<=w;a++)s.set(a,a,s.get(a,a)-d);C=Math.abs(s.get(w,w-1))+Math.abs(s.get(w-1,w-2)),d=p=.75*C,h=-.4375*C*C}if(30===A&&(C=(p-d)/2,C=C*C+h,C>0)){for(C=Math.sqrt(C),p<d&&(C=-C),C=d-h/((p-d)/2+C),a=0;a<=w;a++)s.set(a,a,s.get(a,a)-C);I+=C,d=p=h=.964}for(A+=1,l=w-2;l>=u&&($=s.get(l,l),E=d-$,C=p-$,N=(E*C-h)/s.get(l+1,l)+s.get(l,l+1),T=s.get(l+1,l+1)-$-E-C,E=s.get(l+2,l+1),C=Math.abs(N)+Math.abs(T)+Math.abs(E),N/=C,T/=C,E/=C,l!==u)&&!(Math.abs(s.get(l,l-1))*(Math.abs(T)+Math.abs(E))<k*(Math.abs(N)*(Math.abs(s.get(l-1,l-1))+Math.abs($)+Math.abs(s.get(l+1,l+1)))));)l--;for(a=l+2;a<=w;a++)s.set(a,a-2,0),a>l+2&&s.set(a,a-3,0);for(o=l;o<=w-1&&(b=o!==w-1,o!==l&&(N=s.get(o,o-1),T=s.get(o+1,o-1),E=b?s.get(o+2,o-1):0,d=Math.abs(N)+Math.abs(T)+Math.abs(E),0!==d&&(N/=d,T/=d,E/=d)),0!==d);o++)if(C=Math.sqrt(N*N+T*T+E*E),N<0&&(C=-C),0!==C){for(o!==l?s.set(o,o-1,-C*d):u!==l&&s.set(o,o-1,-s.get(o,o-1)),N+=C,d=N/C,p=T/C,$=E/C,T/=N,E/=N,i=o;i<e;i++)N=s.get(o,i)+T*s.get(o+1,i),b&&(N+=E*s.get(o+2,i),s.set(o+2,i,s.get(o+2,i)-N*$)),s.set(o,i,s.get(o,i)-N*d),s.set(o+1,i,s.get(o+1,i)-N*p);for(a=0;a<=Math.min(w,o+3);a++)N=d*s.get(a,o)+p*s.get(a,o+1),b&&(N+=$*s.get(a,o+2),s.set(a,o+2,s.get(a,o+2)-N*E)),s.set(a,o,s.get(a,o)-N),s.set(a,o+1,s.get(a,o+1)-N*T);for(a=0;a<=v;a++)N=d*r.get(a,o)+p*r.get(a,o+1),b&&(N+=$*r.get(a,o+2),r.set(a,o+2,r.get(a,o+2)-N*E)),r.set(a,o,r.get(a,o)-N),r.set(a,o+1,r.get(a,o+1)-N*T)}}}if(0!==S){for(w=e-1;w>=0;w--)if(N=n[w],T=t[w],0===T)for(u=w,s.set(w,w,1),a=w-1;a>=0;a--){for(h=s.get(a,a)-N,E=0,i=u;i<=w;i++)E+=s.get(a,i)*s.get(i,w);if(t[a]<0)$=h,C=E;else if(u=a,0===t[a]?s.set(a,w,0!==h?-E/h:-E/(k*S)):(d=s.get(a,a+1),p=s.get(a+1,a),T=(n[a]-N)*(n[a]-N)+t[a]*t[a],c=(d*C-$*E)/T,s.set(a,w,c),s.set(a+1,w,Math.abs(d)>Math.abs($)?(-E-h*c)/d:(-C-p*c)/$)),c=Math.abs(s.get(a,w)),k*c*c>1)for(i=a;i<=w;i++)s.set(i,w,s.get(i,w)/c)}else if(T<0)for(u=w-1,Math.abs(s.get(w,w-1))>Math.abs(s.get(w-1,w))?(s.set(w-1,w-1,T/s.get(w,w-1)),s.set(w-1,w,-(s.get(w,w)-N)/s.get(w,w-1))):(x=z(0,-s.get(w-1,w),s.get(w-1,w-1)-N,T),s.set(w-1,w-1,x[0]),s.set(w-1,w,x[1])),s.set(w,w-1,0),s.set(w,w,1),a=w-2;a>=0;a--){for(f=0,m=0,i=u;i<=w;i++)f+=s.get(a,i)*s.get(i,w-1),m+=s.get(a,i)*s.get(i,w);if(h=s.get(a,a)-N,t[a]<0)$=h,E=f,C=m;else if(u=a,0===t[a]?(x=z(-f,-m,h,T),s.set(a,w-1,x[0]),s.set(a,w,x[1])):(d=s.get(a,a+1),p=s.get(a+1,a),g=(n[a]-N)*(n[a]-N)+t[a]*t[a]-T*T,y=2*(n[a]-N)*T,0===g&&0===y&&(g=k*S*(Math.abs(h)+Math.abs(T)+Math.abs(d)+Math.abs(p)+Math.abs($))),x=z(d*E-$*f+T*m,d*C-$*m-T*f,g,y),s.set(a,w-1,x[0]),s.set(a,w,x[1]),Math.abs(d)>Math.abs($)+Math.abs(T)?(s.set(a+1,w-1,(-f-h*s.get(a,w-1)+T*s.get(a,w))/d),s.set(a+1,w,(-m-h*s.get(a,w)-T*s.get(a,w-1))/d)):(x=z(-E-p*s.get(a,w-1),-C-p*s.get(a,w),$,T),s.set(a+1,w-1,x[0]),s.set(a+1,w,x[1]))),c=Math.max(Math.abs(s.get(a,w-1)),Math.abs(s.get(a,w))),k*c*c>1)for(i=a;i<=w;i++)s.set(i,w-1,s.get(i,w-1)/c),s.set(i,w,s.get(i,w)/c)}for(a=0;a<e;a++)if(a<0||a>v)for(i=a;i<e;i++)r.set(a,i,s.get(a,i));for(i=e-1;i>=0;i--)for(a=0;a<=v;a++){for($=0,o=0;o<=Math.min(i,v);o++)$+=r.get(a,o)*s.get(o,i);r.set(a,i,$)}}}(a,u,o,i,e)}this.n=a,this.e=u,this.d=o,this.V=i}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let e,t,n=this.n,r=this.e,s=this.d,a=new I(n,n);for(e=0;e<n;e++){for(t=0;t<n;t++)a.set(e,t,0);a.set(e,e,s[e]),r[e]>0?a.set(e,e+1,r[e]):r[e]<0&&a.set(e,e-1,r[e])}return a}}function z(e,t,n,r){let s,a;return Math.abs(n)>Math.abs(r)?(s=r/n,a=n+s*r,[(e+s*t)/a,(t-s*e)/a]):(s=n/r,a=r+s*n,[(s*e+t)/a,(s*t-e)/a])}class P{constructor(e){if(!(e=$.checkMatrix(e)).isSymmetric())throw new Error("Matrix is not symmetric");let t,n,r,s=e,a=s.rows,i=new I(a,a),o=!0;for(n=0;n<a;n++){let e=0;for(r=0;r<n;r++){let a=0;for(t=0;t<r;t++)a+=i.get(r,t)*i.get(n,t);a=(s.get(n,r)-a)/i.get(r,r),i.set(n,r,a),e+=a*a}for(e=s.get(n,n)-e,o&&=e>0,i.set(n,n,Math.sqrt(Math.max(e,0))),r=n+1;r<a;r++)i.set(n,r,0)}this.L=i,this.positiveDefinite=o}isPositiveDefinite(){return this.positiveDefinite}solve(e){e=$.checkMatrix(e);let t=this.L,n=t.rows;if(e.rows!==n)throw new Error("Matrix dimensions do not match");if(!1===this.isPositiveDefinite())throw new Error("Matrix is not positive definite");let r,s,a,i=e.columns,o=e.clone();for(a=0;a<n;a++)for(s=0;s<i;s++){for(r=0;r<a;r++)o.set(a,s,o.get(a,s)-o.get(r,s)*t.get(a,r));o.set(a,s,o.get(a,s)/t.get(a,a))}for(a=n-1;a>=0;a--)for(s=0;s<i;s++){for(r=a+1;r<n;r++)o.set(a,s,o.get(a,s)-o.get(r,s)*t.get(r,a));o.set(a,s,o.get(a,s)/t.get(a,a))}return o}get lowerTriangularMatrix(){return this.L}}class B{constructor(e,t={}){e=$.checkMatrix(e);let{Y:n}=t;const{scaleScores:s=!1,maxIterations:a=1e3,terminationCriteria:i=1e-10}=t;let o;if(n){if(n=r.isAnyArray(n)&&"number"==typeof n[0]?I.columnVector(n):$.checkMatrix(n),n.rows!==e.rows)throw new Error("Y should have the same number of rows as X");o=n.getColumnVector(0)}else o=e.getColumnVector(0);let u,l,c,h,d=1;for(let t=0;t<a&&d>i;t++)c=e.transpose().mmul(o).div(o.transpose().mmul(o).get(0,0)),c=c.div(c.norm()),u=e.mmul(c).div(c.transpose().mmul(c).get(0,0)),t>0&&(d=u.clone().sub(h).pow(2).sum()),h=u.clone(),n?(l=n.transpose().mmul(u).div(u.transpose().mmul(u).get(0,0)),l=l.div(l.norm()),o=n.mmul(l).div(l.transpose().mmul(l).get(0,0))):o=u;if(n){let t=e.transpose().mmul(u).div(u.transpose().mmul(u).get(0,0));t=t.div(t.norm());let r=e.clone().sub(u.clone().mmul(t.transpose())),s=o.transpose().mmul(u).div(u.transpose().mmul(u).get(0,0)),a=n.clone().sub(u.clone().mulS(s.get(0,0)).mmul(l.transpose()));this.t=u,this.p=t.transpose(),this.w=c.transpose(),this.q=l,this.u=o,this.s=u.transpose().mmul(u),this.xResidual=r,this.yResidual=a,this.betas=s}else this.w=c.transpose(),this.s=u.transpose().mmul(u).sqrt(),this.t=s?u.clone().div(this.s.get(0,0)):u,this.xResidual=e.sub(u.mmul(c.transpose()))}}t.AbstractMatrix=w,t.CHO=P,t.CholeskyDecomposition=P,t.DistanceMatrix=N,t.EVD=L,t.EigenvalueDecomposition=L,t.LU=A,t.LuDecomposition=A,t.Matrix=I,t.MatrixColumnSelectionView=class extends T{constructor(e,t){m(e,t),super(e,e.rows,t.length),this.columnIndices=t}set(e,t,n){return this.matrix.set(e,this.columnIndices[t],n),this}get(e,t){return this.matrix.get(e,this.columnIndices[t])}},t.MatrixColumnView=class extends T{constructor(e,t){h(e,t),super(e,e.rows,1),this.column=t}set(e,t,n){return this.matrix.set(e,this.column,n),this}get(e){return this.matrix.get(e,this.column)}},t.MatrixFlipColumnView=class extends T{constructor(e){super(e,e.rows,e.columns)}set(e,t,n){return this.matrix.set(e,this.columns-t-1,n),this}get(e,t){return this.matrix.get(e,this.columns-t-1)}},t.MatrixFlipRowView=class extends T{constructor(e){super(e,e.rows,e.columns)}set(e,t,n){return this.matrix.set(this.rows-e-1,t,n),this}get(e,t){return this.matrix.get(this.rows-e-1,t)}},t.MatrixRowSelectionView=class extends T{constructor(e,t){f(e,t),super(e,t.length,e.columns),this.rowIndices=t}set(e,t,n){return this.matrix.set(this.rowIndices[e],t,n),this}get(e,t){return this.matrix.get(this.rowIndices[e],t)}},t.MatrixRowView=class extends T{constructor(e,t){c(e,t),super(e,1,e.columns),this.row=t}set(e,t,n){return this.matrix.set(this.row,t,n),this}get(e,t){return this.matrix.get(this.row,t)}},t.MatrixSelectionView=E,t.MatrixSubView=class extends T{constructor(e,t,n,r,s
5057){g(e,t,n,r,s),super(e,n-t+1,s-r+1),this.startRow=t,this.startColumn=r}set(e,t,n){return this.matrix.set(this.startRow+e,this.startColumn+t,n),this}get(e,t){return this.matrix.get(this.startRow+e,this.startColumn+t)}},t.MatrixTransposeView=class extends T{constructor(e){super(e,e.columns,e.rows)}set(e,t,n){return this.matrix.set(t,e,n),this}get(e,t){return this.matrix.get(t,e)}},t.NIPALS=B,t.Nipals=B,t.QR=_,t.QrDecomposition=_,t.SVD=M,t.SingularValueDecomposition=M,t.SymmetricMatrix=S,t.WrapperMatrix1D=C,t.WrapperMatrix2D=$,t.correlation=function(e,t=e,n={}){e=new I(e);let s=!1;if("object"!=typeof t||I.isMatrix(t)||r.isAnyArray(t)?t=new I(t):(n=t,t=e,s=!0),e.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:a=!0,scale:i=!0}=n;a&&(e.center("column"),s||t.center("column")),i&&(e.scale("column"),s||t.scale("column"));const o=e.standardDeviation("column",{unbiased:!0}),u=s?o:t.standardDeviation("column",{unbiased:!0}),l=e.transpose().mmul(t);for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)*(1/(o[t]*u[n]))*(1/(e.rows-1)));return l},t.covariance=function(e,t=e,n={}){e=new I(e);let s=!1;if("object"!=typeof t||I.isMatrix(t)||r.isAnyArray(t)?t=new I(t):(n=t,t=e,s=!0),e.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:a=!0}=n;a&&(e=e.center("column"),s||(t=t.center("column")));const i=e.transpose().mmul(t);for(let t=0;t<i.rows;t++)for(let n=0;n<i.columns;n++)i.set(t,n,i.get(t,n)*(1/(e.rows-1)));return i},t.default=I,t.determinant=function e(t){if((t=I.checkMatrix(t)).isSquare()){if(0===t.columns)return 1;let n,r,s,a;if(2===t.columns)return n=t.get(0,0),r=t.get(0,1),s=t.get(1,0),a=t.get(1,1),n*a-r*s;if(3===t.columns){let a,i,o;return a=new E(t,[1,2],[1,2]),i=new E(t,[1,2],[0,2]),o=new E(t,[1,2],[0,1]),n=t.get(0,0),r=t.get(0,1),s=t.get(0,2),n*e(a)-r*e(i)+s*e(o)}return new A(t).determinant}throw Error("determinant can only be calculated for a square matrix")},t.inverse=function(e,t=!1){return e=$.checkMatrix(e),t?new M(e).inverse():F(e,I.eye(e.rows))},t.linearDependencies=function(e,t={}){const{thresholdValue:n=1e-9,thresholdError:r=1e-9}=t;let s=(e=I.checkMatrix(e)).rows,a=new I(s,s);for(let t=0;t<s;t++){let i=I.columnVector(e.getRow(t)),o=e.subMatrixRow(D(s,t)).transpose(),u=new M(o).solve(i),l=I.sub(i,o.mmul(u)).abs().max();a.setRow(t,O(l,u,t,n,r))}return a},t.pseudoInverse=function(e,t=Number.EPSILON){if((e=I.checkMatrix(e)).isEmpty())return e.transpose();let n=new M(e,{autoTranspose:!0}),r=n.leftSingularVectors,s=n.rightSingularVectors,a=n.diagonal;for(let e=0;e<a.length;e++)Math.abs(a[e])>t?a[e]=1/a[e]:a[e]=0;return s.mmul(I.diag(a).mmul(r.transpose()))},t.solve=F,t.wrap=function(e,t){if(r.isAnyArray(e))return e[0]&&r.isAnyArray(e[0])?new $(e):new C(e,t);throw new Error("the argument is not an array")}},717:function(e,t,n){var r;!function(e,s){function a(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,s=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^s,s=s-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^s,t.a=s-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function o(e,t){var n=new a(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.tychei=o}(0,e=n.nmd(e),n.amdD)},718:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>s});var r=n(788);function s(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,r.isAnyArray)(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");if(void 0!==n.output){if(!(0,r.isAnyArray)(n.output))throw new TypeError("output option must be an array if specified");t=n.output}else t=new Array(e.length);var s=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,r.isAnyArray)(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var n=t.fromIndex,s=void 0===n?0:n,a=t.toIndex,i=void 0===a?e.length:a;if(s<0||s>=e.length||!Number.isInteger(s))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=s||i>e.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var o=e[s],u=s+1;u<i;u++)e[u]<o&&(o=e[u]);return o}(e),a=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,r.isAnyArray)(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var n=t.fromIndex,s=void 0===n?0:n,a=t.toIndex,i=void 0===a?e.length:a;if(s<0||s>=e.length||!Number.isInteger(s))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=s||i>e.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var o=e[s],u=s+1;u<i;u++)e[u]>
5057o&&(o=e[u]);return o}(e);if(s===a)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var i=n.min,o=void 0===i?n.autoMinMax?s:0:i,u=n.max,l=void 0===u?n.autoMinMax?a:1:u;if(o>=l)throw new RangeError("min option must be smaller than max option");for(var c=(l-o)/(a-s),h=0;h<e.length;h++)t[h]=(e[h]-s)*c+o;return t}},743:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,o)}u((r=r.apply(e,t||[])).next())})},s=this&&this.__generator||function(e,t){var n,r,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var a=n(848),i=function(){function e(){}return e.prototype.initialize=function(){return r(this,void 0,void 0,function(){var e,t;return s(this,function(n){switch(n.label){case 0:return[4,a.FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm")];case 1:return e=n.sent(),t=this,[4,a.FaceLandmarker.createFromOptions(e,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",delegate:"GPU"},outputFaceBlendshapes:!0,outputFacialTransformationMatrixes:!0,runningMode:"IMAGE",numFaces:1})];case 2:return t.faceLandmarker=n.sent(),[2]}})})},e.prototype.processFrame=function(e){return r(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this.faceLandmarker?[4,this.faceLandmarker.detect(e)]:(console.error("FaceLandmarker is not loaded yet."),[2,null]);case 1:return[2,t.sent()]}})})},e}();t.default=i},788:(e,t,n)=>{"use strict";n.r(t),n.d(t,{isAnyArray:()=>s});const r=Object.prototype.toString;function s(e){const t=r.call(e);return t.endsWith("Array]")&&!t.includes("Big")}},801:function(e,t,n){var r;!function(s,a,i){var o,u=256,l=i.pow(u,6),c=i.pow(2,52),h=2*c,d=255;function p(e,t,n){var r=[],d=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(u):(e=new Uint8Array(u),(s.crypto||s.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=s.navigator,n=t&&t.plugins;return[+new Date,s,n,s.screen,b(a)]}}():e,3),r),p=new f(r),x=function(){for(var e=p.g(6),t=l,n=0;e<c;)e=(e+n)*u,t*=u,n=p.g(1);for(;e>=h;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|p.g(4)},x.quick=function(){return p.g(4)/4294967296},x.double=x,y(b(p.S),a),(t.pass||n||function(e,t,n,r){return r&&(r.S&&m(r,p),e.state=function(){return m(p,{})}),n?(i.random=e,t):e})(x,d,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,r=this,s=0,a=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);s<u;)i[s]=s++;for(s=0;s<u;s++)i[s]=i[a=d&a+e[s%n]+(t=i[s])],i[a]=t;(r.g=function(e){for(var t,n=0,s=r.i,a=r.j,i=r.S;e--;)t=i[s=d&s+1],n=n*u+i[d&(i[s]=i[a=d&a+t])+(i[a]=t)];return r.i=s,r.j=a,n})(u)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function g(e,t){var n,r=[],s=typeof e;if(t&&"object"==s)for(n in e)try{r.push(g(e[n],t-1))}catch(e){}return r.length?r:"string"==s?e:e+"\\0"}function y(e,t){for(var n,r=e+"",s=0;s<r.length;)t[d&s]=d&(n^=19*t[d&s])+r.charCodeAt(s++);return b(t)}function b(e){return String.fromCharCode.apply(0,e)}if(y(i.random(),a),e.exports){e.exports=p;try{o=n(234)}catch(e){}}else void 0===(r=function(){return p}.call(t,n,t,e))||(e.exports=r)}("undefined"!=typeof self?self:this,[],Math)},817:()=>{},833:function(e,t,n){var r;!function(e,s){function a(e){var t=this;t.next=function(){var e,n,r=t.w,s=t.X,a=t.i;return t.w=r=r+1640531527|0,n=s[a+34&127],e=s[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=s[a]=n^e,t.i=a,n+(r^r>>>16)|0},function(e,t){var n,r,s,a,i,o=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\\0",r=0,u=Math.max(u,t.length)),s=0,a=-32;a<u;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,s=0==(n=o[127&a]^=r+i)?s+1:0);for(s>=128&&(o[127&(t&&t.length||0)]=-1),s=127,a=512;a>0;--a)r=o[s+34&127],n=o[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[s]=r^n;e.w=i,e.X=o,e.i=s}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new a(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e}
5057,s.int32=n.next,s.quick=s,r&&(r.X&&i(r,n),s.state=function(){return i(n,{})}),s}s&&s.exports?s.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,s))||(s.exports=r):this.xor4096=o}(0,e=n.nmd(e),n.amdD)},848:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n="undefined"!=typeof self?self:{};function r(e,t){e:{for(var r=["CLOSURE_FLAGS"],s=n,a=0;a<r.length;a++)if(null==(s=s[r[a]])){r=null;break e}r=s}return null!=(e=r&&r[e])?e:t}function s(){throw Error("Invalid UTF8")}function a(e,t){return t=String.fromCharCode.apply(null,t),null==e?t:e+t}let i,o;const u="undefined"!=typeof TextDecoder;let l;const c="undefined"!=typeof TextEncoder;function h(e){if(c)e=(l||=new TextEncoder).encode(e);else{let n=0;const r=new Uint8Array(3*e.length);for(let s=0;s<e.length;s++){var t=e.charCodeAt(s);if(t<128)r[n++]=t;else{if(t<2048)r[n++]=t>>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&s<e.length){const a=e.charCodeAt(++s);if(a>=56320&&a<=57343){t=1024*(t-55296)+a-56320+65536,r[n++]=t>>18|240,r[n++]=t>>12&63|128,r[n++]=t>>6&63|128,r[n++]=63&t|128;continue}s--}t=65533}r[n++]=t>>12|224,r[n++]=t>>6&63|128}r[n++]=63&t|128}}e=n===r.length?r:r.subarray(0,n)}return e}var d,p=r(610401301,!1),f=r(653718497,r(1,!0));const m=n.navigator;function g(e){return!!p&&!!d&&d.brands.some(({brand:t})=>t&&-1!=t.indexOf(e))}function y(e){var t;return(t=n.navigator)&&(t=t.userAgent)||(t=""),-1!=t.indexOf(e)}function b(){return!!p&&!!d&&d.brands.length>0}function x(){return b()?g("Chromium"):(y("Chrome")||y("CriOS"))&&!(!b()&&y("Edge"))||y("Silk")}function w(e){return w[" "](e),e}d=m&&m.userAgentData||null,w[" "]=function(){};var v=!b()&&(y("Trident")||y("MSIE"));!y("Android")||x(),x(),y("Safari")&&(x()||!b()&&y("Coast")||!b()&&y("Opera")||!b()&&y("Edge")||(b()?g("Microsoft Edge"):y("Edg/"))||b()&&g("Opera"));var k={},I=null;function S(){if(!I){I={};for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"],n=0;n<5;n++){var r=e.concat(t[n].split(""));k[n]=r;for(var s=0;s<r.length;s++){var a=r[s];void 0===I[a]&&(I[a]=s)}}}}var N="undefined"!=typeof Uint8Array,T=!v&&"function"==typeof btoa;function E(e){if(!T){var t;void 0===t&&(t=0),S(),t=k[t];var n=Array(Math.floor(e.length/3)),r=t[64]||"";let u=0,l=0;for(;u<e.length-2;u+=3){var s=e[u],a=e[u+1],i=e[u+2],o=t[s>>2];s=t[(3&s)<<4|a>>4],a=t[(15&a)<<2|i>>6],i=t[63&i],n[l++]=o+s+a+i}switch(o=0,i=r,e.length-u){case 2:i=t[(15&(o=e[u+1]))<<2]||r;case 1:e=e[u],n[l]=t[e>>2]+t[(3&e)<<4|o>>4]+i+r}return n.join("")}for(t="",n=0,r=e.length-10240;n<r;)t+=String.fromCharCode.apply(null,e.subarray(n,n+=10240));return t+=String.fromCharCode.apply(null,n?e.subarray(n):e),btoa(t)}const C=/[-_.]/g,$={"-":"+",_:"/",".":"="};function A(e){return $[e]||""}function R(e){if(!T)return function(e){var t=e.length,n=3*t/4;n%3?n=Math.floor(n):-1!="=.".indexOf(e[t-1])&&(n=-1!="=.".indexOf(e[t-2])?n-2:n-1);var r=new Uint8Array(n),s=0;return function(e,t){function n(t){for(;r<e.length;){var n=e.charAt(r++),s=I[n];if(null!=s)return s;if(!/^[\\s\\xa0]*$/.test(n))throw Error("Unknown base64 encoding at char: "+n)}return t}S();for(var r=0;;){var s=n(-1),a=n(0),i=n(64),o=n(64);if(64===o&&-1===s)break;t(s<<2|a>>4),64!=i&&(t(a<<4&240|i>>2),64!=o&&t(i<<6&192|o))}}(e,function(e){r[s++]=e}),s!==n?r.subarray(0,s):r}(e);C.test(e)&&(e=e.replace(C,A)),e=atob(e);const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function _(e){return N&&null!=e&&e instanceof Uint8Array}var M={};let F;function D(e){if(e!==M)throw Error("illegal external caller")}function O(){return F||=new z(null,M)}function L(e){D(M);var t=e.g;return null==(t=null==t||_(t)?t:"string"==typeof t?R(t):null)?t:e.g=t}var z=class{constructor(e,t){if(D(t),this.g=e,null!=e&&0===e.length)throw Error("ByteString should be constructed with non-empty values")}h(){return new Uint8Array(L(this)||0)}};function P(e,t){e.__closure__error__context__984382||(e.__closure__error__context__984382={}),e.__closure__error__context__984382.severity=t}let B;function V(){const e=Error();P(e,"incident"),function(e){n.setTimeout(()=>{throw e},0)}(e)}function U(e){return P(e=Error(e),"warning"),e}function W(){return"function"==typeof BigInt}function G(e){return Array.prototype.slice.call(e)}var H="function"==typeof Symbol&&"symbol"==typeof Symbol();function j(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol()?Symbol():e}var q=j(),K=j("0di"),X=j("2ex"),Y=j("1oa"),J=j("0dg"),Z=H?(e,t)=>{e[q]|=t}:(e,t)=>{void 0!==e.G?e.G|=t:Object.defineProperties(e,{G:{value:t,configurable:!0,writable:!0,enumerable:!1}})},Q=H?(e,t)=>{e[q]&=~t}:(e,t)=>{void 0!==e.G&&(e.G&=~t)},ee=H?e=>
50570|e[q]:e=>0|e.G,te=H?e=>e[q]:e=>e.G,ne=H?(e,t)=>{e[q]=t}:(e,t)=>{void 0!==e.G?e.G=t:Object.defineProperties(e,{G:{value:t,configurable:!0,writable:!0,enumerable:!1}})};function re(e){return Z(e,34),e}function se(e,t){ne(t,-30975&e)}function ae(e,t){ne(t,-30941&e|34)}var ie,oe={},ue={};function le(e){return!(!e||"object"!=typeof e||e.Ja!==ue)}function ce(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&e.constructor===Object}function he(e,t,n){if(null!=e)if("string"==typeof e)e=e?new z(e,M):O();else if(e.constructor!==z)if(_(e))e=e.length?new z(n?e:new Uint8Array(e),M):O();else{if(!t)throw Error();e=void 0}return e}function de(e){return!(!Array.isArray(e)||e.length||!(1&ee(e)))}const pe=[];function fe(e){if(2&e)throw Error()}ne(pe,55),ie=Object.freeze(pe);class me{constructor(e,t,n){this.l=0,this.g=e,this.h=t,this.m=n}next(){if(this.l<this.g.length){const e=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,e):e}}return{done:!0,value:void 0}}[Symbol.iterator](){return new me(this.g,this.h,this.m)}}let ge;function ye(e,t){(t=ge?t[ge]:void 0)&&(e[ge]=G(t))}var be=Object.freeze({}),xe=Object.freeze({}),we=Object.freeze({});function ve(e){return e.Qa=!0,e}var ke=ve(e=>"number"==typeof e),Ie=ve(e=>"string"==typeof e),Se=ve(e=>"boolean"==typeof e),Ne="function"==typeof n.BigInt&&"bigint"==typeof n.BigInt(0),Te=ve(e=>Ne?e>=Ce&&e<=Ae:"-"===e[0]?Re(e,Ee):Re(e,$e));const Ee=Number.MIN_SAFE_INTEGER.toString(),Ce=Ne?BigInt(Number.MIN_SAFE_INTEGER):void 0,$e=Number.MAX_SAFE_INTEGER.toString(),Ae=Ne?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Re(e,t){if(e.length>t.length)return!1;if(e.length<t.length||e===t)return!0;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(r>s)return!1;if(r<s)return!0}}const _e="function"==typeof Uint8Array.prototype.slice;let Me,Fe=0,De=0;function Oe(e){const t=e>>>0;Fe=t,De=(e-t)/4294967296>>>0}function Le(e){if(e<0){Oe(-e);const[t,n]=Ge(Fe,De);Fe=t>>>0,De=n>>>0}else Oe(e)}function ze(e){const t=Me||=new DataView(new ArrayBuffer(8));t.setFloat32(0,+e,!0),De=0,Fe=t.getUint32(0,!0)}function Pe(e,t){return 4294967296*t+(e>>>0)}function Be(e,t){const n=2147483648&t;return n&&(t=~t>>>0,0==(e=1+~e>>>0)&&(t=t+1>>>0)),e=Pe(e,t),n?-e:e}function Ve(e,t){if(e>>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+e);else W()?n=""+(BigInt(t)<<BigInt(32)|BigInt(e)):(e=(16777215&e)+6777216*(n=16777215&(e>>>24|t<<8))+6710656*(t=t>>16&65535),n+=8147497*t,t*=2,e>=1e7&&(n+=e/1e7>>>0,e%=1e7),n>=1e7&&(t+=n/1e7>>>0,n%=1e7),n=t+Ue(n)+Ue(e));return n}function Ue(e){return e=String(e),"0000000".slice(e.length)+e}function We(e){if(e.length<16)Le(Number(e));else if(W())e=BigInt(e),Fe=Number(e&BigInt(4294967295))>>>0,De=Number(e>>BigInt(32)&BigInt(4294967295));else{const t=+("-"===e[0]);De=Fe=0;const n=e.length;for(let r=t,s=(n-t)%6+t;s<=n;r=s,s+=6){const t=Number(e.slice(r,s));De*=1e6,Fe=1e6*Fe+t,Fe>=4294967296&&(De+=Math.trunc(Fe/4294967296),De>>>=0,Fe>>>=0)}if(t){const[e,t]=Ge(Fe,De);Fe=e,De=t}}}function Ge(e,t){return t=~t,e?e=1+~e:t+=1,[e,t]}function He(e){return null==e||"number"==typeof e?e:"NaN"===e||"Infinity"===e||"-Infinity"===e?Number(e):void 0}function je(e){return null==e||"boolean"==typeof e?e:"number"==typeof e?!!e:void 0}const qe=/^-?([1-9][0-9]*|0)(\\.[0-9]+)?$/;function Ke(e){const t=typeof e;switch(t){case"bigint":return!0;case"number":return Number.isFinite(e)}return"string"===t&&qe.test(e)}function Xe(e){if(null==e)return e;if("string"==typeof e){if(!e)return;e=+e}return"number"==typeof e&&Number.isFinite(e)?0|e:void 0}function Ye(e){if(null==e)return e;if("string"==typeof e){if(!e)return;e=+e}return"number"==typeof e&&Number.isFinite(e)?e>>>0:void 0}function Je(e){return"-"!==e[0]&&(e.length<20||20===e.length&&Number(e.substring(0,6))<184467)}function Ze(e){return e=Math.trunc(e),Number.isSafeInteger(e)||(Le(e),e=Be(Fe,De)),e}function Qe(e){var t=Math.trunc(Number(e));if(Number.isSafeInteger(t))return String(t);if(-1!==(t=e.indexOf("."))&&(e=e.substring(0,t)),!("-"===e[0]?e.length<20||20===e.length&&Number(e.substring(0,7))>-922337:e.length<19||19===e.length&&Number(e.substring(0,6))<922337))if(We(e),e=Fe,2147483648&(t=De))if(W())e=""+(BigInt(0|t)<<BigInt(32)|BigInt(e>>>0));else{const[n,r]=Ge(e,t);e="-"+Ve(n,r)}else e=Ve(e,t);return e}function et(e){return null==e?e:"bigint"==typeof e?(Te(e)?e=Number(e):(e=BigInt.asIntN(64,e),e=Te(e)?Number(e):String(e)),e):Ke(e)?"number"==typeof e?Ze(e):Qe(e):void 0}function tt(e){if("string"!=typeof e)throw Error();return e}function nt(e){if(null!=e&&"string"!=typeof e)throw Error();return e}function rt(e){return null==e||"string"==typeof e?e:void 0}function st(e,t,n,r){if(null!=e&&"object"==typeof e&&e.X===oe)return e;if(!Array.isArray(e))return n?2&r?(e=t[K])?t=e:(re((e=new t).u),t=t[K]=e):t=new t:t=void 0,t;let s=n=ee(e);return 0===s&&(s|=32&r),s|=2&r,s!==n&&ne(e,s),new t(e)}function at(e,t,n){if(t)e:{if(!Ke(t=e))throw U("int64");switch(typeof t){case"string":t=Qe(t);break e;case"bigint":if(e=t=BigInt.asIntN(64,t),Ie(e)){if(!/^\\s*(?:-?[1-9]\\d*|0)?\\s*$/.test(e))throw Error(String(e))}else if(ke(e)&&!Number.isSafeInteger(e))throw Error(String(e));t=Ne?BigInt(t):Se(t)?t?"1":"0":Ie(t)?t.trim()||"0":String(t);break e;default:t=Ze(t)}}else t=et(e);return"string"==typeof(n=null==(e=t)?n?0:void 0:e)&&(t=+n,Number.isSafeInteger(t))?t:n}function it(e){if(void 0===lt&&(lt="function"==typeof Proxy?yt(Proxy):null),!lt||!gt())return e;let t=ot?.get(e);return t||(Math.random()>.01?e:(function(e){if(void 0===ht){const e=new lt([],{});ht=1===Array.prototype.concat.call([],e).length}ht&&"function"==typeof Symbol&&Symbol.isConcatSpreadable&&(e[Symbol.isConcatSpreadable]=!0)}(e),t=new lt(e,{set:(e,t,n)=>(V(),e[t]=n,!0)}),function(e,t){(ot||=new ct).set(e,t),(ut||=new ct).set(t,e)}(e,t),t))}let ot,ut,lt,ct,ht,dt,pt,ft,mt;function gt(){return void 0===ct&&(ct="function"==typeof WeakMap?yt(WeakMap):null),ct}function yt(e){try{return-1!==e.toString().indexOf("[native code]")?e:null}catch{return null}}function bt(e,t,n){if(gt()){if(dt?.get(t)?.get(e)){if(n)return}else if(Math.random()>.01)return;var r=e.length;n={length:r};for(var s=0;s<Math.min(r,10);s++){if(r<=10)var a=s;else{a=r/10;const e=Math.floor(s*a);a=e+Math.floor(Math.random()*(Math.floor((s+1)*a)-e))}n[a]=e[a]}wt(e,n)?((s=(r=dt||=new ct).get(t))||(s=new ct,r.set(t,s)),s.set(e,n)):(V(),kt(e,t))}}function xt(e,t){const n=dt?.get(t)?.get(e);n&&!wt(e,n)&&(V(),kt(e,t))}function wt(e,t){if(e.length!==t.length)return!1;for(const s in t){var n,r=Number(s);if((n=Number.isInteger(r))&&(n=e[r],r=t[r],n=!(Number.isNaN(n)?Number.isNaN(r):n===r)),n)return!1}return!0}function vt(e){if(e&&dt?.has(e)){var t=e.u;if(t)for(let n=0;n<t.length;n++){const r=t[n];
5057if(n===t.length-1&&ce(r))for(const t in r){const n=r[t];Array.isArray(n)&&xt(n,e)}else Array.isArray(r)&&xt(r,e)}}}function kt(e,t){dt?.get(t)?.delete(e)}function It(e,t,n){return e=St(e,t[0],t[1],n?1:2),t!==ft&&n&&Z(e,16384),e}function St(e,t,n,r){if(r=r??0,null==e&&(e=pt),pt=void 0,null==e){var s=96;n?(e=[n],s|=512):e=[],t&&(s=-33521665&s|(1023&t)<<15)}else{if(!Array.isArray(e))throw Error("narr");if(2048&(s=ee(e)))throw Error("farr");if(64&s)return e;if(1===r||2===r||(s|=64),n&&(s|=512,n!==e[0]))throw Error("mid");e:{if(r=(n=e).length){const e=r-1;if(ce(n[e])){if((t=e-(+!!(512&(s|=256))-1))>=1024)throw Error("pvtlmt");s=-33521665&s|(1023&t)<<15;break e}}if(t){if((t=Math.max(t,r-(+!!(512&s)-1)))>1024)throw Error("spvt");s=-33521665&s|(1023&t)<<15}}}return ne(e,s),e}const Nt={};let Tt=function(){try{return w(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class Et{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,t){return this.g.set(e,t),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,t){return this.g.forEach(e,t)}[Symbol.iterator](){return this.entries()}}const Ct=Tt?(Object.setPrototypeOf(Et.prototype,Map.prototype),Object.defineProperties(Et.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Et):class extends Map{constructor(){super()}};function $t(e){return e}function At(e){if(2&e.M)throw Error("Cannot mutate an immutable Map")}var Rt=class extends Ct{constructor(e,t,n=$t,r=$t){super();let s=ee(e);s|=64,ne(e,s),this.M=s,this.T=t,this.S=n,this.Z=this.T?_t:r;for(let a=0;a<e.length;a++){const i=e[a],o=n(i[0],!1,!0);let u=i[1];t?void 0===u&&(u=null):u=r(i[1],!1,!0,void 0,void 0,s),super.set(o,u)}}pa(e=Mt){if(0!==this.size)return this.Y(e)}Y(e=Mt){const t=[],n=super.entries();for(var r;!(r=n.next()).done;)(r=r.value)[0]=e(r[0]),r[1]=e(r[1]),t.push(r);return t}clear(){At(this),super.clear()}delete(e){return At(this),super.delete(this.S(e,!0,!1))}entries(){var e=this.oa();return new me(e,Ft,this)}keys(){return this.Ia()}values(){var e=this.oa();return new me(e,Rt.prototype.get,this)}forEach(e,t){super.forEach((n,r)=>{e.call(t,this.get(r),r,this)})}set(e,t){return At(this),null==(e=this.S(e,!0,!1))?this:null==t?(super.delete(e),this):super.set(e,this.Z(t,!0,!0,this.T,!1,this.M))}Oa(e){const t=this.S(e[0],!1,!0);e=e[1],e=this.T?void 0===e?null:e:this.Z(e,!1,!0,void 0,!1,this.M),super.set(t,e)}has(e){return super.has(this.S(e,!1,!1))}get(e){e=this.S(e,!1,!1);const t=super.get(e);if(void 0!==t){var n=this.T;return n?((n=this.Z(t,!1,!0,n,this.ta,this.M))!==t&&super.set(e,n),n):t}}oa(){return Array.from(super.keys())}Ia(){return super.keys()}[Symbol.iterator](){return this.entries()}};function _t(e,t,n,r,s,a){return e=st(e,r,n,a),s&&(e=Gt(e)),e}function Mt(e){return e}function Ft(e){return[e,this.get(e)]}let Dt;function Ot(){return Dt||=new Rt(re([]),void 0,void 0,void 0,Nt)}function Lt(e,t,n,r,s){if(null!=e){if(Array.isArray(e))e=de(e)?void 0:s&&2&ee(e)?e:zt(e,t,n,void 0!==r,s);else if(ce(e)){const a={};for(let i in e)a[i]=Lt(e[i],t,n,r,s);e=a}else e=t(e,r);return e}}function zt(e,t,n,r,s){const a=r||n?ee(e):0;r=r?!!(32&a):void 0;const i=G(e);for(let e=0;e<i.length;e++)i[e]=Lt(i[e],t,n,r,s);return n&&(ye(i,e),n(a,i)),i}function Pt(e){return Lt(e,Bt,void 0,void 0,!1)}function Bt(e){return e.X===oe?e.toJSON():e instanceof Rt?e.pa(Pt):function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"bigint":return Te(e)?Number(e):String(e);case"boolean":return e?1:0;case"object":if(e)if(Array.isArray(e)){if(de(e))return}else{if(_(e))return E(e);if(e instanceof z){const t=e.g;return null==t?"":"string"==typeof t?t:e.g=E(t)}if(e instanceof Rt)return e.pa()}}return e}(e)}function Vt(e,t,n=ae){if(null!=e){if(N&&e instanceof Uint8Array)return t?e:new Uint8Array(e);if(Array.isArray(e)){var r=ee(e);return 2&r?e:(t&&=0===r||!!(32&r)&&!(64&r||!(16&r)),t?(ne(e,-12293&r|34),e):zt(e,Vt,4&r?ae:n,!0,!0))}return e.X===oe?(n=e.u,e=2&(r=te(n))?e:Ut(e,n,r,!0)):e instanceof Rt&&!(2&e.M)&&(n=re(e.Y(Vt)),e=new Rt(n,e.T,e.S,e.Z)),e}}function Ut(e,t,n,r){return vt(e),e=e.constructor,pt=t=Wt(t,n,r),t=new e(t),pt=void 0,t}function Wt(e,t,n){const r=n||2&t?ae:se,s=!!(32&t);return e=function(e,t,n){const r=G(e);var s=r.length;const a=256&t?r[s-1]:void 0;for(s+=a?-1:0,t=512&t?1:0;t<s;t++)r[t]=n(r[t]);if(a){t=r[t]={};for(const e in a)t[e]=n(a[e])}return ye(r,e),r}(e,t,e=>Vt(e,s,r)),Z(e,32|(n?2:0)),e}function Gt(e){const t=e.u,n=te(t);return 2&n?Ut(e,t,n,!1):e}function Ht(e,t,n,r){return!(4&t&&(null==n||(!r&&0===n&&(4096&t||8192&t)&&(e.constructor[J]=1+(0|e.constructor[J]))<5&&
5057V(),0===n||n&t)))}function jt(e,t){return Kt(e=e.u,te(e),t)}function qt(e,t,n,r){if(!((t=r+(+!!(512&t)-1))<0||t>=e.length||t>=n))return e[t]}function Kt(e,t,n,r){if(-1===n)return null;const s=t>>15&1023||536870912;if(!(n>=s)){var a=e.length;return r&&256&t&&null!=(r=e[a-1][n])?(qt(e,t,s,n)&&null!=X&&((t=(e=B??={})[X]||0)>=4||(e[X]=t+1,V())),r):qt(e,t,s,n)}return 256&t?e[e.length-1][n]:void 0}function Xt(e,t,n){const r=e.u;let s=te(r);return fe(s),Yt(r,s,t,n),e}function Yt(e,t,n,r){const s=t>>15&1023||536870912;if(n>=s){let a,i=t;if(256&t)a=e[e.length-1];else{if(null==r)return i;a=e[s+(+!!(512&t)-1)]={},i|=256}return a[n]=r,n<s&&(e[n+(+!!(512&t)-1)]=void 0),i!==t&&ne(e,i),i}return e[n+(+!!(512&t)-1)]=r,256&t&&n in(e=e[e.length-1])&&delete e[n],t}function Jt(e,t,n,r,s){var a=2&t;s=Kt(e,t,n,s),Array.isArray(s)||(s=ie);const i=!(2&r);r=!(1&r);const o=!!(32&t);let u=ee(s);return 0!==u||!o||a||i?1&u||(u|=1,ne(s,u)):(u|=33,ne(s,u)),a?(e=!1,2&u||(re(s),e=!!(4&u)),(r||e)&&Object.freeze(s)):(a=!!(2&u)||!!(2048&u),r&&a?(s=G(s),a=1,o&&!i&&(a|=32),ne(s,a),Yt(e,t,n,s)):i&&32&u&&!a&&Q(s,32)),s}function Zt(e,t){e=e.u;let n=te(e);const r=Kt(e,n,t),s=He(r);return null!=s&&s!==r&&Yt(e,n,t,s),s}function Qt(e){e=e.u;let t=te(e);const n=Kt(e,t,1),r=he(n,!0,!!(34&t));return null!=r&&r!==n&&Yt(e,t,1,r),r}function en(){return void 0===be?2:5}function tn(e,t,n,r,s,a){const i=e.u;let o=te(i);r=2&o?1:r,a=!!a,s=nn(i,o,t,s);var u=ee(s),l=s;if(xt(l,e),2!==r&&1!==r||kt(l,e),Ht(e,u,void 0,a)){4&u&&(s=G(s),u=xn(u,o),o=Yt(i,o,t,s));let e=l=0;for(;l<s.length;l++){const t=n(s[l]);null!=t&&(s[e++]=t)}e<l&&(s.length=e),u=-4097&(u=rn(u,o))|20,ne(s,u&=-8193),2&u&&Object.freeze(s)}let c;return 1===r||4===r&&32&u?sn(u)||(e=u,(u|=2)!==e&&ne(s,u),Object.freeze(s)):(n=5===r&&(!!(32&u)||sn(u)||!!ot?.get(s)),(2===r||n)&&sn(u)&&(s=G(s),u=wn(u=xn(u,o),o,a),ne(s,u),o=Yt(i,o,t,s)),sn(u)||(t=u,(u=wn(u,o,a))!==t&&ne(s,u)),n?(c=it(s),bt(s,e,!0)):2!==r||a||ot?.delete(s)),c||s}function nn(e,t,n,r){return e=Kt(e,t,n,r),Array.isArray(e)?e:ie}function rn(e,t){return 0===e&&(e=xn(e,t)),1|e}function sn(e){return!!(2&e)&&!!(4&e)||!!(2048&e)}function an(e){e=G(e);for(let t=0;t<e.length;t++){const n=e[t]=G(e[t]);Array.isArray(n[1])&&(n[1]=re(n[1]))}return e}function on(e,t,n,r){e=e.u;let s=te(e);fe(s),Yt(e,s,t,("0"===r?0===Number(n):n===r)?void 0:n)}function un(e,t){var n=$a;return hn(ln(e=e.u),e,te(e),n)===t?t:-1}function ln(e){if(H)return e[Y]??(e[Y]=new Map);if(Y in e)return e[Y];const t=new Map;return Object.defineProperty(e,Y,{value:t}),t}function cn(e,t,n,r){const s=ln(e),a=hn(s,e,t,n);return a!==r&&(a&&(t=Yt(e,t,a)),s.set(n,r)),t}function hn(e,t,n,r){let s=e.get(r);if(null!=s)return s;s=0;for(let e=0;e<r.length;e++){const a=r[e];null!=Kt(t,n,a)&&(0!==s&&(n=Yt(t,n,s)),s=a)}return e.set(r,s),s}function dn(e,t,n,r){let s,a=te(e);if(null!=(r=Kt(e,a,n,r))&&r.X===oe)return(t=Gt(r))!==r&&Yt(e,a,n,t),t.u;if(Array.isArray(r)){const e=ee(r);s=2&e?It(Wt(r,e,!1),t,!0):64&e?r:It(s,t,!0)}else s=It(void 0,t,!0);return s!==r&&Yt(e,a,n,s),s}function pn(e,t,n,r){e=e.u;let s=te(e);return(t=st(r=Kt(e,s,n,r),t,!1,s))!==r&&null!=t&&Yt(e,s,n,t),t}function fn(e,t,n,r=!1){if(null==(t=pn(e,t,n,r)))return t;if(e=e.u,!(2&(r=te(e)))){const s=Gt(t);s!==t&&Yt(e,r,n,t=s)}return t}function mn(e,t,n,r,s,a,i){const o=e.u;var u=!!(2&t);s=u?1:s,a=!!a,i&&=!u,u=nn(o,t,r);var l=ee(u),c=u;if(xt(c,e),2!==s&&1!==s||kt(c,e),!(c=!!(4&l))){var h=u,d=t;const e=!!(2&(l=rn(l,t)));e&&(d|=2);let r=!e,s=!0,a=0,i=0;for(;a<h.length;a++){const t=st(h[a],n,!1,d);if(t instanceof n){if(!e){const e=!!(2&ee(t.u));r&&=!e,s&&=e}h[i++]=t}}i<a&&(h.length=i),l|=4,l=s?16|l:-17&l,ne(h,l=r?8|l:-9&l),e&&Object.freeze(h)}if(i&&!(8&l||!u.length&&(1===s||4===s&&32&l))){for(sn(l)?(u=G(u),l=xn(l,t),t=Yt(o,t,r,u)):kt(u,e),n=u,i=l,h=0;h<n.length;h++)(l=n[h])!==(d=Gt(l))&&(n[h]=d);i|=8,i=n.length?-17&i:16|i,ne(n,i),l=i}let p;return 1===s||4===s&&32&l?sn(l)||(e=l,(l|=!u.length||16&l&&(!c||32&l)?2:2048)!==e&&ne(u,l),Object.freeze(u)):(c=5===s&&(!!(32&l)||sn(l)||!!ot?.get(u)),(2===s||c)&&sn(l)&&(u=G(u),l=wn(l=xn(l,t),t,a),ne(u,l),t=Yt(o,t,r,u)),sn(l)||(r=l,(l=wn(l,t,a))!==r&&ne(u,l)),c?(p=it(u),bt(u,e,!0)):2!==s||a||ot?.delete(u)),p||u}function gn(e,t,n){const r=te(e.u);return mn(e,r,t,n,en(),!1,!(2&r))}function yn(e,t,n,r){return null==r&&(r=void 0),Xt(e,n,r)}function bn(e,t,n,r){null==r&&(r=void 0);e:{e=e.u;let s=te(e);if(fe(s),null==r){const r=ln(e);if(hn(r,e,s,n)!==t)break e;r.set(n,0)}else s=cn(e,s,n,t);Yt(e,s,t,r)}}function xn(e,t){return-2049&(2&t?2|e:-3&e)|32}function wn(e,t,n){return 32&t&&n||(e&=-33),e}function vn(e,t,n,r){const s=te(e.u);fe(s),e=mn(e,s,n,t,2,!0),r=null!=r?r:new n,e.push(r),2&ee(r.u)?Q(e,8):Q(e,16)}function kn(e,t){return e??t}function In(e,t){return Xe(jt(e,t))}function Sn(e,t){return kn(Zt(e,t),0)}function Nn(e,t){return kn(rt(jt(e,t)),"")}
5057function Tn(e,t,n){if(null!=n&&"boolean"!=typeof n)throw e=typeof n,Error(`Expected boolean but got ${"object"!=e?e:n?Array.isArray(n)?"array":e:"null"}: ${n}`);Xt(e,t,n)}function En(e,t,n){if(null!=n){if("number"!=typeof n)throw U("int32");if(!Number.isFinite(n))throw U("int32");n|=0}Xt(e,t,n)}function Cn(e,t,n){if(null!=n&&"number"!=typeof n)throw Error(`Value of float/double field must be a number, found ${typeof n}: ${n}`);Xt(e,t,n)}function $n(e,t,n){{const o=e.u;let u=te(o);if(fe(u),null==n)Yt(o,u,t);else{n=ut?.get(n)||n;var r,s=ee(n),a=s,i=!!(2&s)||Object.isFrozen(n);if((r=!i)&&((r=void 0===we)||(r=!!f&&void 0!==xe)),Ht(e,s)){s=21,i&&(n=G(n),a=0,s=wn(s=xn(s,u),u,!0));for(let e=0;e<n.length;e++)n[e]=tt(n[e])}r?(n=G(n),a=0,s=wn(s=xn(s,u),u,!0)):i||bt(n,e),s!==a&&ne(n,s),Yt(o,u,t,n)}}}function An(e,t,n){fe(te(e.u)),tn(e,t,rt,2,void 0,!0).push(tt(n))}function Rn(e,t){return Error(`Invalid wire type: ${e} (at position ${t})`)}function _n(){return Error("Failed to read varint, encoding is invalid.")}function Mn(e,t){return Error(`Tried to read past the end of the data ${t} > ${e}`)}function Fn(e){if("string"==typeof e)return{buffer:R(e),O:!1};if(Array.isArray(e))return{buffer:new Uint8Array(e),O:!1};if(e.constructor===Uint8Array)return{buffer:e,O:!1};if(e.constructor===ArrayBuffer)return{buffer:new Uint8Array(e),O:!1};if(e.constructor===z)return{buffer:L(e)||new Uint8Array(0),O:!0};if(e instanceof Uint8Array)return{buffer:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),O:!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 Dn(e,t){let n,r=0,s=0,a=0;const i=e.h;let o=e.g;do{n=i[o++],r|=(127&n)<<a,a+=7}while(a<32&&128&n);for(a>32&&(s|=(127&n)>>4),a=3;a<32&&128&n;a+=7)n=i[o++],s|=(127&n)<<a;if(Wn(e,o),n<128)return t(r>>>0,s>>>0);throw _n()}function On(e){let t=0,n=e.g;const r=n+10,s=e.h;for(;n<r;){const r=s[n++];if(t|=r,!(128&r))return Wn(e,n),!!(127&t)}throw _n()}function Ln(e){const t=e.h;let n=e.g,r=t[n++],s=127&r;if(128&r&&(r=t[n++],s|=(127&r)<<7,128&r&&(r=t[n++],s|=(127&r)<<14,128&r&&(r=t[n++],s|=(127&r)<<21,128&r&&(r=t[n++],s|=r<<28,128&r&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++])))))throw _n();return Wn(e,n),s}function zn(e){return Ln(e)>>>0}function Pn(e){var t=e.h;const n=e.g,r=t[n],s=t[n+1],a=t[n+2];return t=t[n+3],Wn(e,e.g+4),(r|s<<8|a<<16|t<<24)>>>0}function Bn(e){var t=Pn(e);e=2*(t>>31)+1;const n=t>>>23&255;return t&=8388607,255==n?t?NaN:e*(1/0):0==n?1401298464324817e-60*e*t:e*Math.pow(2,n-150)*(t+8388608)}function Vn(e){return Ln(e)}function Un(e,t,{ca:n=!1}={}){e.ca=n,t&&(t=Fn(t),e.h=t.buffer,e.m=t.O,e.j=0,e.l=e.h.length,e.g=e.j)}function Wn(e,t){if(e.g=t,t>e.l)throw Mn(e.l,t)}function Gn(e,t){if(t<0)throw Error(`Tried to read a negative byte length: ${t}`);const n=e.g,r=n+t;if(r>e.l)throw Mn(t,e.l-n);return e.g=r,n}function Hn(e,t){if(0==t)return O();var n=Gn(e,t);return e.ca&&e.m?n=e.h.subarray(n,n+t):(e=e.h,n=n===(t=n+t)?new Uint8Array(0):_e?e.slice(n,t):new Uint8Array(e.subarray(n,t))),0==n.length?O():new z(n,M)}Rt.prototype.toJSON=void 0,Rt.prototype.Ja=ue;var jn=[];function qn(e){var t=e.g;if(t.g==t.l)return!1;e.l=e.g.g;var n=zn(e.g);if(t=n>>>3,!((n&=7)>=0&&n<=5))throw Rn(n,e.l);if(t<1)throw Error(`Invalid field number: ${t} (at position ${e.l})`);return e.m=t,e.h=n,!0}function Kn(e){switch(e.h){case 0:0!=e.h?Kn(e):On(e.g);break;case 1:Wn(e=e.g,e.g+8);break;case 2:if(2!=e.h)Kn(e);else{var t=zn(e.g);Wn(e=e.g,e.g+t)}break;case 5:Wn(e=e.g,e.g+4);break;case 3:for(t=e.m;;){if(!qn(e))throw Error("Unmatched start-group tag: stream EOF");if(4==e.h){if(e.m!=t)throw Error("Unmatched end-group tag");break}Kn(e)}break;default:throw Rn(e.h,e.l)}}function Xn(e,t,n){const r=e.g.l,s=zn(e.g),a=e.g.g+s;let i=a-r;if(i<=0&&(e.g.l=a,n(t,e,void 0,void 0,void 0),i=a-e.g.g),i)throw Error(`Message parsing ended unexpectedly. Expected to read ${s} bytes, instead read ${s-i} bytes, either the data ended unexpectedly or the message misreported its own length`);return e.g.g=a,e.g.l=r,t}function Yn(e){var t=zn(e.g),n=Gn(e=e.g,t);if(e=e.h,u){var r,l=e;
5057(r=o)||(r=o=new TextDecoder("utf-8",{fatal:!0})),t=n+t,l=0===n&&t===l.length?l:l.subarray(n,t);try{var c=r.decode(l)}catch(e){if(void 0===i){try{r.decode(new Uint8Array([128]))}catch(e){}try{r.decode(new Uint8Array([97])),i=!0}catch(e){i=!1}}throw!i&&(o=void 0),e}}else{t=(c=n)+t,n=[];let i,o=null;for(;c<t;){var h=e[c++];h<128?n.push(h):h<224?c>=t?s():(i=e[c++],h<194||128!=(192&i)?(c--,s()):n.push((31&h)<<6|63&i)):h<240?c>=t-1?s():(i=e[c++],128!=(192&i)||224===h&&i<160||237===h&&i>=160||128!=(192&(r=e[c++]))?(c--,s()):n.push((15&h)<<12|(63&i)<<6|63&r)):h<=244?c>=t-2?s():(i=e[c++],128!=(192&i)||i-144+(h<<28)>>30||128!=(192&(r=e[c++]))||128!=(192&(l=e[c++]))?(c--,s()):(h=(7&h)<<18|(63&i)<<12|(63&r)<<6|63&l,h-=65536,n.push(55296+(h>>10&1023),56320+(1023&h)))):s(),n.length>=8192&&(o=a(o,n),n.length=0)}c=a(o,n)}return c}function Jn(e){const t=zn(e.g);return Hn(e.g,t)}function Zn(e,t,n){var r=zn(e.g);for(r=e.g.g+r;e.g.g<r;)n.push(t(e.g))}var Qn=[];let er;function tr(e,t,n){t.g?t.m(e,t.g,t.h,n,!0):t.m(e,t.h,n,!0)}var nr=class{constructor(e,t){this.u=St(e,t)}toJSON(){return rr(this)}l(){var e=Si;return e.g?e.l(this,e.g,e.h,!0):e.l(this,e.h,e.defaultValue,!0)}clone(){const e=this.u;return Ut(this,e,te(e),!1)}O(){return!!(2&ee(this.u))}};function rr(e){vt(e),e=er?e.u:zt(e.u,Bt,void 0,void 0,!1);{var t=!er;let l=e.length;if(l){var n=e[l-1],r=ce(n);r?l--:n=void 0;var s=e;if(r){e:{var a,i=n,o=!1;if(i)for(let e in i)isNaN(+e)?(a??={})[e]=i[e]:(r=i[e],Array.isArray(r)&&(de(r)||le(r)&&0===r.size)&&(r=null),null==r&&(o=!0),null!=r&&((a??={})[e]=r));if(o||(a=i),a)for(let e in a){o=a;break e}o=null}i=null==o?null!=n:o!==n}for(;l>0&&(null==(a=s[l-1])||de(a)||le(a)&&0===a.size);l--)var u=!0;(s!==e||i||u)&&(t?(u||i||o)&&(s.length=l):s=Array.prototype.slice.call(s,0,l),o&&s.push(o)),u=s}else u=e}return u}function sr(e){return e?/^\\d+$/.test(e)?(We(e),new ar(Fe,De)):null:ir||=new ar(0,0)}nr.prototype.X=oe,nr.prototype.toString=function(){try{return er=!0,rr(this).toString()}finally{er=!1}};var ar=class{constructor(e,t){this.h=e>>>0,this.g=t>>>0}};let ir;function or(e){return e?/^-?\\d+$/.test(e)?(We(e),new ur(Fe,De)):null:lr||=new ur(0,0)}var ur=class{constructor(e,t){this.h=e>>>0,this.g=t>>>0}};let lr;function cr(e,t,n){for(;n>0||t>127;)e.g.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;e.g.push(t)}function hr(e,t){for(;t>127;)e.g.push(127&t|128),t>>>=7;e.g.push(t)}function dr(e,t){if(t>=0)hr(e,t);else{for(let n=0;n<9;n++)e.g.push(127&t|128),t>>=7;e.g.push(1)}}function pr(e,t){e.g.push(t>>>0&255),e.g.push(t>>>8&255),e.g.push(t>>>16&255),e.g.push(t>>>24&255)}function fr(e,t){0!==t.length&&(e.l.push(t),e.h+=t.length)}function mr(e,t,n){hr(e.g,8*t+n)}function gr(e,t){return mr(e,t,2),t=e.g.end(),fr(e,t),t.push(e.h),t}function yr(e,t){var n=t.pop();for(n=e.h+e.g.length()-n;n>127;)t.push(127&n|128),n>>>=7,e.h++;t.push(n),e.h++}function br(e,t,n){mr(e,t,2),hr(e.g,n.length),fr(e,e.g.end()),fr(e,n)}function xr(e,t,n,r){null!=n&&(t=gr(e,t),r(n,e),yr(e,t))}function wr(){const e=class{constructor(){throw Error()}};return Object.setPrototypeOf(e,e.prototype),e}var vr=wr(),kr=wr(),Ir=wr(),Sr=wr(),Nr=wr(),Tr=wr(),Er=wr(),Cr=wr(),$r=class{constructor(e,t,n){this.g=e,this.h=t,e=vr,this.l=!!e&&n===e||!1}};function Ar(e,t){return new $r(e,t,vr)}function Rr(e,t,n,r,s){xr(e,n,Ur(t,r),s)}const _r=Ar(function(e,t,n,r,s){return 2===e.h&&(Xn(e,dn(t,r,n),s),!0)},Rr),Mr=Ar(function(e,t,n,r,s){return 2===e.h&&(Xn(e,dn(t,r,n,!0),s),!0)},Rr);var Fr=Symbol(),Dr=Symbol(),Or=Symbol(),Lr=Symbol();let zr,Pr;function Br(e,t,n,r){var s=r[e];if(s)return s;(s={}).W=function(e){switch(typeof e){case"boolean":return ft||=[0,void 0,!0];case"number":return e>0?void 0:0===e?mt||=[0,void 0]:[-e,void 0];case"string":return[0,e];case"object":return e}}(r[0]);var a=r[1];let i=1;a&&a.constructor===Object&&(s.ia=a,"function"==typeof(a=r[++i])&&(s.na=!0,zr??=a,Pr??=r[i+1],a=r[i+=2]));const o={};for(;a&&Array.isArray(a)&&a.length&&"number"==typeof a[0]&&a[0]>0;){for(var u=0;u<a.length;u++)o[a[u]]=a;a=r[++i]}for(u=1;void 0!==a;){let e;"number"==typeof a&&(u+=a,a=r[++i]);var l=void 0;if(a instanceof $r?e=a:(e=_r,i--),e?.l){a=r[++i],l=r;var c=i;"function"==typeof a&&(a=a(),l[c]=a),l=a}for(c=u+1,"number"==typeof(a=r[++i])&&a<0&&(c-=a,a=r[++i]);u<c;u++){const r=o[u];l?n(s,u,e,l,r):t(s,u,e,r)}}return r[e]=s}function Vr(e){return Array.isArray(e)?e[0]instanceof $r?e:[Mr,e]:[e,void 0]}function Ur(e,t){return e instanceof nr?(vt(e),e.u):Array.isArray(e)?It(e,t,!1):void 0}function Wr(e,t,n,r){const s=n.g;e[t]=r?(e,t,n)=>s(e,t,n,r):s}
5057function Gr(e,t,n,r,s){const a=n.g;let i,o;e[t]=(e,t,n)=>a(e,t,n,o||=Br(Dr,Wr,Gr,r).W,i||=Hr(r),s)}function Hr(e){let t=e[Or];if(null!=t)return t;const n=Br(Dr,Wr,Gr,e);return t=n.na?(e,t)=>zr(e,t,n):(e,t)=>{const r=te(e);for(;qn(t)&&4!=t.h;){var s=t.m,a=n[s];if(null==a){var i=n.ia;i&&(i=i[s])&&null!=(i=jr(i))&&(a=n[s]=i)}null!=a&&a(t,e,s)||(s=(a=t).l,Kn(a),a.ha?a=void 0:(i=a.g.g-s,a.g.g=s,a=Hn(a.g,i)),s=e,a&&(ge||=Symbol(),(i=s[ge])?i.push(a):s[ge]=[a]))}return 16384&r&&re(e),!0},e[Or]=t}function jr(e){const t=(e=Vr(e))[0].g;if(e=e[1]){const n=Hr(e),r=Br(Dr,Wr,Gr,e).W;return(e,s,a)=>t(e,s,a,r,n)}return t}function qr(e,t,n){e[t]=n.h}function Kr(e,t,n,r){let s,a;const i=n.h;e[t]=(e,t,n)=>i(e,t,n,a||=Br(Fr,qr,Kr,r).W,s||=Xr(r))}function Xr(e){let t=e[Lr];if(!t){const n=Br(Fr,qr,Kr,e);t=(e,t)=>Yr(e,t,n),e[Lr]=t}return t}function Yr(e,t,n){for(var r=ee(e),s=+!!(512&r)-1,a=e.length,i=512&r?1:0,o=a+(256&r?-1:0);i<o;i++){const r=e[i];if(null==r)continue;const a=i-s,o=Jr(n,a);o&&o(t,r,a)}if(256&r){r=e[a-1];for(const e in r)s=+e,Number.isNaN(s)||null!=(a=r[s])&&(o=Jr(n,s))&&o(t,a,s)}if(e=ge?e[ge]:void 0)for(fr(t,t.g.end()),n=0;n<e.length;n++)fr(t,L(e[n])||new Uint8Array(0))}function Jr(e,t){var n=e[t];if(n)return n;if((n=e.ia)&&(n=n[t])){var r=(n=Vr(n))[0].h;if(n=n[1]){const t=Xr(n),s=Br(Fr,qr,Kr,n).W;n=e.na?Pr(s,t):(e,n,a)=>r(e,n,a,s,t)}else n=r;return e[t]=n}}function Zr(e,t){if(Array.isArray(t)){var n=ee(t);if(4&n)return t;for(var r=0,s=0;r<t.length;r++){const n=e(t[r]);null!=n&&(t[s++]=n)}return s<r&&(t.length=s),ne(t,-12289&n|5),2&n&&Object.freeze(t),t}}function Qr(e,t,n){return new $r(e,t,n)}
5057function es(e,t,n){return new $r(e,t,n)}function ts(e,t,n){Yt(e,te(e),t,n)}var ns=Ar(function(e,t,n,r,s){return 2===e.h&&(e=Xn(e,It([void 0,void 0],r,!0),s),fe(r=te(t)),(s=Kt(t,r,n))instanceof Rt?2&s.M?((s=s.Y()).push(e),Yt(t,r,n,s)):s.Oa(e):Array.isArray(s)?(2&ee(s)&&Yt(t,r,n,s=an(s)),s.push(e)):Yt(t,r,n,[e]),!0)},function(e,t,n,r,s){if(t instanceof Rt)t.forEach((t,a)=>{xr(e,n,It([a,t],r,!1),s)});else if(Array.isArray(t))for(let a=0;a<t.length;a++){const i=t[a];Array.isArray(i)&&xr(e,n,It(i,r,!1),s)}});function rs(e,t,n){if(t=function(e){if(null==e)return e;const t=typeof e;if("bigint"===t)return String(BigInt.asIntN(64,e));if(Ke(e)){if("string"===t)return Qe(e);if("number"===t)return Ze(e)}}(t),null!=t&&("string"==typeof t&&or(t),null!=t))switch(mr(e,n,0),typeof t){case"number":e=e.g,Le(t),cr(e,Fe,De);break;case"bigint":n=BigInt.asUintN(64,t),n=new ur(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),cr(e.g,n.h,n.g);break;default:n=or(t),cr(e.g,n.h,n.g)}}function ss(e,t,n){null!=(t=Xe(t))&&null!=t&&(mr(e,n,0),dr(e.g,t))}function as(e,t,n){null!=(t=je(t))&&(mr(e,n,0),e.g.g.push(t?1:0))}function is(e,t,n){null!=(t=rt(t))&&br(e,n,h(t))}function os(e,t,n,r,s){xr(e,n,Ur(t,r),s)}function us(e,t,n){null!=(t=null==t||"string"==typeof t||_(t)||t instanceof z?t:void 0)&&br(e,n,Fn(t).buffer)}function ls(e,t,n){return(5===e.h||2===e.h)&&(t=Jt(t,te(t),n,2,!1),2==e.h?Zn(e,Bn,t):t.push(Bn(e.g)),!0)}var cs=Qr(function(e,t,n){if(1!==e.h)return!1;var r=e.g;e=Pn(r);const s=Pn(r);r=2*(s>>31)+1;const a=s>>>20&2047;return e=4294967296*(1048575&s)+e,ts(t,n,2047==a?e?NaN:r*(1/0):0==a?5e-324*r*e:r*Math.pow(2,a-1075)*(e+4503599627370496)),!0},function(e,t,n){null!=(t=He(t))&&(mr(e,n,1),e=e.g,(n=Me||=new DataView(new ArrayBuffer(8))).setFloat64(0,+t,!0),Fe=n.getUint32(0,!0),De=n.getUint32(4,!0),pr(e,Fe),pr(e,De))},wr()),hs=Qr(function(e,t,n){return 5===e.h&&(ts(t,n,Bn(e.g)),!0)},function(e,t,n){null!=(t=He(t))&&(mr(e,n,5),e=e.g,ze(t),pr(e,Fe))},Tr),ds=es(ls,function(e,t,n){if(null!=(t=Zr(He,t)))for(let i=0;i<t.length;i++){var r=e,s=n,a=t[i];null!=a&&(mr(r,s,5),r=r.g,ze(a),pr(r,Fe))}},Tr),ps=es(ls,function(e,t,n){if(null!=(t=Zr(He,t))&&t.length){mr(e,n,2),hr(e.g,4*t.length);for(let r=0;r<t.length;r++)n=e.g,ze(t[r]),pr(n,Fe)}},Tr),fs=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,Dn(e.g,Be)),!0)},rs,Nr),ms=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,0===(e=Dn(e.g,Be))?void 0:e),!0)},rs,Nr),gs=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,Dn(e.g,Pe)),!0)},function(e,t,n){if(null!=(t=function(e){if(null==e)return e;var t=typeof e;if("bigint"===t)return String(BigInt.asUintN(64,e));if(Ke(e)){if("string"===t)return t=Math.trunc(Number(e)),Number.isSafeInteger(t)&&t>=0?e=String(t):(-1!==(t=e.indexOf("."))&&(e=e.substring(0,t)),Je(e)||(We(e),e=Ve(Fe,De))),e;if("number"===t)return(e=Math.trunc(e))>=0&&Number.isSafeInteger(e)?e:function(e){if(e<0){Le(e);const t=Ve(Fe,De);return e=Number(t),Number.isSafeInteger(e)?e:t}return Je(String(e))?e:(Le(e),Pe(Fe,De))}(e)}}(t))&&("string"==typeof t&&sr(t),null!=t))switch(mr(e,n,0),typeof t){case"number":e=e.g,Le(t),cr(e,Fe,De);break;case"bigint":n=BigInt.asUintN(64,t),n=new ar(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),cr(e.g,n.h,n.g);break;default:n=sr(t),cr(e.g,n.h,n.g)}},wr()),ys=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,Ln(e.g)),!0)},ss,Sr),bs=es(function(e,t,n){return(0===e.h||2===e.h)&&(t=Jt(t,te(t),n,2,!1),2==e.h?Zn(e,Ln,t):t.push(Ln(e.g)),!0)},function(e,t,n){if(null!=(t=Zr(Xe,t))&&t.length){n=gr(e,n);for(let n=0;n<t.length;n++)dr(e.g,t[n]);yr(e,n)}},Sr),xs=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,0===(e=Ln(e.g))?void 0:e),!0)},ss,Sr),ws=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,On(e.g)),!0)},as,kr),vs=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,!1===(e=On(e.g))?void 0:e),!0)},as,kr),ks=es(function(e,t,n){if(2!==e.h)return!1;e=Yn(e);const r=te(t);return fe(r),Jt(t,r,n,2).push(e),!0},function(e,t,n){if(null!=(t=Zr(rt,t)))for(let i=0;i<t.length;i++){var r=e,s=n,a=t[i];null!=a&&br(r,s,h(a))}},Ir),Is=Qr(function(e,t,n){return 2===e.h&&(ts(t,n,""===(e=Yn(e))?void 0:e),!0)},is,Ir),Ss=Qr(function(e,t,n){return 2===e.h&&(ts(t,n,Yn(e)),!0)},is,Ir),Ns=function(e,t,n=vr){return new $r(e,t,n)}
5057(function(e,t,n,r,s){if(2!==e.h)return!1;r=It(void 0,r,!0);let a=te(t);fe(a);let i=Jt(t,a,n,3);return a=te(t),4&ee(i)&&(i=G(i),ne(i,-2079&ee(i)|1),Yt(t,a,n,i)),i.push(r),Xn(e,r,s),!0},function(e,t,n,r,s){if(Array.isArray(t))for(let a=0;a<t.length;a++)os(e,t[a],n,r,s)}),Ts=Ar(function(e,t,n,r,s,a){return 2===e.h&&(cn(t,ee(t),a,n),Xn(e,t=dn(t,r,n),s),!0)},os),Es=Qr(function(e,t,n){return 2===e.h&&(ts(t,n,Jn(e)),!0)},us,Er),Cs=es(function(e,t,n){return(0===e.h||2===e.h)&&(t=Jt(t,te(t),n,2,!1),2==e.h?Zn(e,zn,t):t.push(zn(e.g)),!0)},function(e,t,n){if(null!=(t=Zr(Ye,t)))for(let i=0;i<t.length;i++){var r=e,s=n,a=t[i];null!=a&&(mr(r,s,0),hr(r.g,a))}},wr()),$s=Qr(function(e,t,n){return 0===e.h&&(ts(t,n,Ln(e.g)),!0)},function(e,t,n){null!=(t=Xe(t))&&(t=parseInt(t,10),mr(e,n,0),dr(e.g,t))},Cr);class As{constructor(e,t){this.h=e,this.g=t,this.l=fn,this.m=yn,this.defaultValue=void 0}}function Rs(e,t){return new As(e,t)}function _s(e,t){return(n,r)=>{if(Qn.length){const e=Qn.pop();e.o(r),Un(e.g,n,r),n=e}else n=new class{constructor(e,t){if(jn.length){const n=jn.pop();Un(n,e,t),e=n}else e=new class{constructor(e,t){this.h=null,this.m=!1,this.g=this.l=this.j=0,Un(this,e,t)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ca=!1}}(e,t);this.g=e,this.l=this.g.g,this.h=this.m=-1,this.o(t)}o({ha:e=!1}={}){this.ha=e}}(n,r);try{const r=new e,a=r.u;Hr(t)(a,n);var s=r}finally{n.g.clear(),n.m=-1,n.h=-1,Qn.length<100&&Qn.push(n)}return s}}function Ms(e){return function(){vt(this);const t=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const e=this.g;return this.g=[],e}}}};Yr(this.u,t,Br(Fr,qr,Kr,e)),fr(t,t.g.end());const n=new Uint8Array(t.h),r=t.l,s=r.length;let a=0;for(let e=0;e<s;e++){const t=r[e];n.set(t,a),a+=t.length}return t.l=[n],n}}var Fs=class extends nr{constructor(e){super(e)}},Ds=[0,Is,Qr(function(e,t,n){return 2===e.h&&(ts(t,n,(e=Jn(e))===O()?void 0:e),!0)},function(e,t,n){if(null!=t){if(t instanceof nr){const r=t.Ra;return void(r&&(t=r(t),null!=t&&br(e,n,Fn(t).buffer)))}if(Array.isArray(t))return}us(e,t,n)},Er)];let Os,Ls=globalThis.trustedTypes;function zs(e){void 0===Os&&(Os=function(){let e=null;if(!Ls)return e;try{const t=e=>e;e=Ls.createPolicy("goog#html",{createHTML:t,createScript:t,createScriptURL:t})}catch(e){}return e}());var t=Os;return new class{constructor(e){this.g=e}toString(){return this.g+""}}(t?t.createScriptURL(e):e)}function Ps(e,...t){if(0===t.length)return zs(e[0]);let n=e[0];for(let r=0;r<t.length;r++)n+=encodeURIComponent(t[r])+e[r+1];return zs(n)}var Bs=[0,ys,$s,ws,-1,bs,$s,-1],Vs=class extends nr{constructor(){super()}},Us=[0,ws,Ss,ws,$s,-1,es(function(e,t,n){return(0===e.h||2===e.h)&&(t=Jt(t,te(t),n,2,!1),2==e.h?Zn(e,Vn,t):t.push(Ln(e.g)),!0)},function(e,t,n){if(null!=(t=Zr(Xe,t))&&t.length){n=gr(e,n);for(let n=0;n<t.length;n++)dr(e.g,t[n]);yr(e,n)}},Cr),Ss,-1,[0,ws,-1],$s,ws,-1],Ws=[0,Ss,-2],Gs=class extends nr{constructor(){super()}},Hs=[0],js=[0,ys,ws,1,ws,-3],qs=class extends nr{constructor(e){super(e,2)}},Ks={};Ks[336783863]=[0,Ss,ws,-1,ys,[0,[1,2,3,4,5,6,7],Ts,Hs,Ts,Us,Ts,Ws,Ts,js,Ts,Bs,Ts,[0,Ss,-2],Ts,[0,Ss,$s]],[0,Ss],ws,[0,[1,3],[2,4],Ts,[0,bs],-1,Ts,[0,ks],-1,Ns,[0,Ss,-1]],Ss];var Xs=[0,ms,-1,vs,-3,ms,bs,Is,xs,ms,-1,vs,xs,vs,-2,Is];function Ys(e,t){on(e,2,nt(t),"")}function Js(e,t){An(e,3,t)}function Zs(e,t){An(e,4,t)}var Qs=class extends nr{constructor(e){super(e,500)}o(e){return yn(this,0,7,e)}},ea=[-1,{}],ta=[0,Ss,1,ea],na=[0,Ss,ks,ea];function ra(e,t){vn(e,1,Qs,t)}function sa(e,t){An(e,10,t)}function aa(e,t){An(e,15,t)}var ia=class extends nr{constructor(e){super(e,500)}o(e){return yn(this,0,1001,e)}},oa=[-500,Ns,[-500,Is,-1,ks,-3,[-2,Ks,ws],Ns,Ds,xs,-1,ta,na,Ns,[0,Is,vs],Is,Xs,xs,ks,987,ks],4,Ns,[-500,Ss,-1,[-1,{}],998,Ss],Ns,[-500,Ss,ks,-1,[-2,{},ws],997,ks,-1],xs,Ns,[-500,Ss,ks,ea,998,ks],ks,xs,ta,na,Ns,[0,Is,-1,ea],ks,-2,Xs,Is,-1,vs,979,ea,Ns,Ds];ia.prototype.g=Ms(oa);var ua=_s(ia,oa),la=class extends nr{constructor(e){super(e)}},ca=class extends nr{constructor(e){super(e)}g(){return gn(this,la,1)}},ha=[0,Ns,[0,ys,hs,Ss,-1]],da=_s(ca,ha),pa=class extends nr{constructor(e){super(e)}},fa=class extends nr{constructor(e){super(e)}},ma=class extends nr{constructor(e){super(e)}h(){return fn(this,pa,2)}g(){return gn(this,fa,5)}},ga=_s(class extends nr{constructor(e){super(e)}},[0,ks,bs,ps,[0,$s,[0,ys,-3],[0,hs,-3],[0,ys,-1,[0,Ns,[0,ys,-2]]],Ns,[0,hs,-1,Ss,hs]],Ss,-1,fs,Ns,[0,ys,hs],ks,fs]),ya=class extends nr{constructor(e){super(e)}},ba=_s(class extends nr{constructor(e){super(e)}},[0,Ns,[0,hs,-4]]),xa=class extends nr{constructor(e){super(e)}},wa=_s(class extends nr{constructor(e){super(e)}},[0,Ns,[0,hs,-4]]),va=class extends nr{constructor(e){super(e)}},ka=[0,ys,-1,ps,$s],Ia=class extends nr{constructor(){super()}};Ia.prototype.g=Ms([0,hs,-4,fs]);var Sa=class extends nr{constructor(e){super(e)}},Na=_s(class extends nr{constructor(e){super(e)}},[0,Ns,[0,1,ys,Ss,ha],fs]),Ta=class extends nr{constructor(e){super(e)}},Ea=class extends nr{constructor(e){super(e)}qa(){const e=Qt(this);return null==e?O():e}},Ca=class extends nr{constructor(e){super(e)}},$a=[1,2],Aa=_s(class extends nr{constructor(e){super(e)}},[0,Ns,[0,$a,Ts,[0,ps],Ts,[0,Es],ys,Ss],fs]),Ra=class extends nr{constructor(e){super(e)}},_a=[0,Ss,ys,hs,ks,-1],Ma=class extends nr{constructor(e){super(e)}},Fa=[0,ws,-1],Da=class extends nr{constructor(e){super(e)}},Oa=[1,2,3,4,5],La=class extends nr{constructor(e){super(e)}g(){return null!=Qt(this)}h(){return null!=rt(jt(this,2))}},za=class extends nr{constructor(e){super(e)}g(){return je(jt(this,2))??!1}}
5057,Pa=[0,Es,Ss,[0,ys,fs,-1],[0,gs,fs]],Ba=[0,Pa,ws,[0,Oa,Ts,js,Ts,Us,Ts,Bs,Ts,Hs,Ts,Ws],$s],Va=class extends nr{constructor(e){super(e)}},Ua=[0,Ba,hs,-1,ys],Wa=Rs(502141897,Va);Ks[502141897]=Ua;var Ga=_s(class extends nr{constructor(e){super(e)}},[0,[0,$s,-1,ds,Cs],ka]),Ha=class extends nr{constructor(e){super(e)}},ja=class extends nr{constructor(e){super(e)}},qa=[0,Ba,hs,[0,Ba],ws],Ka=[0,Ba,Ua,qa,hs,[0,[0,Pa]]],Xa=Rs(508968150,ja);Ks[508968150]=Ka,Ks[508968149]=qa;var Ya=class extends nr{constructor(e){super(e)}},Ja=Rs(513916220,Ya);Ks[513916220]=[0,Ba,Ka,ys];var Za=class extends nr{constructor(e){super(e)}h(){return fn(this,Ra,2)}g(){Xt(this,2)}},Qa=[0,Ba,_a];Ks[478825465]=Qa;var ei=class extends nr{constructor(e){super(e)}},ti=class extends nr{constructor(e){super(e)}},ni=class extends nr{constructor(e){super(e)}},ri=class extends nr{constructor(e){super(e)}},si=class extends nr{constructor(e){super(e)}},ai=[0,Ba,[0,Ba],Qa,-1],ii=[0,Ba,hs,ys],oi=[0,Ba,hs],ui=[0,Ba,ii,oi,hs],li=Rs(479097054,si);Ks[479097054]=[0,Ba,ui,ai],Ks[463370452]=ai,Ks[464864288]=ii;var ci=Rs(462713202,ri);Ks[462713202]=ui,Ks[474472470]=oi;var hi=class extends nr{constructor(e){super(e)}},di=class extends nr{constructor(e){super(e)}},pi=class extends nr{constructor(e){super(e)}},fi=class extends nr{constructor(){super()}},mi=[0,Ba,hs,-1,ys],gi=[0,Ba,hs,ws];fi.prototype.g=Ms([0,Ba,oi,[0,Ba],Ua,qa,mi,gi]);var yi=class extends nr{constructor(e){super(e)}},bi=Rs(456383383,yi);Ks[456383383]=[0,Ba,_a];var xi=class extends nr{constructor(e){super(e)}},wi=Rs(476348187,xi);Ks[476348187]=[0,Ba,Fa];var vi=class extends nr{constructor(e){super(e)}},ki=class extends nr{constructor(e){super(e)}},Ii=[0,$s,-1],Si=Rs(458105876,class extends nr{constructor(e){super(e)}g(){var e=this.u;const t=te(e),n=2&t;return e=function(e,t,n){var r=ki;const s=2&t;let a=!1;if(null==n){if(s)return Ot();n=[]}else if(n.constructor===Rt){if(!(2&n.M)||s)return n;n=n.Y()}else Array.isArray(n)?a=!!(2&ee(n)):n=[];if(s){if(!n.length)return Ot();a||(a=!0,re(n))}else a&&(a=!1,n=an(n));return a||(64&ee(n)?Q(n,32):32&t&&Z(n,32)),Yt(e,t,2,r=new Rt(n,r,at,void 0)),r}(e,t,Kt(e,t,2)),!n&&ki&&(e.ta=!0),e}});Ks[458105876]=[0,Ii,ns,[!0,fs,[0,Ss,-1,ks]]];var Ni=class extends nr{constructor(e){super(e)}},Ti=Rs(458105758,Ni);Ks[458105758]=[0,Ba,Ss,Ii];var Ei=class extends nr{constructor(e){super(e)}},Ci=Rs(443442058,Ei);Ks[443442058]=[0,Ba,Ss,ys,hs,ks,-1],Ks[514774813]=mi;var $i=class extends nr{constructor(e){super(e)}},Ai=Rs(516587230,$i);function Ri(e,t){return t=t?t.clone():new Ra,void 0!==e.displayNamesLocale?Xt(t,1,nt(e.displayNamesLocale)):void 0===e.displayNamesLocale&&Xt(t,1),void 0!==e.maxResults?En(t,2,e.maxResults):"maxResults"in e&&Xt(t,2),void 0!==e.scoreThreshold?Cn(t,3,e.scoreThreshold):"scoreThreshold"in e&&Xt(t,3),void 0!==e.categoryAllowlist?$n(t,4,e.categoryAllowlist):"categoryAllowlist"in e&&Xt(t,4),void 0!==e.categoryDenylist?$n(t,5,e.categoryDenylist):"categoryDenylist"in e&&Xt(t,5),t}function _i(e,t=-1,n=""){return{categories:e.map(e=>({index:kn(In(e,1),0)??-1,score:Sn(e,2)??0,categoryName:Nn(e,3)??"",dis
5057playName:Nn(e,4)??""})),headIndex:t,headName:n}}function Mi(e){var t=tn(e,3,He,en()),n=tn(e,2,Xe,en()),r=tn(e,1,rt,en()),s=tn(e,9,rt,en());const a={categories:[],keypoints:[]};for(let e=0;e<t.length;e++)a.categories.push({score:t[e],index:n[e]??-1,categoryName:r[e]??"",displayName:s[e]??""});if((t=fn(e,ma,4)?.h())&&(a.boundingBox={originX:In(t,1)??0,originY:In(t,2)??0,width:In(t,3)??0,height:In(t,4)??0,angle:0}),fn(e,ma,4)?.g().length)for(const t of fn(e,ma,4).g())a.keypoints.push({x:Zt(t,1)??0,y:Zt(t,2)??0,score:Zt(t,4)??0,label:rt(jt(t,3))??""});return a}function Fi(e){const t=[];for(const n of gn(e,xa,1))t.push({x:Sn(n,1)??0,y:Sn(n,2)??0,z:Sn(n,3)??0,visibility:Sn(n,4)??0});return t}function Di(e){const t=[];for(const n of gn(e,ya,1))t.push({x:Sn(n,1)??0,y:Sn(n,2)??0,z:Sn(n,3)??0,visibility:Sn(n,4)??0});return t}function Oi(e){return Array.from(e,e=>e>127?e-256:e)}function Li(e,t){if(e.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${e.length} vs. ${t.length}).`);let n=0,r=0,s=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],s+=t[a]*t[a];if(r<=0||s<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return n/Math.sqrt(r*s)}let zi;Ks[516587230]=[0,Ba,mi,gi,hs],Ks[518928384]=gi;const Pi=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function Bi(){if(void 0===zi)try{await WebAssembly.instantiate(Pi),zi=!0}catch{zi=!1}return zi}async function Vi(e,t=Ps``){const n=await Bi()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${t}/${e}_${n}.js`,wasmBinaryPath:`${t}/${e}_${n}.wasm`}}var Ui=class{};function Wi(){var e=navigator;return!("undefined"==typeof OffscreenCanvas||function(e=navigator){return(e=e.userAgent).includes("Safari")&&!e.includes("Chrome")}(e)&&!((e=e.userAgent.match(/Version\\/([\\d]+).*Safari/))&&e.length>=1&&Number(e[1])>=17))}async function Gi(e){if("function"!=typeof importScripts){const t=document.createElement("script");return t.src=e.toString(),t.crossOrigin="anonymous",new Promise((e,n)=>{t.addEventListener("load",()=>{e()},!1),t.addEventListener("error",e=>{n(e)},!1),document.body.appendChild(t)})}importScripts(e.toString())}function Hi(e){return void 0!==e.videoWidth?[e.videoWidth,e.videoHeight]:void 0!==e.naturalWidth?[e.naturalWidth,e.naturalHeight]:void 0!==e.displayWidth?[e.displayWidth,e.displayHeight]:[e.width,e.height]}function ji(e,t,n){e.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(t=e.i.stringToNewUTF8(t)),e.i._free(t)}function qi(e,t,n){if(!e.i.canvas)throw Error("No OpenGL canvas configured.");if(n?e.i._bindTextureToStream(n):e.i._bindTextureToCanvas(),!(n=e.i.canvas.getContext("webgl2")||e.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");e.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,s]=Hi(t);return!e.l||r===e.i.canvas.width&&s===e.i.canvas.height||(e.i.canvas.width=r,e.i.canvas.height=s),[r,s]}function Ki(e,t,n){e.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(t.length);for(let n=0;n<t.length;n++)r[n]=e.i.stringToNewUTF8(t[n]);t=e.i._malloc(4*r.length),e.i.HEAPU32.set(r,t>>2),n(t);for(const t of r)e.i._free(t);e.i._free(t)}function Xi(e,t,n){e.i.simpleListeners=e.i.simpleListeners||{},e.i.simpleListeners[t]=n}function Yi(e,t,n){let r=[];e.i.simpleListeners=e.i.simpleListeners||{},e.i.simpleListeners[t]=(e,t,s)=>{t?(n(r,s),r=[]):r.push(e)}}function Ji(e,t){const n=fn(e.baseOptions,La,1)||new La;"string"==typeof t?(Xt(n,2,nt(t)),Xt(n,1)):t instanceof Uint8Array&&(Xt(n,1,he(t,!1,!1)),Xt(n,2)),yn(e.baseOptions,0,1,n)}function Zi(e){try{const t=e.H.length;if(1===t)throw Error(e.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+e.H.map(e=>e.message).join(", "))}finally{e.H=[]}}function Qi(e,t){e.B=Math.max(e.B,t)}function eo(e,t){e.A=new Qs,Ys(e.A,"PassThroughCalculator"),Js(e.A,"free_memory"),Zs(e.A,"free_memory_unused_out"),sa(t,"free_memory"),ra(t,e.A)}function to(e,t){Js(e.A,t),Zs(e.A,t+"_unused_out")}function no(e){e.g.addBoolToStream(!0,"free_memory",e.B)}Ui.forVisionTasks=function(e){return Vi("vision",e)},Ui.forTextTasks=function(e){return Vi("text",e)},Ui.forGenAiExperimentalTasks=function(e){return Vi("genai_experimental",e)},Ui.forGenAiTasks=function(e){return Vi("genai",e)},Ui.forAudioTasks=function(e){return Vi("audio",e)},Ui.isSimdSupported=function(){return Bi()};var ro=class{constructor(e){this.g=e,this.H=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(e,t=!0){if(t){const t=e.baseOptions||{};if(e.baseOptions?.modelAssetBuffer&&e.baseOptions?.modelAssetPath)throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!(fn(this.baseOptions,La,1)?.g()||fn(this.baseOptions,La,1)?.h()||e.baseOptions?.modelAssetBuffer||e.baseOptions?.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(e,t){let n=fn(e.baseOptions,Da,3);if(!n){var r=n=new Da,s=new Gs;bn(r,4,Oa,s)}"delegate"in t&&("GPU"===t.delegate?(t=n,r=new Vs,bn(t,2,Oa,r)):(t=n,r=new Gs,bn(t,4,Oa,r))),yn(e.baseOptions,0,3,n)}(this,t),t.modelAssetPath)return fetch(t.modelAssetPath.toString()).then(e=>{if(e.ok)return e.arrayBuffer();throw Error(`Failed to fetch model: ${t.modelAssetPath} (${e.status})`)}).then(e=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(e),!0,!1,!1),Ji(this,"/model.dat"),this.m(),this.J()});if(t.modelAssetBuffer instanceof Uint8Array)Ji(this,t.modelAssetBuffer);else if(t.modelAssetBuffer)return async function(e){const t=[];for(var n=0;;){const{done:r,value:s}=await e.read();if(r)break;t.push(s),n+=s.length}if(0===t.length)return new Uint8Array(0);if(1===t.length)return t[0];e=new Uint8Array(n),n=0;for(const r of t)e.set(r,n),n+=r.length;return e}(t.modelAssetBuffer).then(e=>{Ji(this,e),this.m(),this.J()})}return this.m(),this.J(),Promise.resolve()}J(){}ea(){let e;if(this.g.ea(t=>{e=ua(t)}),!e)throw Error("Failed to retrieve CalculatorGraphConfig");return e}setGraph(e,t){this.g.attachErrorListener((e,t)=>
5057{this.H.push(Error(t))}),this.g.Ma(),this.g.setGraph(e,t),this.A=void 0,Zi(this)}finishProcessing(){this.g.finishProcessing(),Zi(this)}close(){this.A=void 0,this.g.closeGraph()}};function so(e,t){if(!e)throw Error(`Unable to obtain required WebGL resource: ${t}`);return e}ro.prototype.close=ro.prototype.close,function(e,t){e=e.split(".");var r,s=n;e[0]in s||void 0===s.execScript||s.execScript("var "+e[0]);for(;e.length&&(r=e.shift());)e.length||void 0===t?s=s[r]&&s[r]!==Object.prototype[r]?s[r]:s[r]={}:s[r]=t}("TaskRunner",ro);class ao{constructor(e,t,n,r){this.g=e,this.h=t,this.m=n,this.l=r}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function io(e,t,n){const r=e.g;if(n=so(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,t),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(e.h,n),n}function oo(e,t){const n=e.g,r=so(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const s=so(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,s),n.enableVertexAttribArray(e.P),n.vertexAttribPointer(e.P,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const a=so(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,a),n.enableVertexAttribArray(e.J),n.vertexAttribPointer(e.J,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new ao(n,r,s,a)}function uo(e,t){if(e.g){if(t!==e.g)throw Error("Cannot change GL context once initialized")}else e.g=t}function lo(e,t,n,r){return uo(e,t),e.h||(e.m(),e.C()),n?(e.s||(e.s=oo(e,!0)),n=e.s):(e.v||(e.v=oo(e,!1)),n=e.v),t.useProgram(e.h),n.bind(),e.l(),e=r(),n.g.bindVertexArray(null),e}function co(e,t,n){return uo(e,t),e=so(t.createTexture(),"Failed to create texture"),t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),e}function ho(e,t,n){uo(e,t),e.A||(e.A=so(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,e.A),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}function po(e){e.g?.bindFramebuffer(e.g.FRAMEBUFFER,null)}var fo=class{H(){return"\\n  precision mediump float;\\n  varying vec2 vTex;\\n  uniform sampler2D inputTexture;\\n  void main() {\\n    gl_FragColor = texture2D(inputTexture, vTex);\\n  }\\n "}m(){const e=this.g;if(this.h=so(e.createProgram(),"Failed to create WebGL program"),this.ba=io(this,"\\n  attribute vec2 aVertex;\\n  attribute vec2 aTex;\\n  varying vec2 vTex;\\n  void main(void) {\\n    gl_Position = vec4(aVertex, 0.0, 1.0);\\n    vTex = aTex;\\n  }",e.VERTEX_SHADER),this.aa=io(this,this.H(),e.FRAGMENT_SHADER),e.linkProgram(this.h),!e.getProgramParameter(this.h,e.LINK_STATUS))throw Error(`Error during program linking: ${e.getProgramInfoLog(this.h)}`);this.P=e.getAttribLocation(this.h,"aVertex"),this.J=e.getAttribLocation(this.h,"aTex")}C(){}l(){}close(){if(this.h){const e=this.g;e.deleteProgram(this.h),e.deleteShader(this.ba),e.deleteShader(this.aa)}this.A&&this.g.deleteFramebuffer(this.A),this.v&&this.v.close(),this.s&&this.s.close()}},mo=class extends fo{H(){return"\\n  precision mediump float;\\n  uniform sampler2D backgroundTexture;\\n  uniform sampler2D maskTexture;\\n  uniform sampler2D colorMappingTexture;\\n  varying vec2 vTex;\\n  void main() {\\n    vec4 backgroundColor = texture2D(backgroundTexture, vTex);\\n    float category = texture2D(maskTexture, vTex).r;\\n    vec4 categoryColor = texture2D(colorMappingTexture, vec2(category, 0.0));\\n    gl_FragColor = mix(backgroundColor, categoryColor, categoryColor.a);\\n  }\\n "}C(){const e=this.g;e.activeTexture(e.TEXTURE1),this.B=co(this,e,e.LINEAR),e.activeTexture(e.TEXTURE2),this.j=co(this,e,e.NEAREST)}m(){super.m();const e=this.g;this.L=so(e.getUniformLocation(this.h,"backgroundTexture"),"Uniform location"),this.U=so(e.getUniformLocation(this.h,"colorMappingTexture"),"Uniform location"),this.K=so(e.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const e=this.g;e.uniform1i(this.K,0),e.uniform1i(this.L,1),e.uniform1i(this.U,2)}close(){this.B&&this.g.deleteTexture(this.B),this.j&&this.g.deleteTexture(this.j),super.close()}},go=class extends fo{H(){return"\\n  precision mediump float;\\n  uniform sampler2D maskTexture;\\n  uniform sampler2D defaultTexture;\\n  uniform sampler2D overlayTexture;\\n  varying vec2 vTex;\\n  void main() {\\n    float confidence = texture2D(maskTexture, vTex).r;\\n    vec4 defaultColor = texture2D(defaultTexture, vTex);\\n    vec4 overlayColor = texture2D(overlayTexture, vTex);\\n    // Apply the alpha from the overlay and merge in the default color\\n    overlayColor = mix(defaultColor, overlayColor, overlayColor.a);\\n    gl_FragColor = mix(defaultColor, overlayColor, confidence);\\n  }\\n "}C(){const e=this.g;e.activeTexture(e.TEXTURE1),this.j=co(this,e),e.activeTexture(e.TEXTURE2),this.B=co(this,e)}m(){super.m();const e=this.g;this.K=so(e.getUniformLocation(this.h,"defaultTexture"),"Uniform location"),this.L=so(e.getUniformLocation(this.h,"overlayTexture"),"Uniform location"),this.I=so(e.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const e=this.g;e.uniform1i(this.I,0),e.uniform1i(this.K,1),e.uniform1i(this.L,2)}close(){this.j&&this.g.deleteTexture(this.j),this.B&&this.g.deleteTexture(this.B),super.close()}};function yo(e,t){switch(t){case 0:return e.g.find(e=>e instanceof Uint8Array);case 1:return e.g.find(e=>e instanceof Float32Array);case 2:return e.g.find(e=>"undefined"!=typeof WebGLTexture&&e instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function bo(e){var t=yo(e,1);if(!t){if(t=yo(e,0))t=new Float32Array(t).map(e=>e/255);else{t=new Float32Array(e.width*e.height);const r=wo(e);var n=ko(e);if(ho(n,r,xo(e)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){n=new Float32Array(e.width*e.height*4),r.readPixels(0,0,e.width,e.height,r.RGBA,r.FLOAT,n);for(let e=0,r=0;e<t.length;++e,r+=4)t[e]=n[r]}else r.readPixels(0,0,e.width,e.height,r.RED,r.FLOAT,t)}e.g.push(t)}return t}function xo(e){let t=yo(e,2);if(!t){const n=wo(e);t=Io(e);const r=bo(e),s=vo(e);n.texImage2D(n.TEXTURE_2D,0,s,e.width,e.height,0,n.RED,n.FLOAT,r),So(e)}return t}function wo(e){if(!e.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return e.h||(e.h=so(e.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),e.h}function vo(e){if(e=wo(e),!No)if(e.getExtension("EXT_color_buffer_float")&&e.getExtension("OES_texture_float_linear")&&e.getExtension("EXT_float_blend"))No=e.R32F;else{if(!e.getExtension("EXT_color_buffer_half_float"))throw Error("GPU does not fully support 4-channel float32 or float16 formats");No=e.R16F}return No}function ko(e){return e.l||(e.l=new fo),e.l}function Io(e){const t=wo(e);t.viewport(0,0,e.width,e.height),t.activeTexture(t.TEXTURE0);let n=yo(e,2);return n||(n=co(ko(e),t,e.m?t.LINEAR:t.NEAREST),e.g.push(n),e.j=!0),t.bindTexture(t.TEXTURE_2D,n),n}function So(e){e.h.bindTexture(e.h.TEXTURE_2D,null)}var No,To=class{constructor(e,t,n,r,s,a,i){this.g=e,this.m=t,this.j=n,this.canvas=r,this.l=s,this.width=a,this.height=i,this.j&&0===--Eo&&console.error("You seem to be creating MPMask instances without invoking .close(). This leaks resources.")}Ha(){return!!yo(this,0)}la(){return!!yo(this,1)}R(){return!!yo(this,2)}ka(){return(e=yo(this,0))||(e=bo(this),e=new Uint8Array(e.map(e=>255*e)),this.g.push(e)),e;var e}ja(){return bo(this)}N(){return xo(this)}clone(){const e=[];for(const t of this.g){let n;if(t instanceof Uint8Array)n=new Uint8Array(t);else if(t instanceof Float32Array)n=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const e=wo(this),t=ko(this);e.activeTexture(e.TEXTURE1),n=co(t,e,this.m?e.LINEAR:e.NEAREST),e.bindTexture(e.TEXTURE_2D,n);const r=vo(this);e.texImage2D(e.TEXTURE_2D,0,r,this.width,this.height,0,e.RED,e.FLOAT,null),e.bindTexture(e.TEXTURE_2D,null),ho(t,e,n),lo(t,e,!1,()=>{Io(this),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),So(this)}),po(t),So(this)}}
5057e.push(n)}return new To(e,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&wo(this).deleteTexture(yo(this,2)),Eo=-1}};To.prototype.close=To.prototype.close,To.prototype.clone=To.prototype.clone,To.prototype.getAsWebGLTexture=To.prototype.N,To.prototype.getAsFloat32Array=To.prototype.ja,To.prototype.getAsUint8Array=To.prototype.ka,To.prototype.hasWebGLTexture=To.prototype.R,To.prototype.hasFloat32Array=To.prototype.la,To.prototype.hasUint8Array=To.prototype.Ha;var Eo=250;const Co={color:"white",lineWidth:4,radius:6};function $o(e){return{...Co,fillColor:(e=e||{}).color,...e}}function Ao(e,t){return e instanceof Function?e(t):e}function Ro(e,t,n){return Math.max(Math.min(t,n),Math.min(Math.max(t,n),e))}function _o(e){if(!e.l)throw Error("CPU rendering requested but CanvasRenderingContext2D not provided.");return e.l}function Mo(e){if(!e.j)throw Error("GPU rendering requested but WebGL2RenderingContext not provided.");return e.j}function Fo(e,t,n){if(t.R())n(t.N());else{const r=t.la()?t.ja():t.ka();e.m=e.m??new fo;const s=Mo(e);n((e=new To([r],t.m,!1,s.canvas,e.m,t.width,t.height)).N()),e.close()}}function Do(e,t,n,r){const s=function(e){return e.g||(e.g=new mo),e.g}(e),a=Mo(e),i=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n;lo(s,a,!0,()=>{!function(e,t,n,r){const s=e.g;if(s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,t),s.activeTexture(s.TEXTURE1),s.bindTexture(s.TEXTURE_2D,e.B),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,n),e.I&&function(e,t){if(e!==t)return!1;e=e.entries(),t=t.entries();for(const[r,s]of e){e=r;const a=s;var n=t.next();if(n.done)return!1;const[i,o]=n.value;if(n=o,e!==i||a[0]!==n[0]||a[1]!==n[1]||a[2]!==n[2]||a[3]!==n[3])return!1}return!!t.next().done}(e.I,r))s.activeTexture(s.TEXTURE2),s.bindTexture(s.TEXTURE_2D,e.j);else{e.I=r;const t=Array(1024).fill(0);r.forEach((e,n)=>{if(4!==e.length)throw Error(`Color at index ${n} is not a four-channel value.`);t[4*n]=e[0],t[4*n+1]=e[1],t[4*n+2]=e[2],t[4*n+3]=e[3]}),s.activeTexture(s.TEXTURE2),s.bindTexture(s.TEXTURE_2D,e.j),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,256,1,0,s.RGBA,s.UNSIGNED_BYTE,new Uint8Array(t))}}(s,t,i,r),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.drawArrays(a.TRIANGLE_FAN,0,4);const e=s.g;e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,null)})}function Oo(e,t,n,r){const s=Mo(e),a=function(e){return e.h||(e.h=new go),e.h}(e),i=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n,o=Array.isArray(r)?new ImageData(new Uint8ClampedArray(r),1,1):r;lo(a,s,!0,()=>{var e=a.g;e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a.j),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,i),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,a.B),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.drawArrays(s.TRIANGLE_FAN,0,4),s.bindTexture(s.TEXTURE_2D,null),(e=a.g).activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,null)})}var Lo=class{constructor(e,t){e instanceof CanvasRenderingContext2D||e instanceof OffscreenCanvasRenderingContext2D?(this.l=e,this.j=t):this.j=e}Aa(e,t){if(e){var n=_o(this);t=$o(t),n.save();var r=n.canvas,s=0;for(const a of e)n.fillStyle=Ao(t.fillColor,{index:s,from:a}),n.strokeStyle=Ao(t.color,{index:s,from:a}),n.lineWidth=Ao(t.lineWidth,{index:s,from:a}),(e=new Path2D).arc(a.x*r.width,a.y*r.height,Ao(t.radius,{index:s,from:a}),0,2*Math.PI),n.fill(e),n.stroke(e),++s;n.restore()}}za(e,t,n){if(e&&t){var r=_o(this);n=$o(n),r.save();var s=r.canvas,a=0;for(const i of t){r.beginPath(),t=e[i.start];const o=e[i.end];t&&o&&(r.strokeStyle=Ao(n.color,{index:a,from:t,to:o}),r.lineWidth=Ao(n.lineWidth,{index:a,from:t,to:o}),r.moveTo(t.x*s.width,t.y*s.height),r.lineTo(o.x*s.width,o.y*s.height)),++a,r.stroke()}
5057r.restore()}}wa(e,t){const n=_o(this);t=$o(t),n.save(),n.beginPath(),n.lineWidth=Ao(t.lineWidth,{}),n.strokeStyle=Ao(t.color,{}),n.fillStyle=Ao(t.fillColor,{}),n.moveTo(e.originX,e.originY),n.lineTo(e.originX+e.width,e.originY),n.lineTo(e.originX+e.width,e.originY+e.height),n.lineTo(e.originX,e.originY+e.height),n.lineTo(e.originX,e.originY),n.stroke(),n.fill(),n.restore()}xa(e,t,n=[0,0,0,255]){this.l?function(e,t,n,r){const s=Mo(e);Fo(e,t,t=>{Do(e,t,n,r),(t=_o(e)).drawImage(s.canvas,0,0,t.canvas.width,t.canvas.height)})}(this,e,n,t):Do(this,e.N(),n,t)}ya(e,t,n){this.l?function(e,t,n,r){const s=Mo(e);Fo(e,t,t=>{Oo(e,t,n,r),(t=_o(e)).drawImage(s.canvas,0,0,t.canvas.width,t.canvas.height)})}(this,e,t,n):Oo(this,e.N(),t,n)}close(){this.g?.close(),this.g=void 0,this.h?.close(),this.h=void 0,this.m?.close(),this.m=void 0}};function zo(e,t){switch(t){case 0:return e.g.find(e=>e instanceof ImageData);case 1:return e.g.find(e=>"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap);case 2:return e.g.find(e=>"undefined"!=typeof WebGLTexture&&e instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function Po(e){var t=zo(e,0);if(!t){t=Vo(e);const n=Uo(e),r=new Uint8Array(e.width*e.height*4);ho(n,t,Bo(e)),t.readPixels(0,0,e.width,e.height,t.RGBA,t.UNSIGNED_BYTE,r),po(n),t=new ImageData(new Uint8ClampedArray(r.buffer),e.width,e.height),e.g.push(t)}return t}function Bo(e){let t=zo(e,2);if(!t){const n=Vo(e);t=Wo(e);const r=zo(e,1)||Po(e);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),Go(e)}return t}function Vo(e){if(!e.canvas)throw Error("Conversion to different image formats require that a canvas is passed when iniitializing the image.");return e.h||(e.h=so(e.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),e.h}function Uo(e){return e.l||(e.l=new fo),e.l}function Wo(e){const t=Vo(e);t.viewport(0,0,e.width,e.height),t.activeTexture(t.TEXTURE0);let n=zo(e,2);return n||(n=co(Uo(e),t),e.g.push(n),e.m=!0),t.bindTexture(t.TEXTURE_2D,n),n}function Go(e){e.h.bindTexture(e.h.TEXTURE_2D,null)}function Ho(e){const t=Vo(e);return lo(Uo(e),t,!0,()=>function(e,t){const n=e.canvas;if(n.width===e.width&&n.height===e.height)return t();const r=n.width,s=n.height;return n.width=e.width,n.height=e.height,e=t(),n.width=r,n.height=s,e}(e,()=>{if(t.bindFramebuffer(t.FRAMEBUFFER,null),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLE_FAN,0,4),!(e.canvas instanceof OffscreenCanvas))throw Error("Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas");return e.canvas.transferToImageBitmap()}))}Lo.prototype.close=Lo.prototype.close,Lo.prototype.drawConfidenceMask=Lo.prototype.ya,Lo.prototype.drawCategoryMask=Lo.prototype.xa,Lo.prototype.drawBoundingBox=Lo.prototype.wa,Lo.prototype.drawConnectors=Lo.prototype.za,Lo.prototype.drawLandmarks=Lo.prototype.Aa,Lo.lerp=function(e,t,n,r,s){return Ro(r*(1-(e-t)/(n-t))+s*(1-(n-e)/(n-t)),r,s)},Lo.clamp=Ro;var jo=class{constructor(e,t,n,r,s,a,i){this.g=e,this.j=t,this.m=n,this.canvas=r,this.l=s,this.width=a,this.height=i,(this.j||this.m)&&0===--qo&&console.error("You seem to be creating MPImage instances without invoking .close(). This leaks resources.")}Ga(){return!!zo(this,0)}ma(){return!!zo(this,1)}R(){return!!zo(this,2)}Ea(){return Po(this)}Da(){var e=zo(this,1);return e||(Bo(this),Wo(this),e=Ho(this),Go(this),this.g.push(e),this.j=!0),e}N(){return Bo(this)}clone(){const e=[];for(const t of this.g){let n;if(t instanceof ImageData)n=new ImageData(t.data,this.width,this.height);else if(t instanceof WebGLTexture){const e=Vo(this),t=Uo(this);e.activeTexture(e.TEXTURE1),n=co(t,e),e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,null),e.bindTexture(e.TEXTURE_2D,null),ho(t,e,n),lo(t,e,!1,()=>{Wo(this),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),Go(this)}),po(t),Go(this)}else{if(!(t instanceof ImageBitmap))throw Error(`Type is not supported: ${t}`);Bo(this),Wo(this),n=Ho(this),Go(this)}e.push(n)}return new jo(e,this.ma(),this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&zo(this,1).close(),this.m&&Vo(this).deleteTexture(zo(this,2)),qo=-1}};jo.prototype.close=jo.prototype.close,jo.prototype.clone=jo.prototype.clone,jo.prototype.getAsWebGLTexture=jo.prototype.N,jo.prototype.getAsImageBitmap=jo.prototype.Da,jo.prototype.getAsImageData=jo.prototype.Ea,jo.prototype.hasWebG
5057LTexture=jo.prototype.R,jo.prototype.hasImageBitmap=jo.prototype.ma,jo.prototype.hasImageData=jo.prototype.Ga;var qo=250;function Ko(...e){return e.map(([e,t])=>({start:e,end:t}))}const Xo=function(e){return class extends e{Ma(){this.i._registerModelResourcesGraphService()}}}((Yo=class{constructor(e,t){this.l=!0,this.i=e,this.g=null,this.h=0,this.m="function"==typeof this.i._addIntToInputStream,void 0!==t?this.i.canvas=t:Wi()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(e){const t=await(await fetch(e)).arrayBuffer();e=!(e.endsWith(".pbtxt")||e.endsWith(".textproto")),this.setGraph(new Uint8Array(t),e)}setGraphFromString(e){this.setGraph((new TextEncoder).encode(e),!1)}setGraph(e,t){const n=e.length,r=this.i._malloc(n);this.i.HEAPU8.set(e,r),t?this.i._changeBinaryGraph(n,r):this.i._changeTextGraph(n,r),this.i._free(r)}configureAudio(e,t,n,r,s){this.i._configureAudio||console.warn(\'Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?\'),ji(this,r||"input_audio",r=>{ji(this,s=s||"audio_header",s=>{this.i._configureAudio(r,s,e,t??0,n)})})}setAutoResizeCanvas(e){this.l=e}setAutoRenderToScreen(e){this.i._setAutoRenderToScreen(e)}setGpuBufferVerticalFlip(e){this.i.gpuOriginForWebTexturesIsBottomLeft=e}ea(e){Xi(this,"__graph_config__",t=>{e(t)}),ji(this,"__graph_config__",e=>{this.i._getGraphConfig(e,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(e){this.i.errorListener=e}attachEmptyPacketListener(e,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[e]=t}addAudioToStream(e,t,n){this.addAudioToStreamWithShape(e,0,0,t,n)}addAudioToStreamWithShape(e,t,n,r,s){const a=4*e.length;this.h!==a&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(a),this.h=a),this.i.HEAPF32.set(e,this.g/4),ji(this,r,e=>{this.i._addAudioToInputStream(this.g,t,n,e,s)})}addGpuBufferToStream(e,t,n){ji(this,t,t=>{const[r,s]=qi(this,e,t);this.i._addBoundTextureToStream(t,r,s,n)})}addBoolToStream(e,t,n){ji(this,t,t=>{this.i._addBoolToInputStream(e,t,n)})}addDoubleToStream(e,t,n){ji(this,t,t=>{this.i._addDoubleToInputStream(e,t,n)})}addFloatToStream(e,t,n){ji(this,t,t=>{this.i._addFloatToInputStream(e,t,n)})}addIntToStream(e,t,n){ji(this,t,t=>{this.i._addIntToInputStream(e,t,n)})}addUintToStream(e,t,n){ji(this,t,t=>{this.i._addUintToInputStream(e,t,n)})}addStringToStream(e,t,n){ji(this,t,t=>{ji(this,e,e=>{this.i._addStringToInputStream(e,t,n)})})}addStringRecordToStream(e,t,n){ji(this,t,t=>{Ki(this,Object.keys(e),r=>{Ki(this,Object.values(e),s=>{this.i._addFlatHashMapToInputStream(r,s,Object.keys(e).length,t,n)})})})}addProtoToStream(e,t,n,r){ji(this,n,n=>{ji(this,t,t=>{const s=this.i._malloc(e.length);this.i.HEAPU8.set(e,s),this.i._addProtoToInputStream(s,e.length,t,n,r),this.i._free(s)})})}addEmptyPacketToStream(e,t){ji(this,e,e=>{this.i._addEmptyPacketToInputStream(e,t)})}addBoolVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateBoolVector(e.length);if(!r)throw Error("Unable to allocate new bool vector on heap.");for(const t of e)this.i._addBoolVectorEntry(r,t);this.i._addBoolVectorToInputStream(r,t,n)})}addDoubleVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateDoubleVector(e.length);if(!r)throw Error("Unable to allocate new double vector on heap.");for(const t of e)this.i._addDoubleVectorEntry(r,t);this.i._addDoubleVectorToInputStream(r,t,n)})}addFloatVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateFloatVector(e.length);if(!r)throw Error("Unable to allocate new float vector on heap.");for(const t of e)this.i._addFloatVectorEntry(r,t);this.i._addFloatVectorToInputStream(r,t,n)})}addIntVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateIntVector(e.length);if(!r)throw Error("Unable to allocate new int vector on heap.");for(const t of e)this.i._addIntVectorEntry(r,t);this.i._addIntVectorToInputStream(r,t,n)})}addUintVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateUintVector(e.length);if(!r)throw Error("Unable to allocate new unsigned int vector on heap.");for(const t of e)this.i._addUintVectorEntry(r,t);this.i._addUintVectorToInputStream(r,t,n)})}addStringVectorToStream(e,t,n){ji(this,t,t=>{const r=this.i._allocateStringVector(e.length);if(!r)throw Error("Unable to allocate new string vector on heap.");for(const t of e)ji(this,t,e=>{this.i._addStringVectorEntry(r,e)});this.i._addStringVectorToInputStream(r,t,n)})}addBoolToInputSidePacket(e,t){ji(this,t,t=>{this.i._addBoolToInputSidePacket(e,t)})}addDoubleToInputSidePacket(e,t){ji(this,t,t=>{this.i._addDoubleToInputSidePacket(e,t)})}addFloatToInputSidePacket(e,t){ji(this,t,t=>{this.i._addFloatToInputSidePacket(e,t)})}addIntToInputSidePacket(e,t){ji(this,t,t=>{this.i._addIntToInputSidePacket(e,t)})}addUintToInputSidePacket(e,t){ji(this,t,t=>{this.i._addUintToInputSidePacket(e,t)})}addStringToInputSidePacket(e,t){ji(this,t,t=>{ji(this,e,e=>{this.i._addStringToInputSidePacket(e,t)})})}addProtoToInputSidePacket(e,t,n){ji(this,n,n=>{ji(this,t,t=>{const r=this.i._malloc(e.length);this.i.HEAPU8.set(e,r),this.i._addProtoToInputSidePacket(r,e.length,t,n),this.i._free(r)})})}addBoolVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateBoolVector(e.length);if(!n)throw Error("Unable to allocate new bool vector on heap.");for(const t of e)this.i._addBoolVectorEntry(n,t);this.i._addBoolVectorToInputSidePacket(n,t)})}addDoubleVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateDoubleVector(e.length);if(!n)throw Error("Unable to allocate new double vector on heap.");for(const t of e)this.i._addDoubleVectorEntry(n,t);this.i._addDoubleVectorToInputSidePacket(n,t)})}addFloatVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateFloatVector(e.length);if(!n)throw Error("Unable to allocate new float vector on heap.");for(const t of e)this.i._addFloatVectorEntry(n,t);this.i._addFloatVectorToInputSidePacket(n,t)})}addIntVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateIntVector(e.length);if(!n)throw Error("Unable to allocate new int vector on heap.");for(const t of e)this.i._addIntVectorEntry(n,t);this.i._addIntVectorToInputSidePacket(n,t)})}addUintVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateUintVector(e.length);if(!n)throw Error("Unable to allocate new unsigned int vector on heap.");for(const t of e)this.i._addUintVectorEntry(n,t);this.i._addUintVectorToInputSidePacket(n,t)})}addStringVectorToInputSidePacket(e,t){ji(this,t,t=>{const n=this.i._allocateStringVector(e.length);if(!n)throw Error("Unable to allocate new string vector on heap.");for(const t of e)ji(this,t,e=>{this.i._addStringVectorEntry(n,e)});this.i._addStringVectorToInputSidePacket(n,t)})}attachBoolListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachBoolListener(e)})}attachBoolVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachBoolVectorListener(e)})}attachIntListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachIntListener(e)})}attachIntVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachIntVectorListener(e)})}attachUintListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachUintListener(e)})}attachUintVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachUintVectorListener(e)})}attachDoubleListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachDoubleListener(e)})}attachDoubleVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachDoubleVectorListener(e)})}attachFloatListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachFloatListener(e)})}attachFloatVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachFloatVectorListener(e)})}attachStringListener(e,t){Xi(this,e,t),ji(this,e,e=>{this.i._attachStringListener(e)})}attachStringVectorListener(e,t){Yi(this,e,t),ji(this,e,e=>{this.i._attachStringVectorListener(e)})}attachProtoListener(e,t,n){Xi(this,e,t),ji(this,e,e=>{this.i._attachProtoListener(e,n||!1)})}attachProtoVectorListener(e,t,n){Yi(this,e,t),ji(this,e,e=>{this.i._attachProtoVectorListener(e,n||!1)})}attachAudioListener(e,t,n){this.i._attachAudioListener||console.warn(\'Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?\'),Xi(this,e,(e,n)=>{e=new Float32Array(e.buffer,e.byteOffset,e.length/4),t(e,n)}),ji(this,e,e=>{this.i._attachAudioListener(e,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends Yo{get ga(){return this.i}
vendor: 4,835 bytes, line 5057
5057sa(e,t,n){ji(this,t,t=>{const[r,s]=qi(this,e,t);this.ga._addBoundTextureAsImageToStream(t,r,s,n)})}V(e,t){Xi(this,e,t),ji(this,e,e=>{this.ga._attachImageListener(e)})}da(e,t){Yi(this,e,t),ji(this,e,e=>{this.ga._attachImageVectorListener(e)})}}));var Yo,Jo=class extends Xo{};async function Zo(e,t,n){return async function(e,t,n,r){return async function(e,t,n,r){return e=await(async(e,t,n,r,s)=>{if(t&&await Gi(t),!self.ModuleFactory)throw Error("ModuleFactory not set.");if(n&&(await Gi(n),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&s&&((t=self.Module).locateFile=s.locateFile,s.mainScriptUrlOrBlob&&(t.mainScriptUrlOrBlob=s.mainScriptUrlOrBlob)),s=await self.ModuleFactory(self.Module||s),self.ModuleFactory=self.Module=void 0,new e(s,r)})(e,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:e=>e.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&e.endsWith(".data")?n.assetBinaryPath.toString():e}),await e.o(r),e}(e,t,n,r)}(e,n.canvas??(Wi()?void 0:document.createElement("canvas")),t,n)}function Qo(e,t,n,r){if(e.U){const a=new Ia;if(n?.regionOfInterest){if(!e.ra)throw Error("This task doesn\'t support region-of-interest.");var s=n.regionOfInterest;if(s.left>=s.right||s.top>=s.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(s.left<0||s.top<0||s.right>1||s.bottom>1)throw Error("Expected RectF values to be in [0,1].");Cn(a,1,(s.left+s.right)/2),Cn(a,2,(s.top+s.bottom)/2),Cn(a,4,s.right-s.left),Cn(a,3,s.bottom-s.top)}else Cn(a,1,.5),Cn(a,2,.5),Cn(a,4,1),Cn(a,3,1);if(n?.rotationDegrees){if(n?.rotationDegrees%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Cn(a,5,-Math.PI*n.rotationDegrees/180),n?.rotationDegrees%180!=0){const[e,r]=Hi(t);n=Sn(a,3)*r/e,s=Sn(a,4)*e/r,Cn(a,4,n),Cn(a,3,s)}}e.g.addProtoToStream(a.g(),"mediapipe.NormalizedRect",e.U,r)}e.g.sa(t,e.ba,r??performance.now()),e.finishProcessing()}function eu(e,t,n){if(e.baseOptions?.g())throw Error("Task is not initialized with image mode. \'runningMode\' must be set to \'IMAGE\'.");Qo(e,t,n,e.B+1)}function tu(e,t,n,r){if(!e.baseOptions?.g())throw Error("Task is not initialized with video mode. \'runningMode\' must be set to \'VIDEO\'.");Qo(e,t,n,r)}function nu(e,t,n,r){var s=t.data;const a=t.width,i=a*(t=t.height);if((s instanceof Uint8Array||s instanceof Float32Array)&&s.length!==i)throw Error("Unsupported channel count: "+s.length/i);return e=new To([s],n,!1,e.g.i.canvas,e.P,a,t),r?e.clone():e}var ru=class extends ro{constructor(e,t,n,r){super(e),this.g=e,this.ba=t,this.U=n,this.ra=r,this.P=new fo}l(e,t=!0){if("runningMode"in e&&Tn(this.baseOptions,2,!!e.runningMode&&"IMAGE"!==e.runningMode),void 0!==e.canvas&&this.g.i.canvas!==e.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(e,t)}close(){this.P.close(),super.close()}};ru.prototype.close=ru.prototype.close;var su=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect_in",!1),this.j={detections:[]},yn(e=this.h=new Va,0,1,t=new za),Cn(this.h,2,.5),Cn(this.h,3,.3)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return"minDetectionConfidence"in e&&Cn(this.h,2,e.minDetectionConfidence??.5),"minSuppressionThreshold"in e&&Cn(this.h,3,e.minSuppressionThreshold??.3),this.l(e)}D(e,t){return this.j={detections:[]},eu(this,e,t),this.j}F(e,t,n){return this.j={detections:[]},tu(this,e,n,t),this.j}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect_in"),aa(e,"detections");const t=new qs;tr(t,Wa,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect_in"),Zs(n,"DETECTIONS:detections"),n.o(t),ra(e,n),this.g.attachProtoVectorListener("detections",(e,t)=>{for(const t of e)e=ga(t),this.j.detections.push(Mi(e));Qi(this,t)}),this.g.attachEmptyPacketListener("detections",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};su.prototype.detectForVideo=su.prototype.F,su.prototype.detect=su.prototype.D,su.prototype.setOptions=su.prototype.o,su.createFromModelPath=async function(e,t){return Zo(su,e,{baseOptions:{modelAssetPath:t}})},su.createFromModelBuffer=function(e,t){return Zo(su,e,{baseOptions:{modelAssetBuffer:t}})},su.createFromOptions=function(e,t){return Zo(su,e,t)};var au=Ko([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),iu=Ko([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),ou
5057=Ko([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),uu=Ko([474,475],[475,476],[476,477],[477,474]),lu=Ko([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),cu=Ko([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),hu=Ko([469,470],[470,471],[471,472],[472,469]),du=Ko([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),pu=[...au,...iu,...ou,...lu,...cu,...du],fu=Ko(
vendor: 8,528 bytes, line 5057
5057[127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400
vendor: 15,824 bytes, line 5057
5057],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function 
vendor: 3,057 bytes, line 5057
5057mu(e){e.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var gu=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,yn(e=this.h=new ja,0,1,t=new za),this.v=new Ha,yn(this.h,0,3,this.v),this.s=new Va,yn(this.h,0,2,this.s),En(this.s,4,1),Cn(this.s,2,.5),Cn(this.v,2,.5),Cn(this.h,4,.5)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return"numFaces"in e&&En(this.s,4,e.numFaces??1),"minFaceDetectionConfidence"in e&&Cn(this.s,2,e.minFaceDetectionConfidence??.5),"minTrackingConfidence"in e&&Cn(this.h,4,e.minTrackingConfidence??.5),"minFacePresenceConfidence"in e&&Cn(this.v,2,e.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in e&&(this.outputFaceBlendshapes=!!e.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in e&&(this.outputFacialTransformationMatrixes=!!e.outputFacialTransformationMatrixes),this.l(e)}D(e,t){return mu(this),eu(this,e,t),this.j}F(e,t,n){return mu(this),tu(this,e,n,t),this.j}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"face_landmarks");const t=new qs;tr(t,Xa,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),ra(e,n),this.g.attachProtoVectorListener("face_landmarks",(e,t)=>{for(const t of e)e=wa(t),this.j.faceLandmarks.push(Fi(e));Qi(this,t)}),this.g.attachEmptyPacketListener("face_landmarks",e=>{Qi(this,e)}),this.outputFaceBlendshapes&&(aa(e,"blendshapes"),Zs(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(e,t)=>{if(this.outputFaceBlendshapes)for(const t of e)e=da(t),this.j.faceBlendshapes.push(_i(e.g()??[]));Qi(this,t)}),this.g.attachEmptyPacketListener("blendshapes",e=>{Qi(this,e)})),this.outputFacialTransformationMatrixes&&(aa(e,"face_geometry"),Zs(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(e,t)=>{if(this.outputFacialTransformationMatrixes)for(const t of e)(e=fn(Ga(t),va,2))&&this.j.facialTransformationMatrixes.push({rows:kn(In(e,1),0)??0,columns:kn(In(e,2),0)??0,data:tn(e,3,He,en()).slice()??[]});Qi(this,t)}),this.g.attachEmptyPacketListener("face_geometry",e=>{Qi(this,e)})),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};gu.prototype.detectForVideo=gu.prototype.F,gu.prototype.detect=gu.prototype.D,gu.prototype.setOptions=gu.prototype.o,gu.createFromModelPath=function(e,t){return Zo(gu,e,{baseOptions:{modelAssetPath:t}})},gu.createFromModelBuffer=function(e,t){return Zo(gu,e,{baseOptions:{modelAssetBuffer:t}})},gu.createFromOptions=function(e,t){return Zo(gu,e,t)},gu.FACE_LANDMARKS_LIPS=au,gu.FACE_LANDMARKS_LEFT_EYE=iu,gu.FACE_LANDMARKS_LEFT_EYEBROW=ou,gu.FACE_LANDMARKS_LEFT_IRIS=uu,gu.FACE_LANDMARKS_RIGHT_EYE=lu,gu.FACE_LANDMARKS_RIGHT_EYEBROW=cu,gu.FACE_LANDMARKS_RIGHT_IRIS=hu,gu.FACE_LANDMARKS_FACE_OVAL=du,gu.FACE_LANDMARKS_CONTOU
vendor: 6,444 bytes, line 5057
5057RS=pu,gu.FACE_LANDMARKS_TESSELATION=fu;var yu=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!0),yn(e=this.j=new Ya,0,1,t=new za)}get baseOptions(){return fn(this.j,za,1)}set baseOptions(e){yn(this.j,0,1,e)}o(e){return super.l(e)}Pa(e,t,n){const r="function"!=typeof t?t:{};if(this.h="function"==typeof t?t:n,eu(this,e,r??{}),!this.h)return this.s}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"stylized_image");const t=new qs;tr(t,Ja,this.j);const n=new Qs;Ys(n,"mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"STYLIZED_IMAGE:stylized_image"),n.o(t),ra(e,n),this.g.V("stylized_image",(e,t)=>{var n=!this.h,r=e.data,s=e.width;const a=s*(e=e.height);if(r instanceof Uint8Array)if(r.length===3*a){const t=new Uint8ClampedArray(4*a);for(let e=0;e<a;++e)t[4*e]=r[3*e],t[4*e+1]=r[3*e+1],t[4*e+2]=r[3*e+2],t[4*e+3]=255;r=new ImageData(t,s,e)}else{if(r.length!==4*a)throw Error("Unsupported channel count: "+r.length/a);r=new ImageData(new Uint8ClampedArray(r.buffer,r.byteOffset,r.length),s,e)}else if(!(r instanceof WebGLTexture))throw Error(`Unsupported format: ${r.constructor.name}`);s=new jo([r],!1,!1,this.g.i.canvas,this.P,s,e),this.s=n=n?s.clone():s,this.h&&this.h(n),Qi(this,t)}),this.g.attachEmptyPacketListener("stylized_image",e=>{this.s=null,this.h&&this.h(null),Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};yu.prototype.stylize=yu.prototype.Pa,yu.prototype.setOptions=yu.prototype.o,yu.createFromModelPath=function(e,t){return Zo(yu,e,{baseOptions:{modelAssetPath:t}})},yu.createFromModelBuffer=function(e,t){return Zo(yu,e,{baseOptions:{modelAssetBuffer:t}})},yu.createFromOptions=function(e,t){return Zo(yu,e,t)};var bu=Ko([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function xu(e){e.gestures=[],e.landmarks=[],e.worldLandmarks=[],e.handedness=[]}function wu(e){return 0===e.gestures.length?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:e.gestures,landmarks:e.landmarks,worldLandmarks:e.worldLandmarks,handedness:e.handedness,handednesses:e.handedness}}function vu(e,t=!0){const n=[];for(const s of e){var r=da(s);e=[];for(const n of r.g())r=t&&null!=In(n,1)?kn(In(n,1),0):-1,e.push({score:Sn(n,2)??0,index:r,categoryName:Nn(n,3)??"",displayName:Nn(n,4)??""});n.push(e)}return n}var ku=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],yn(e=this.j=new si,0,1,t=new za),this.s=new ri,yn(this.j,0,2,this.s),this.C=new ni,yn(this.s,0,3,this.C),this.v=new ti,yn(this.s,0,2,this.v),this.h=new ei,yn(this.j,0,3,this.h),Cn(this.v,2,.5),Cn(this.s,4,.5),Cn(this.C,2,.5)}get baseOptions(){return fn(this.j,za,1)}set baseOptions(e){yn(this.j,0,1,e)}o(e){if(En(this.v,3,e.numHands??1),"minHandDetectionConfidence"in e&&Cn(this.v,2,e.minHandDetectionConfidence??.5),"minTrackingConfidence"in e&&Cn(this.s,4,e.minTrackingConfidence??.5),"minHandPresenceConfidence"in e&&Cn(this.C,2,e.minHandPresenceConfidence??.5),e.cannedGesturesClassifierOptions){var t=new Za,n=t,r=Ri(e.cannedGesturesClassifierOptions,fn(this.h,Za,3)?.h());yn(n,0,2,r),yn(this.h,0,3,t)}else void 0===e.cannedGesturesClassifierOptions&&fn(this.h,Za,3)?.g();return e.customGesturesClassifierOptions?(yn(n=t=new Za,0,2,r=Ri(e.customGesturesClassifierOptions,fn(this.h,Za,4)?.h())),yn(this.h,0,4,t)):void 0===e.customGesturesClassifierOptions&&fn(this.h,Za,4)?.g(),this.l(e)}Ka(e,t){return xu(this),eu(this,e,t),wu(this)}La(e,t,n){return xu(this),tu(this,e,n,t),wu(this)}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"hand_gestures"),aa(e,"hand_landmarks"),aa(e,"world_hand_landmarks"),aa(e,"handedness");const t=new qs;tr(t,li,this.j);const n=new Qs;Ys(n,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"HAND_GESTURES:hand_gestures"),Zs(n,"LANDMARKS:hand_landmarks"),Zs(n,"WORLD_LANDMARKS:world_hand_landmarks"),Zs(n,"HANDEDNESS:handedness"),n.o(t),ra(e,n),this.g.attachProtoVectorListener("hand_landmarks",(e,t)=>{for(const t of e){e=wa(t);const n=[];for(const t of gn(e,xa,1))n.push({x:Sn(t,1)??0,y:Sn(t,2)??0,z:Sn(t,3)??0,visibility:Sn(t,4)??0});this.landmarks.push(n)}Qi(this,t)}),this.g.attachEmptyPacketListener("hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoVectorListener("world_hand_landmarks",(e,t)=>{for(const t of e){e=ba(t);const n=[];for(const t of gn(e,ya,1))n.push({x:Sn(t,1)??0,y:Sn(t,2)??0,z:Sn(t,3)??0,visibility:Sn(t,4)??0});this.worldLandmarks.push(n)}Qi(this,t)}),this.g.attachEmptyPacketListener("world_hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoVectorListener("hand_gestures",(e,t)=>{this.gestures.push(...vu(e,!1)),Qi(this,t)}),this.g.attachEmptyPacketListener("hand_gestures",e=>{Qi(this,e)}),this.g.attachProtoVectorListener("handedness",(e,t)=>{this.handedness.push(...vu(e)),Qi(this,t)}),this.g.attachEmptyPacketListener("handedness",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};function Iu(e){return{landmarks:e.landmarks,worldLandmarks:e.worldLandmarks,handednesses:e.handedness,handedness:e.handedness}}ku.prototype.recognizeForVideo=ku.prototype.La,ku.prototype.recognize=ku.prototype.Ka,ku.prototype.setOptions=ku.prototype.o,ku.createFromModelPath=function(e,t){return Zo(ku,e,{baseOptions:{modelAssetPath:t}})},ku.createFromModelBuffer=function(e,t){return Zo(ku,e,{baseOptions:{modelAssetBuffer:t}})},ku.createFromOptions=function(e,t){return Zo(ku,e,t)},ku.HAND_CONNECTIONS=bu;var Su=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],yn(e=this.h=new ri,0,1,t=new za),this.s=new ni,yn(this.h,0,3,this.s),this.j=new ti,yn(this.h,0,2,this.j),En(this.j,3,1),Cn(this.j,2,.5),Cn(this.s,2,.5),Cn(this.h,4,.5)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return"numHands"in e&&En(this.j,3,e.numHands??1),"minHandDetectionConfidence"in e&&Cn(this.j,2,e.minHandDetectionConfidence??.5),"minTrackingConfidence"in e&&Cn(this.h,4,e.minTrackingConfidence??.5),"minHandPresenceConfidence"in e&&Cn(this.s,2,e.minHandPresenceConfidence??.5),this.l(e)}D(e,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],eu(this,e,t),Iu(this)}
5057F(e,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],tu(this,e,n,t),Iu(this)}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"hand_landmarks"),aa(e,"world_hand_landmarks"),aa(e,"handedness");const t=new qs;tr(t,ci,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"LANDMARKS:hand_landmarks"),Zs(n,"WORLD_LANDMARKS:world_hand_landmarks"),Zs(n,"HANDEDNESS:handedness"),n.o(t),ra(e,n),this.g.attachProtoVectorListener("hand_landmarks",(e,t)=>{for(const t of e)e=wa(t),this.landmarks.push(Fi(e));Qi(this,t)}),this.g.attachEmptyPacketListener("hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoVectorListener("world_hand_landmarks",(e,t)=>{for(const t of e)e=ba(t),this.worldLandmarks.push(Di(e));Qi(this,t)}),this.g.attachEmptyPacketListener("world_hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoVectorListener("handedness",(e,t)=>{var n=this.handedness,r=n.push;const s=[];for(const t of e){e=da(t);const n=[];for(const t of e.g())n.push({score:Sn(t,2)??0,index:kn(In(t,1),0)??-1,categoryName:Nn(t,3)??"",displayName:Nn(t,4)??""});s.push(n)}r.call(n,...s),Qi(this,t)}),this.g.attachEmptyPacketListener("handedness",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Su.prototype.detectForVideo=Su.prototype.F,Su.prototype.detect=Su.prototype.D,Su.prototype.setOptions=Su.prototype.o,Su.createFromModelPath=function(e,t){return Zo(Su,e,{baseOptions:{modelAssetPath:t}})},Su.createFromModelBuffer=function(e,t){return Zo(Su,e,{baseOptions:{modelAssetBuffer:t}})},Su.createFromOptions=function(e,t){return Zo(Su,e,t)},Su.HAND_CONNECTIONS=bu;var Nu=Ko([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function Tu(e){e.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function Eu(e){try{if(!e.C)return e.h;e.C(e.h)}finally{no(e)}}function Cu(e,t){e=wa(e),t.push(Fi(e))}var $u=class extends ru{constructor(e,t){super(new Jo(e,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,yn(e=this.j=new fi,0,1,t=new za),this.K=new ni,yn(this.j,0,2,this.K),this.aa=new hi,yn(this.j,0,3,this.aa),this.s=new Va,yn(this.j,0,4,this.s),this.I=new Ha,yn(this.j,0,5,this.I),this.v=new di,yn(this.j,0,6,this.v),this.L=new pi,yn(this.j,0,7,this.L),Cn(this.s,2,.5),Cn(this.s,3,.3),Cn(this.I,2,.5),Cn(this.v,2,.5),Cn(this.v,3,.3),Cn(this.L,2,.5),Cn(this.K,2,.5)}get baseOptions(){return fn(this.j,za,1)}set baseOptions(e){yn(this.j,0,1,e)}o(e){return"minFaceDetectionConfidence"in e&&Cn(this.s,2,e.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in e&&Cn(this.s,3,e.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in e&&Cn(this.I,2,e.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in e&&(this.outputFaceBlendshapes=!!e.outputFaceBlendshapes),"minPoseDetectionConfidence"in e&&Cn(this.v,2,e.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in e&&Cn(this.v,3,e.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in e&&Cn(this.L,2,e.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in e&&(this.outputPoseSegmentationMasks=!!e.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in e&&Cn(this.K,2,e.minHandLandmarksConfidence??.5),this.l(e)}D(e,t,n){const r="function"!=typeof t?t:{};return this.C="function"==typeof t?t:n,Tu(this),eu(this,e,r),Eu(this)}F(e,t,n,r){const s="function"!=typeof n?n:{};return this.C="function"==typeof n?n:r,Tu(this),tu(this,e,s,t),Eu(this)}m(){var e=new ia;sa(e,"input_frames_image"),aa(e,"pose_landmarks"),aa(e,"pose_world_landmarks"),aa(e,"face_landmarks"),aa(e,"left_hand_landmarks"),aa(e,"left_hand_world_landmarks"),aa(e,"right_hand_landmarks"),aa(e,"right_hand_world_landmarks");const t=new qs,n=new Fs;on(n,1,nt("type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),""),function(e,t){if(null!=t)if(Array.isArray(t))Xt(e,2,zt(t,Bt,void 0,void 0,!1));else{if(!("string"==typeof t||t instanceof z||_(t)))throw Error("invalid value in Any.value field: "+t+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");on(e,2,he(t,!1,!1),O())}}(n,this.j.g());const r=new Qs;Ys(r,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),vn(r,8,Fs,n),Js(r,"IMAGE:input_frames_image"),Zs(r,"POSE_LANDMARKS:pose_landmarks"),Zs(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Zs(r,"FACE_LANDMARKS:face_landmarks"),Zs(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Zs(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Zs(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Zs(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),ra(e,r),eo(this,e),this.g.attachProtoListener("pose_landmarks",(e,t)=>{Cu(e,this.h.poseLandmarks),Qi(this,t)}),this.g.attachEmptyPacketListener("pose_landmarks",e=>{Qi(this,e)}),this.g.attachProtoListener("pose_world_landmarks",(e,t)=>{var n=this.h.poseWorldLandmarks;e=ba(e),n.push(Di(e)),Qi(this,t)}),this.g.attachEmptyPacketListener("pose_world_landmarks",e=>{Qi(this,e)}),this.outputPoseSegmentationMasks&&(Zs(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),to(this,"pose_segmentation_mask"),this.g.V("pose_segmentation_mask",(e,t)=>{this.h.poseSegmentationMasks=[nu(this,e,!0,!this.C)],Qi(this,t)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",e=>{this.h.poseSegmentationMasks=[],Qi(this,e)})),this.g.attachProtoListener("face_landmarks",(e,t)=>{Cu(e,this.h.faceLandmarks),Qi(this,t)}),this.g.attachEmptyPacketListener("face_landmarks",e=>{Qi(this,e)}
5057),this.outputFaceBlendshapes&&(aa(e,"extra_blendshapes"),Zs(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(e,t)=>{var n=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(e=da(e),n.push(_i(e.g()??[]))),Qi(this,t)}),this.g.attachEmptyPacketListener("extra_blendshapes",e=>{Qi(this,e)})),this.g.attachProtoListener("left_hand_landmarks",(e,t)=>{Cu(e,this.h.leftHandLandmarks),Qi(this,t)}),this.g.attachEmptyPacketListener("left_hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoListener("left_hand_world_landmarks",(e,t)=>{var n=this.h.leftHandWorldLandmarks;e=ba(e),n.push(Di(e)),Qi(this,t)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",e=>{Qi(this,e)}),this.g.attachProtoListener("right_hand_landmarks",(e,t)=>{Cu(e,this.h.rightHandLandmarks),Qi(this,t)}),this.g.attachEmptyPacketListener("right_hand_landmarks",e=>{Qi(this,e)}),this.g.attachProtoListener("right_hand_world_landmarks",(e,t)=>{var n=this.h.rightHandWorldLandmarks;e=ba(e),n.push(Di(e)),Qi(this,t)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};$u.prototype.detectForVideo=$u.prototype.F,$u.prototype.detect=$u.prototype.D,$u.prototype.setOptions=$u.prototype.o,$u.createFromModelPath=function(e,t){return Zo($u,e,{baseOptions:{modelAssetPath:t}})},$u.createFromModelBuffer=function(e,t){return Zo($u,e,{baseOptions:{modelAssetBuffer:t}})},$u.createFromOptions=function(e,t){return Zo($u,e,t)},$u.HAND_CONNECTIONS=bu,$u.POSE_CONNECTIONS=Nu,$u.FACE_LANDMARKS_LIPS=au,$u.FACE_LANDMARKS_LEFT_EYE=iu,$u.FACE_LANDMARKS_LEFT_EYEBROW=ou,$u.FACE_LANDMARKS_LEFT_IRIS=uu,$u.FACE_LANDMARKS_RIGHT_EYE=lu,$u.FACE_LANDMARKS_RIGHT_EYEBROW=cu,$u.FACE_LANDMARKS_RIGHT_IRIS=hu,$u.FACE_LANDMARKS_FACE_OVAL=du,$u.FACE_LANDMARKS_CONTOURS=pu,$u.FACE_LANDMARKS_TESSELATION=fu;var Au=class extends ru{constructor(e,t){super(new Jo(e,t),"input_image","norm_rect",!0),this.j={classifications:[]},yn(e=this.h=new yi,0,1,t=new za)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return yn(this.h,0,2,Ri(e,fn(this.h,Ra,2))),this.l(e)}ua(e,t){return this.j={classifications:[]},eu(this,e,t),this.j}va(e,t,n){return this.j={classifications:[]},tu(this,e,n,t),this.j}m(){var e=new ia;sa(e,"input_image"),sa(e,"norm_rect"),aa(e,"classifications");const t=new qs;tr(t,bi,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Js(n,"IMAGE:input_image"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"CLASSIFICATIONS:classifications"),n.o(t),ra(e,n),this.g.attachProtoListener("classifications",(e,t)=>{this.j=function(e){const t={classifications:gn(e,Sa,1).map(e=>_i(fn(e,ca,4)?.g()??[],kn(In(e,2),0),Nn(e,3)))};return null!=et(jt(e,2))&&(t.timestampMs=kn(et(jt(e,2)),0)),t}(Na(e)),Qi(this,t)}),this.g.attachEmptyPacketListener("classifications",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Au.prototype.classifyForVideo=Au.prototype.va,Au.prototype.classify=Au.prototype.ua,Au.prototype.setOptions=Au.prototype.o,Au.createFromModelPath=function(e,t){return Zo(Au,e,{baseOptions:{modelAssetPath:t}})},Au.createFromModelBuffer=function(e,t){return Zo(Au,e,{baseOptions:{modelAssetBuffer:t}})},Au.createFromOptions=function(e,t){return Zo(Au,e,t)};var Ru=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!0),this.h=new xi,this.embeddings={embeddings:[]},yn(e=this.h,0,1,t=new za)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){var t=this.h,n=fn(this.h,Ma,2);return n=n?n.clone():new Ma,void 0!==e.l2Normalize?Tn(n,1,e.l2Normalize):"l2Normalize"in e&&Xt(n,1),void 0!==e.quantize?Tn(n,2,e.quantize):"quantize"in e&&Xt(n,2),yn(t,0,2,n),this.l(e)}Ba(e,t){return eu(this,e,t),this.embeddings}Ca(e,t,n){return tu(this,e,n,t),this.embeddings}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"embeddings_out");const t=new qs;tr(t,wi,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"EMBEDDINGS:embeddings_out"),n.o(t),ra(e,n),this.g.attachProtoListener("embeddings_out",(e,t)=>{e=Aa(e),this.embeddings=function(e){return{embeddings:gn(e,Ca,1).map(e=>{const t={headIndex:kn(In(e,3),0)??-1,headName:Nn(e,4)??""};
5057if(void 0!==pn(e,Ta,un(e,1)))e=tn(e=fn(e,Ta,un(e,1)),1,He,en()),t.floatEmbedding=e.slice();else{const n=new Uint8Array(0);t.quantizedEmbedding=fn(e,Ea,un(e,2))?.qa()?.h()??n}return t}),timestampMs:kn(et(jt(e,2)),0)}}(e),Qi(this,t)}),this.g.attachEmptyPacketListener("embeddings_out",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Ru.cosineSimilarity=function(e,t){if(e.floatEmbedding&&t.floatEmbedding)e=Li(e.floatEmbedding,t.floatEmbedding);else{if(!e.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");e=Li(Oi(e.quantizedEmbedding),Oi(t.quantizedEmbedding))}return e},Ru.prototype.embedForVideo=Ru.prototype.Ca,Ru.prototype.embed=Ru.prototype.Ba,Ru.prototype.setOptions=Ru.prototype.o,Ru.createFromModelPath=function(e,t){return Zo(Ru,e,{baseOptions:{modelAssetPath:t}})},Ru.createFromModelBuffer=function(e,t){return Zo(Ru,e,{baseOptions:{modelAssetBuffer:t}})},Ru.createFromOptions=function(e,t){return Zo(Ru,e,t)};var _u=class{constructor(e,t,n){this.confidenceMasks=e,this.categoryMask=t,this.qualityScores=n}close(){this.confidenceMasks?.forEach(e=>{e.close()}),this.categoryMask?.close()}};function Mu(e){e.categoryMask=void 0,e.confidenceMasks=void 0,e.qualityScores=void 0}function Fu(e){try{const t=new _u(e.confidenceMasks,e.categoryMask,e.qualityScores);if(!e.j)return t;e.j(t)}finally{no(e)}}_u.prototype.close=_u.prototype.close;var Du=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!1),this.s=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Ni,this.v=new vi,yn(this.h,0,3,this.v),yn(e=this.h,0,1,t=new za)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return void 0!==e.displayNamesLocale?Xt(this.h,2,nt(e.displayNamesLocale)):"displayNamesLocale"in e&&Xt(this.h,2),"outputCategoryMask"in e&&(this.outputCategoryMask=e.outputCategoryMask??!1),"outputConfidenceMasks"in e&&(this.outputConfidenceMasks=e.outputConfidenceMasks??!0),super.l(e)}J(){!function(e){const t=gn(e.ea(),Qs,1).filter(e=>Nn(e,1).includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(e.s=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");1===t.length&&(fn(t[0],qs,7)?.l()?.g()??new Map).forEach((t,n)=>{e.s[Number(n)]=Nn(t,1)})}(this)}fa(e,t,n){const r="function"!=typeof t?t:{};return this.j="function"==typeof t?t:n,Mu(this),eu(this,e,r),Fu(this)}Na(e,t,n,r){const s="function"!=typeof n?n:{};return this.j="function"==typeof n?n:r,Mu(this),tu(this,e,s,t),Fu(this)}Fa(){return this.s}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect");const t=new qs;tr(t,Ti,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),n.o(t),ra(e,n),eo(this,e),this.outputConfidenceMasks&&(aa(e,"confidence_masks"),Zs(n,"CONFIDENCE_MASKS:confidence_masks"),to(this,"confidence_masks"),this.g.da("confidence_masks",(e,t)=>{this.confidenceMasks=e.map(e=>nu(this,e,!0,!this.j)),Qi(this,t)}),this.g.attachEmptyPacketListener("confidence_masks",e=>{this.confidenceMasks=[],Qi(this,e)})),this.outputCategoryMask&&(aa(e,"category_mask"),Zs(n,"CATEGORY_MASK:category_mask"),to(this,"category_mask"),this.g.V("category_mask",(e,t)=>{this.categoryMask=nu(this,e,!1,!this.j),Qi(this,t)}),this.g.attachEmptyPacketListener("category_mask",e=>{this.categoryMask=void 0,Qi(this,e)})),aa(e,"quality_scores"),Zs(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(e,t)=>{this.qualityScores=e,Qi(this,t)}),this.g.attachEmptyPacketListener("quality_scores",e=>{this.categoryMask=void 0,Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Du.prototype.getLabels=Du.prototype.Fa,Du.prototype.segmentForVideo=Du.prototype.Na,Du.prototype.segment=Du.prototype.fa,Du.prototype.setOptions=Du.prototype.o,Du.createFromModelPath=function(e,t){return Zo(Du,e,{baseOptions:{modelAssetPath:t}})},Du.createFromModelBuffer=function(e,t){return Zo(Du,e,{baseOptions:{modelAssetBuffer:t}})},Du.createFromOptions=function(e,t){return Zo(Du,e,t)};var Ou=class{constructor(e,t,n){this.confidenceMasks=e,this.categoryMask=t,this.qual
5057ityScores=n}close(){this.confidenceMasks?.forEach(e=>{e.close()}),this.categoryMask?.close()}};Ou.prototype.close=Ou.prototype.close;var Lu=class extends nr{constructor(e){super(e)}},zu=[0,ys,-2],Pu=[0,cs,-3,ws,cs,-1],Bu=[0,Pu],Vu=[0,Pu,ys,-1],Uu=class extends nr{constructor(e){super(e)}},Wu=[0,cs,-1,ws],Gu=class extends nr{constructor(){super()}},Hu=class extends nr{constructor(e){super(e)}},ju=[1,2,3,4,5,6,7,8,9,10,14,15],qu=class extends nr{constructor(){super()}};qu.prototype.g=Ms([0,Ns,[0,ju,Ts,Pu,Ts,[0,Pu,zu],Ts,Bu,Ts,[0,Bu,zu],Ts,Wu,Ts,[0,cs,-3,ws,$s],Ts,[0,cs,-3,ws],Ts,[0,Ss,cs,-2,ws,ys,ws,-1,2,cs,zu],Ts,Vu,Ts,[0,Vu,zu],cs,zu,Ss,Ts,[0,cs,-3,ws,zu,-1],Ts,[0,Ns,Wu]],Ss,[0,Ss,ys,-1,ws]]);var Ku=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Ni,this.s=new vi,yn(this.h,0,3,this.s),yn(e=this.h,0,1,t=new za)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return"outputCategoryMask"in e&&(this.outputCategoryMask=e.outputCategoryMask??!1),"outputConfidenceMasks"in e&&(this.outputConfidenceMasks=e.outputConfidenceMasks??!0),super.l(e)}fa(e,t,n,r){const s="function"!=typeof n?n:{};this.j="function"==typeof n?n:r,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.B+1,r=new qu;const a=new Hu;var i=new Lu;if(En(i,1,255),yn(a,0,12,i),t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var o=new Uu;
vendor: 9,060 bytes, line 5057
5057Tn(o,3,!0),Cn(o,1,t.keypoint.x),Cn(o,2,t.keypoint.y),bn(a,5,ju,o)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");for(o of(i=new Gu,t.scribble))Tn(t=new Uu,3,!0),Cn(t,1,o.x),Cn(t,2,o.y),vn(i,1,Uu,t);bn(a,15,ju,i)}vn(r,1,Hu,a),this.g.addProtoToStream(r.g(),"drishti.RenderData","roi_in",n),eu(this,e,s);e:{try{const e=new Ou(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var u=e;break e}this.j(e)}finally{no(this)}u=void 0}return u}m(){var e=new ia;sa(e,"image_in"),sa(e,"roi_in"),sa(e,"norm_rect_in");const t=new qs;tr(t,Ti,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraph"),Js(n,"IMAGE:image_in"),Js(n,"ROI:roi_in"),Js(n,"NORM_RECT:norm_rect_in"),n.o(t),ra(e,n),eo(this,e),this.outputConfidenceMasks&&(aa(e,"confidence_masks"),Zs(n,"CONFIDENCE_MASKS:confidence_masks"),to(this,"confidence_masks"),this.g.da("confidence_masks",(e,t)=>{this.confidenceMasks=e.map(e=>nu(this,e,!0,!this.j)),Qi(this,t)}),this.g.attachEmptyPacketListener("confidence_masks",e=>{this.confidenceMasks=[],Qi(this,e)})),this.outputCategoryMask&&(aa(e,"category_mask"),Zs(n,"CATEGORY_MASK:category_mask"),to(this,"category_mask"),this.g.V("category_mask",(e,t)=>{this.categoryMask=nu(this,e,!1,!this.j),Qi(this,t)}),this.g.attachEmptyPacketListener("category_mask",e=>{this.categoryMask=void 0,Qi(this,e)})),aa(e,"quality_scores"),Zs(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(e,t)=>{this.qualityScores=e,Qi(this,t)}),this.g.attachEmptyPacketListener("quality_scores",e=>{this.categoryMask=void 0,Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Ku.prototype.segment=Ku.prototype.fa,Ku.prototype.setOptions=Ku.prototype.o,Ku.createFromModelPath=function(e,t){return Zo(Ku,e,{baseOptions:{modelAssetPath:t}})},Ku.createFromModelBuffer=function(e,t){return Zo(Ku,e,{baseOptions:{modelAssetBuffer:t}})},Ku.createFromOptions=function(e,t){return Zo(Ku,e,t)};var Xu=class extends ru{constructor(e,t){super(new Jo(e,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},yn(e=this.h=new Ei,0,1,t=new za)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return void 0!==e.displayNamesLocale?Xt(this.h,2,nt(e.displayNamesLocale)):"displayNamesLocale"in e&&Xt(this.h,2),void 0!==e.maxResults?En(this.h,3,e.maxResults):"maxResults"in e&&Xt(this.h,3),void 0!==e.scoreThreshold?Cn(this.h,4,e.scoreThreshold):"scoreThreshold"in e&&Xt(this.h,4),void 0!==e.categoryAllowlist?$n(this.h,5,e.categoryAllowlist):"categoryAllowlist"in e&&Xt(this.h,5),void 0!==e.categoryDenylist?$n(this.h,6,e.categoryDenylist):"categoryDenylist"in e&&Xt(this.h,6),this.l(e)}D(e,t){return this.j={detections:[]},eu(this,e,t),this.j}F(e,t,n){return this.j={detections:[]},tu(this,e,n,t),this.j}m(){var e=new ia;sa(e,"input_frame_gpu"),sa(e,"norm_rect"),aa(e,"detections");const t=new qs;tr(t,Ci,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.ObjectDetectorGraph"),Js(n,"IMAGE:input_frame_gpu"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"DETECTIONS:detections"),n.o(t),ra(e,n),this.g.attachProtoVectorListener("detections",(e,t)=>{for(const t of e)e=ga(t),this.j.detections.push(Mi(e));Qi(this,t)}),this.g.attachEmptyPacketListener("detections",e=>{Qi(this,e)}),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Xu.prototype.detectForVideo=Xu.prototype.F,Xu.prototype.detect=Xu.prototype.D,Xu.prototype.setOptions=Xu.prototype.o,Xu.createFromModelPath=async function(e,t){return Zo(Xu,e,{baseOptions:{modelAssetPath:t}})},Xu.createFromModelBuffer=function(e,t){return Zo(Xu,e,{baseOptions:{modelAssetBuffer:t}})},Xu.createFromOptions=function(e,t){return Zo(Xu,e,t)};var Yu=class{constructor(e,t,n){this.landmarks=e,this.worldLandmarks=t,this.segmentationMasks=n}close(){this.segmentationMasks?.forEach(e=>{e.close()})}};function Ju(e){e.landmarks=[],e.worldLandmarks=[],e.segmentationMasks=void 0}function Zu(e){try{const t=new Yu(e.landmarks,e.worldLandmarks,e.segmentationMasks);if(!e.s)return t;e.s(t)}finally{no(e)}}Yu.prototype.close=Yu.prototype.close;var Qu=class extends ru{constructor(e,t){super(new Jo(e,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,yn(e=this.h=new $i,0,1,t=new za),this.v=new pi,yn(this.h,0,3,this.v),this.j=new di,yn(this.h,0,2,this.j),En(this.j,4,1),Cn(this.j,2,.5),Cn(this.v,2,.5),Cn(this.h,4,.5)}get baseOptions(){return fn(this.h,za,1)}set baseOptions(e){yn(this.h,0,1,e)}o(e){return"numPoses"in e&&En(this.j,4,e.numPoses??1),"minPoseDetectionConfidence"in e&&Cn(this.j,2,e.minPoseDetectionConfidence??.5),"minTrackingConfidence"in e&&Cn(this.h,4,e.minTrackingConfidence??.5),"minPosePresenceConfidence"in e&&Cn(this.v,2,e.minPosePresenceConfidence??.5),"outputSegmentationMasks"in e&&(this.outputSegmentationMasks=e.outputSegmentationMasks??!1),this.l(e)}D(e,t,n){const r="function"!=typeof t?t:{};return this.s="function"==typeof t?t:n,Ju(this),eu(this,e,r),Zu(this)}F(e,t,n,r){const s="function"!=typeof n?n:{};return this.s="function"==typeof n?n:r,Ju(this),tu(this,e,s,t),Zu(this)}m(){var e=new ia;sa(e,"image_in"),sa(e,"norm_rect"),aa(e,"normalized_landmarks"),aa(e,"world_landmarks"),aa(e,"segmentation_masks");const t=new qs;tr(t,Ai,this.h);const n=new Qs;Ys(n,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Js(n,"IMAGE:image_in"),Js(n,"NORM_RECT:norm_rect"),Zs(n,"NORM_LANDMARKS:normalized_landmarks"),Zs(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),ra(e,n),eo(this,e),this.g.attachProtoVectorListener("normalized_landmarks",(e,t)=>{this.landmarks=[];for(const t of e)e=wa(t),this.landmarks.push(Fi(e));Qi(this,t)}),this.g.attachEmptyPacketListener("normalized_landmarks",e=>{this.landmarks=[],Qi(this,e)}),this.g.attachProtoVectorListener("world_landmarks",(e,t)=>{this.worldLandmarks=[];for(const t of e)e=ba(t),this.worldLandmarks.push(Di(e));Qi(this,t)}),this.g.attachEmptyPacketListener("world_landmarks",e=>{this.worldLandmarks=[],Qi(this,e)}),this.outputSegmentationMasks&&(Zs(n,"SEGMENTATION_MASK:segmentation_masks"),to(this,"segmentation_masks"),this.g.da("segmentation_masks",(e,t)=>{this.segmentationMasks=e.map(e=>nu(this,e,!0,!this.s)),Qi(this,t)}),this.g.attachEmptyPacketListener("segmentation_masks",e=>{this.segmentationMasks=[],Qi(this,e)})),e=e.g(),this.setGraph(new Uint8Array(e),!0)}};Qu.prototype.detectForVideo=Qu.prototype.F,Qu.prototype.detect=Qu.prototype.D,Qu.prototype.setOptions=Qu.prototype.o,Qu.createFromModelPath=function(e,t){return Zo(Qu,e,{baseOptions:{modelAssetPath:t}})},Qu.createFromModelBuffer=function(e,t){return Zo(Qu,e,{baseOptions:{modelAssetBuffer:t}})},Qu.createFromOptions=function(e,t){return Zo(Qu,e,t)},Qu.POSE_CONNECTIONS=Nu,t.DrawingUtils=Lo,t.FaceDetector=su,t.FaceLandmarker=gu,t.FaceStylizer=yu,t.FilesetResolver=Ui,t.GestureRecognizer=ku,t.HandLandmarker=Su,t.HolisticLandmarker=$u,t.ImageClassifier=Au,t.ImageEmbedder=Ru,t.ImageSegmenter=Du,t.ImageSegmenterResult=_u,t.InteractiveSegmenter=Ku,t.InteractiveSegmenterResult=Ou,t.MPImage=jo,t.MPMask=To,t.ObjectDetector=Xu,t.PoseLandmarker=Qu,t.VisionTaskRunner=ru},951:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Abs:()=>et,Acos:()=>tt,Acosh:()=>nt,AdadeltaOptimizer:()=>Ko,AdagradOptimizer:()=>Yo,AdamOptimizer:()=>Qo,AdamaxOptimizer:()=>au,Add:()=>rt,AddN:()=>st,All:()=>at,Any:()=>it,ArgMax:()=>ot,ArgMin:()=>ut,Asin:()=>lt,Asinh:()=>ct,Atan:()=>ht,Atan2:()=>pt,Atanh:()=>dt,AvgPool:()=>ft,AvgPool3D:()=>gt,AvgPool3DGrad:()=>yt,AvgPoolGrad:()=>mt,BatchMatMul:()=>bt,BatchToSpaceND:()=>xt,Bincount:()=>wt,BitwiseAnd:()=>vt,BroadcastArgs:()=>It,BroadcastTo:()=>kt,Callback:()=>iN,CallbackList:()=>Kx,Cast:()=>St,Ceil:()=>Nt,ClipByValue:()=>Tt,Complex:()=>Et,ComplexAbs:()=>Ct,Concat:()=>$t,Conv2D:()=>At,Conv2DBackpropFilter:()=>Rt,Conv2DBackpropInput:()=>_t,Conv3D:()=>Mt,Conv3DBackpropFilterV2:()=>Ft,Conv3DBackpropInputV2:()=>Dt,Cos:()=>Ot,Cosh:()=>Lt,CropAndResize:()=>Bt,Cumprod:()=>zt,Cumsum:()=>Pt,CustomCallback:()=>Jx,DataStorage:()=>X,DenseBincount:()=>Vt,DepthToSpace:()=>Ut,DepthwiseConv2dNative:()=>Wt,DepthwiseConv2dNativeBackpropFilter:()=>Gt,DepthwiseConv2dNativeBackpropInput:()=>Ht,Diag:()=>jt,Dilation2D:()=>qt,Dilation2DBackpropFilter:()=>Xt,Dilation2DBackpropInput:()=>Kt,Draw:()=>Yt,ENV:()=>Je,EarlyStopping:()=>lN,Einsum:()=>Zt,Elu:()=>Qt,EluGrad:()=>en,Environment:()=>qe,Equal:()=>nn,Erf:()=>tn,Exp:()=>rn,ExpandDims:()=>sn,Expm1:()=>an,FFT:()=>on,Fill:()=>un,FlipLeftRight:()=>ln,Floor:()=>cn,FloorDiv:()=>hn,FromPixels:()=>fs,FusedBatchNorm:()=>dn,FusedConv2D:()=>ys,FusedDepthwiseConv2D:()=>bs,GPGPUContext:()=>TO,GatherNd:()=>fn,GatherV2:()=>pn,GraphModel:()=>$T,Greater:()=>mn,GreaterEqual:()=>gn,History:()=>Yx,IFFT:()=>bn,Identity:()=>yn,Imag:()=>xn,InputSpec:()=>Qb,IsFinite:()=>wn,IsInf:()=>vn,IsNan:()=>kn,KernelBackend:()=>Y,LRN:()=>Dn,LRNGrad:()=>On,LayerVariable:()=>Yb,LayersModel:()=>Xw,LeakyRelu:()=>In,Less:()=>Sn,LessEqual:()=>Nn,LinSpace:()=>Tn,Log:()=>En,Log1p:()=>Cn,LogSoftmax:()=>Mn,LogicalAnd:()=>$n,LogicalNot:()=>An,LogicalOr:()=>Rn,LogicalXor:()=>_n,LowerBound:()=>
5057Fn,MathBackendCPU:()=>UE,MathBackendWebGL:()=>VL,MatrixBandPart:()=>Ln,Max:()=>zn,MaxPool:()=>Bn,MaxPool3D:()=>Un,MaxPool3DGrad:()=>Wn,MaxPoolGrad:()=>Vn,MaxPoolWithArgmax:()=>Gn,Maximum:()=>Pn,Mean:()=>Hn,Min:()=>jn,Minimum:()=>qn,MirrorPad:()=>Kn,Mod:()=>Xn,MomentumOptimizer:()=>ou,Multinomial:()=>Yn,Multiply:()=>Jn,Neg:()=>Zn,NonMaxSuppressionV3:()=>er,NonMaxSuppressionV4:()=>tr,NonMaxSuppressionV5:()=>nr,NotEqual:()=>Qn,OP_SCOPE_SUFFIX:()=>qa,OneHot:()=>sr,OnesLike:()=>rr,Optimizer:()=>qo,OptimizerConstructors:()=>Al,Pack:()=>ar,PadV2:()=>ir,Pool:()=>or,Pow:()=>ur,Prelu:()=>lr,Prod:()=>cr,RMSPropOptimizer:()=>uu,RNN:()=>rk,RaggedGather:()=>hr,RaggedRange:()=>dr,RaggedTensorToTensor:()=>pr,Range:()=>fr,Rank:()=>ga,Real:()=>mr,RealDiv:()=>Jt,Reciprocal:()=>gr,Reduction:()=>mf,Relu:()=>yr,Relu6:()=>Ir,Reshape:()=>br,ResizeBilinear:()=>vr,ResizeBilinearGrad:()=>kr,ResizeNearestNeighbor:()=>xr,ResizeNearestNeighborGrad:()=>wr,Reverse:()=>Sr,RotateWithOffset:()=>ms,Round:()=>Nr,Rsqrt:()=>Tr,SGDOptimizer:()=>iu,ScatterNd:()=>Er,SearchSorted:()=>$r,Select:()=>Ar,Selu:()=>Rr,Sequential:()=>Qw,Sigmoid:()=>Or,Sign:()=>Dr,Sin:()=>Mr,Sinh:()=>Fr,Slice:()=>_r,Softmax:()=>Ur,Softplus:()=>Lr,SpaceToBatchND:()=>Br,SparseFillEmptyRows:()=>Wr,SparseReshape:()=>Gr,SparseSegmentMean:()=>Hr,SparseSegmentSum:()=>jr,SparseToDense:()=>qr,SplitV:()=>Vr,Sqrt:()=>zr,Square:()=>Xr,SquaredDifference:()=>Kr,StaticRegexReplace:()=>Yr,Step:()=>ps,StridedSlice:()=>Jr,StringNGrams:()=>Zr,StringSplit:()=>Qr,StringToHashBucketFast:()=>es,Sub:()=>ts,Sum:()=>Pr,SymbolicTensor:()=>ex,Tan:()=>ns,Tanh:()=>rs,Tensor:()=>pa,TensorBuffer:()=>la,TensorScatterUpdate:()=>Cr,Tile:()=>ss,TopK:()=>as,Transform:()=>is,Transpose:()=>os,Unique:()=>us,Unpack:()=>ls,UnsortedSegmentSum:()=>cs,UpperBound:()=>hs,Variable:()=>ma,ZerosLike:()=>ds,_FusedMatMul:()=>gs,abs:()=>eu,acos:()=>Rl,acosh:()=>_l,add:()=>To,addN:()=>Ml,all:()=>Fl,any:()=>Dl,argMax:()=>Ol,argMin:()=>Ll,asin:()=>zl,asinh:()=>Pl,atan:()=>Bl,atan2:()=>Vl,atanh:()=>Ul,avgPool:()=>ac,avgPool3d:()=>ic,backend:()=>xi,backend_util:()=>y,basicLSTMCell:()=>hc,batchNorm:()=>pc,batchNorm2d:()=>fc,batchNorm3d:()=>mc,batchNorm4d:()=>gc,batchToSpaceND:()=>dc,bincount:()=>yc,bitwiseAnd:()=>bc,booleanMaskAsync:()=>xp,broadcastArgs:()=>xc,broadcastTo:()=>wc,broadcast_util:()=>o,browser:()=>c,buffer:()=>ko,callbacks:()=>cN,cast:()=>Io,ceil:()=>vc,clipByValue:()=>kc,clone:()=>So,complex:()=>Xa,concat:()=>oc,concat1d:()=>Ic,concat2d:()=>Sc,concat3d:()=>Nc,concat4d:()=>Tc,constraints:()=>x,conv1d:()=>Cc,conv2d:()=>Ec,conv2dTranspose:()=>Ac,conv3d:()=>Rc,conv3dTranspose:()=>Mc,copyRegisteredKernels:()=>As,cos:()=>Fc,cosh:()=>Dc,cosineWindow:()=>Tp,cumprod:()=>Oc,cumsum:()=>Lc,customGrad:()=>zo,data:()=>H,denseBincount:()=>zc,deprecationWarn:()=>ri,depthToSpace:()=>Pc,depthwiseConv2d:()=>Bc,deregisterOp:()=>gN,device_util:()=>a,diag:()=>Vc,dilation2d:()=>Uc,disableDeprecationWarnings:()=>ni,dispose:()=>li,disposeVariables:()=>si,div:()=>
5057Co,divNoNan:()=>Hc,dot:()=>jc,dropout:()=>Sp,einsum:()=>qc,elu:()=>Kc,enableDebugMode:()=>ti,enableProdMode:()=>ei,enclosingPowerOfTwo:()=>Np,engine:()=>ai,ensureShape:()=>Xc,env:()=>Xe,equal:()=>Wc,erf:()=>Yc,euclideanNorm:()=>ch,exp:()=>hh,expandDims:()=>dh,expm1:()=>ph,eye:()=>mh,fft:()=>qd,fill:()=>Xo,findBackend:()=>gi,findBackendFactory:()=>yi,floor:()=>gh,floorDiv:()=>Eo,forceHalfFloat:()=>WL,fused:()=>m,gather:()=>yh,gatherND:()=>Ip,gather_util:()=>h,getBackend:()=>fi,getGradient:()=>Ss,getKernel:()=>Is,getKernelsForBackend:()=>Ns,gpgpu_util:()=>K,grad:()=>Mo,grads:()=>Fo,greater:()=>bh,greaterEqual:()=>xh,ifft:()=>Kd,imag:()=>_u,image:()=>Df,inTopKAsync:()=>Ep,initializers:()=>w,input:()=>nv,io:()=>u,irfft:()=>Xd,isFinite:()=>wh,isInf:()=>vh,isNaN:()=>kh,keep:()=>ci,kernel_impls:()=>b,layers:()=>v,leakyRelu:()=>Ih,less:()=>Sh,lessEqual:()=>Nh,linalg:()=>Of,linspace:()=>Th,loadGraphModel:()=>AT,loadGraphModelSync:()=>RT,loadLayersModel:()=>Zw,localResponseNormalization:()=>Eh,log:()=>Ch,log1p:()=>$h,logSigmoid:()=>Rh,logSoftmax:()=>_h,logSumExp:()=>Mh,logicalAnd:()=>Fh,logicalNot:()=>Dh,logicalOr:()=>Oh,logicalXor:()=>Lh,losses:()=>Lf,lowerBound:()=>Bh,matMul:()=>Au,math:()=>l,max:()=>ah,maxPool:()=>Vh,maxPool3d:()=>Uh,maxPoolWithArgmax:()=>Wh,maximum:()=>su,mean:()=>Gh,memory:()=>ii,meshgrid:()=>qh,metrics:()=>k,min:()=>ih,minimum:()=>Kh,mirrorPad:()=>Xh,mod:()=>Yh,model:()=>ev,models:()=>I,moments:()=>Jh,movingAverage:()=>wp,mul:()=>$o,multiRNNCell:()=>Zh,multinomial:()=>Qh,neg:()=>Mu,nextFrame:()=>Uf,norm:()=>lh,notEqual:()=>ed,oneHot:()=>Ru,ones:()=>jh,onesLike:()=>td,op:()=>Ka,outerProduct:()=>nd,pad:()=>rd,pad1d:()=>sd,pad2d:()=>ad,pad3d:()=>id,pad4d:()=>od,pool:()=>ld,pow:()=>Jo,prelu:()=>cd,print:()=>No,prod:()=>hd,profile:()=>oi,raggedGather:()=>dd,raggedRange:()=>pd,raggedTensorToTensor:()=>fd,rand:()=>md,randomGamma:()=>wd,randomNormal:()=>vd,randomStandardNormal:()=>kd,randomUniform:()=>Id,randomUniformInt:()=>Sd,range:()=>Nd,ready:()=>pi,real:()=>Fu,reciprocal:()=>Td,registerBackend:()=>bi,registerCallbackConstructor:()=>rv,registerGradient:()=>Es,registerKernel:()=>Ts,registerOp:()=>fN,regularizers:()=>S,relu:()=>Ed,relu6:()=>Cd,removeBackend:()=>mi,reshape:()=>sc,reverse:()=>$d,reverse1d:()=>Ad,reverse2d:()=>Rd,reverse3d:()=>_d,reverse4d:()=>Md,rfft:()=>Jd,round:()=>Fd,rsqrt:()=>Dd,scalar:()=>Bo,scatterND:()=>vp,scatter_util:()=>d,searchSorted:()=>Ph,selu:()=>Od,separableConv2d:()=>Ld,sequential:()=>tv,serialization:()=>i,setBackend:()=>di,setPlatform:()=>wi,setWebGLContext:()=>vF,setdiff1dAsync:()=>zd,shared:()=>j,sigmoid:()=>uc,sign:()=>Pd,signal:()=>Ff,sin:()=>Bd,sinh:()=>Vd,slice:()=>lc,slice1d:()=>Ud,slice2d:()=>Wd,slice3d:()=>Gd,slice4d:()=>Hd,slice_util:()=>p,softmax:()=>jd,softplus:()=>Ah,spaceToBatchND:()=>ud,sparse:()=>zf,sparseToDense:()=>kp,spectral:()=>Mf,split:()=>Yd,sqrt:()=>Ao,square:()=>Ro,squaredDifference:()=>Zd,squeeze:()=>Qd,stack:()=>ep,step:()=>tp,stridedSlice:()=>np,string:()=>Pf,sub:()=>Zo,sum:()=>oh,sumOutType:()=>Ia,tan:()=>rp,tanh:()=>cc,tensor:()=>Ja,tensor1d:()=>sp,tensor2d:()=>ap,tensor3d:()=>Lu,tensor4d:()=>ip,tensor5d:()=>op,tensor6d:()=>up,tensorScatterUpdate:()=>lp,tensor_util:()=>s,test_util:()=>f,tidy:()=>ui,tile:()=>fh,time:()=>hi,topk:()=>cp,train:()=>Bf,transpose:()=>Du,truncatedNormal:()=>hp,unique:()=>dp,unregisterGradient:()=>$s,unregisterKernel:()=>Cs,unsortedSegmentSum:()=>pp,unstack:()=>fp,upcastType:()=>ka,upperBound:()=>mp,util:()=>r,valueAndGrad:()=>Do,valueAndGrads:()=>Oo,variable:()=>gp,variableGrads:()=>Lo,version:()=>DG,version_converter:()=>_T,version_core:()=>$l,version_cpu:()=>pA,version_layers:()=>Rw,version_webgl:()=>UL,webgl:()=>GL,webgl_util:()=>q,where:()=>Gc,whereAsync:()=>bp,zeros:()=>Hh,zerosLike:()=>_o});var r={};n.r(r),n.d(r,{arraysEqual:()=>de,arraysEqualWithNull:()=>he,assert:()=>ie,assertNonNegativeIntegerDimensions:()=>Ue,assertNonNull:()=>ue,assertShapesMatch:()=>oe,bytesFromStringArray:()=>Ce,bytesPerElement:()=>Ee,checkConversionForErrors:()=>Se,clamp:()=>ee,computeStrides:()=>De,convertBackendValuesAndArrayBuffer:()=>ze,createScalarValue:()=>qs,createShuffledIndices:()=>ge,decodeString:()=>Zs,distSquared:()=>ae,encodeString:()=>Js,fetch:()=>Ys,fingerPrint64:()=>js,flatten:()=>ea,getArrayFromDType:()=>Ie,getTypedArrayFromDType:()=>ke,hasEncodingLoss:()=>Te,hexToLong:()=>Ds,indexToLoc:()=>Ge,inferDtype:()=>_e,inferFromImplicitShape:()=>xe,isBoolean:()=>Ae,isFunction:()=>Me,isInt:()=>pe,isNumber:()=>Re,isPromise:()=>He,isScalarShape:()=>ce,isString:()=>$e,isTypedArray:()=>Qs,isValidDtype:()=>Ne,locToIndex:()=>We,makeOnesTypedArray:()=>Pe,makeZerosNestedTypedArray:()=>Ve,makeZerosTypedArray:()=>Be,nearestDivisor:()=>Fe,nearestLargerEven:()=>te,now:()=>Xs,parseAxisParam:()=>we,randUniform:()=>se,repeatedTry:()=>be,rightPad:()=>ye,shuffle:()=>Z,shuffleCombo:()=>Q,sizeFromShape:()=>le,sizeToSquarishShape:()=>me,squeezeShape:()=>ve,sum:()=>re,swap:()=>
5057ne,tanh:()=>fe,toNestedArray:()=>Le,toTypedArray:()=>Ks});var s={};n.r(s),n.d(s,{assertTypesMatch:()=>Ea,getTensorsInContainer:()=>$a,isTensorInList:()=>Ca,makeTypesMatch:()=>Ta});var a={};n.r(a),n.d(a,{isBrowser:()=>Ba,isMobile:()=>Pa,mockIsMobile:()=>za});var i={};n.r(i),n.d(i,{Serializable:()=>Wo,SerializationMap:()=>Go,getRegisteredName:()=>jo,registerClass:()=>Ho});var o={};n.r(o),n.d(o,{assertAndGetBroadcastShape:()=>ru,getBroadcastDims:()=>tu,getReductionAxes:()=>nu});var u={};n.r(u),n.d(u,{CompositeArrayBuffer:()=>Qa,browserFiles:()=>pu,browserHTTPRequest:()=>ku,concatenateArrayBuffers:()=>_i,copyModel:()=>bo,decodeWeights:()=>Ii,decodeWeightsStream:()=>Ci,encodeWeights:()=>ki,fromMemory:()=>Tu,fromMemorySync:()=>Eu,getLoadHandlers:()=>Wi,getModelArtifactsForJSON:()=>Oi,getModelArtifactsForJSONSync:()=>Di,getModelArtifactsInfoForJSON:()=>Li,getSaveHandlers:()=>Ui,getWeightSpecs:()=>zi,http:()=>vu,isHTTPScheme:()=>xu,listModels:()=>go,loadWeights:()=>gu,moveModel:()=>xo,registerLoadRouter:()=>Vi,registerSaveRouter:()=>Bi,removeModel:()=>yo,weightsLoaderFactory:()=>yu,withSaveHandler:()=>Cu,withSaveHandlerSync:()=>$u});var l={};n.r(l),n.d(l,{confusionMatrix:()=>Ou});var c={};n.r(c),n.d(c,{draw:()=>Gu,fromPixels:()=>Hu,fromPixelsAsync:()=>Vu,toPixels:()=>Wu});var h={};n.r(h),n.d(h,{prepareAndValidate:()=>ju});var d={};n.r(d),n.d(d,{calculateShapes:()=>Xu,validateInput:()=>Ku,validateUpdateShape:()=>qu});var p={};n.r(p),n.d(p,{assertParamsValid:()=>Zu,computeFlatOffset:()=>hl,computeOutShape:()=>el,getNormalizedAxes:()=>sl,isSliceContinous:()=>cl,maskToAxes:()=>Qu,parseSliceParams:()=>dl,sliceInfo:()=>pl,startForAxis:()=>ul,startIndicesWithElidedDims:()=>al,stopForAxis:()=>ll,stopIndicesWithElidedDims:()=>il,stridesForAxis:()=>ol,stridesWithElidedDims:()=>tl});var f={};n.r(f),n.d(f,{TEST_EPSILON_FLOAT16:()=>gl,createVideoElement:()=>El,encodeStrings:()=>Tl,expectArrayBuffersEqual:()=>Nl,expectArraysClose:()=>yl,expectArraysEqual:()=>vl,expectNumbersClose:()=>kl,expectPromiseToFail:()=>wl,expectValuesInRange:()=>Sl,play:()=>Cl,testEpsilon:()=>bl});var m={};n.r(m),n.d(m,{conv2d:()=>Mp,depthwiseConv2d:()=>Op,matMul:()=>Lp});var g={};n.r(g),n.d(g,{collectGatherOpShapeInfo:()=>Hm,computeOutShape:()=>Gm,segOpComputeOptimalWindowSize:()=>Wm});var y={};n.r(y),n.d(y,{ERF_A1:()=>om,ERF_A2:()=>um,ERF_A3:()=>lm,ERF_A4:()=>cm,ERF_A5:()=>hm,ERF_P:()=>im,PARALLELIZE_THRESHOLD:()=>Yf,RowPartitionType:()=>Hf,SELU_SCALE:()=>am,SELU_SCALEALPHA:()=>sm,applyActivation:()=>Rp,assertAndGetBroadcastShape:()=>ru,assertAxesAreInnerMostDims:()=>th,assertParamsConsistent:()=>Wf,assignToTypedArray:()=>ym,axesAreInnerMostDims:()=>Jc,calculateShapes:()=>Xu,checkEinsumDimSizes:()=>Tm,checkPadOnDimRoundingMode:()=>rc,combineLocations:()=>Zc,combineRaggedTensorToTensorShapes:()=>jf,complexWithEvenIndex:()=>fm,complexWithOddIndex:()=>mm,computeConv2DInfo:()=>jl,computeConv3DInfo:()=>ql,computeDefaultPad:()=>Kl,computeDilation2DInfo:()=>Wl,computeOptimalWindowSize:()=>Jf,computeOutAndReduceShapes:()=>Qc,computeOutShape:()=>Gf,computePool2DInfo:()=>Gl,computePool3DInfo:()=>Hl,convertConv2DDataFormat:()=>nc,decodeEinsumEquation:()=>Sm,eitherStridesOrDilationsAreOne:()=>ec,expandShapeToKeepDim:()=>eh,exponent:()=>xm,exponents:()=>bm,fromStringArrayToUint8:()=>qm,fromUint8ToStringArray:()=>jm,getAxesPermutation:()=>nh,getBroadcastDims:()=>tu,getComplexWithIndex:()=>gm,getEinsumComputePath:()=>Em,getEinsumPermutation:()=>Nm,getFusedBiasGradient:()=>Ap,getFusedDyActivation:()=>$p,getImageCenter:()=>Zf,getInnerMostAxes:()=>sh,getPermuted:()=>em,getRaggedRank:()=>Kf,getReductionAxes:()=>nu,getReshaped:()=>Qf,getReshapedPermuted:()=>tm,getRowPartitionTypesHelper:()=>qf,getSliceBeginCoords:()=>nm,getSliceSize:()=>rm,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Rm,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>_m,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Mm,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Om,getSparseReshapeInputOutputMismatchErrorMessage:()=>zm,getSparseReshapeInputOutputMultipleErrorMessage:()=>Lm,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>Fm,getSparseReshapeNegativeOutputDimErrorMessage:()=>Dm,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>Um,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>Pm,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>Bm,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>Vm,getUndoAxesPermutation:()=>rh,isIdentityPermutation:()=>Cm,log:()=>ws,mergeRealAndImagArrays:()=>dm,prepareAndValidate:()=>ju,prepareSplitSize:()=>Am,segment_util:()=>g,shouldFuse:()=>_p,slice_util:()=>p,splitRealAndImagArrays:()=>pm,stridesOrDilationsArePositive:()=>tc,tupleValuesAreOne:()=>Ql,upcastType:()=>ka,validateDefaultValueShape:()=>Xf,validateInput:()=>Ku,validateUpdateShape:()=>qu,warn:()=>xs});var b={};n.r(b),n.d(b,{nonMaxSuppressionV3Impl:()=>Jp,nonMaxSuppressionV4Impl:()=>Zp,nonMaxSuppressionV5Impl:()=>Qp,whereImpl:()=>yp});var x={};n.r(x),n.d(x,{maxNorm:()=>Nx,minMaxNorm:()=>Cx,nonNeg:()=>Ex,unitNorm:()=>Tx});var w={};n.r(w),n.d(w,{constant:()=>Rx,glorotNormal:()=>zx,glorotUniform:()=>Lx,heNormal:()=>Px,heUniform:()=>Bx,identity:()=>Dx,leCunNormal:()=>Vx,leCunUniform:()=>Ux,ones:()=>Ax,orthogonal:()=>Wx,randomNormal:()=>Mx,randomUniform:()=>_x,truncatedNormal:()=>Fx,varianceScaling:()=>Ox,zeros:()=>$x});var v={};n.r(v),n.d(v,{Layer:()=>sx,RNN:()=>rk,RNNCell:()=>sk,activation:()=>DI,add:()=>
5057GI,alphaDropout:()=>FS,average:()=>HI,averagePooling1d:()=>eS,averagePooling2d:()=>rS,averagePooling3d:()=>iS,avgPool1d:()=>tS,avgPool2d:()=>sS,avgPool3d:()=>oS,avgPooling1d:()=>nS,avgPooling2d:()=>aS,avgPooling3d:()=>uS,batchNormalization:()=>JI,bidirectional:()=>TS,categoryEncoding:()=>PS,centerCrop:()=>LS,concatenate:()=>jI,conv1d:()=>TI,conv2d:()=>EI,conv2dTranspose:()=>CI,conv3d:()=>$I,conv3dTranspose:()=>AI,convLstm2d:()=>kS,convLstm2dCell:()=>IS,cropping2D:()=>_I,dense:()=>OI,depthwiseConv2d:()=>FI,dot:()=>YI,dropout:()=>LI,elu:()=>wI,embedding:()=>WI,flatten:()=>PI,gaussianDropout:()=>MS,gaussianNoise:()=>_S,globalAveragePooling1d:()=>lS,globalAveragePooling2d:()=>cS,globalMaxPool1d:()=>CS,globalMaxPool2d:()=>$S,globalMaxPooling1d:()=>hS,globalMaxPooling2d:()=>dS,gru:()=>gS,gruCell:()=>yS,input:()=>nv,inputLayer:()=>xI,layerNormalization:()=>ZI,leakyReLU:()=>kI,lstm:()=>bS,lstmCell:()=>xS,masking:()=>DS,maxPool1d:()=>AS,maxPool2d:()=>RS,maxPooling1d:()=>pS,maxPooling2d:()=>fS,maxPooling3d:()=>mS,maximum:()=>qI,minimum:()=>KI,multiply:()=>XI,permute:()=>UI,prelu:()=>II,randomWidth:()=>BS,reLU:()=>vI,repeatVector:()=>BI,rescaling:()=>OS,reshape:()=>VI,resizing:()=>zS,rnn:()=>SS,separableConv2d:()=>RI,simpleRNN:()=>wS,simpleRNNCell:()=>vS,softmax:()=>SI,spatialDropout1d:()=>zI,stackedRNNCells:()=>NS,thresholdedReLU:()=>NI,timeDistributed:()=>ES,upSampling2d:()=>MI,zeroPadding2d:()=>QI});var k={};n.r(k),n.d(k,{MAPE:()=>JS,MSE:()=>eN,binaryAccuracy:()=>VS,binaryCrossentropy:()=>US,categoricalAccuracy:()=>GS,categoricalCrossentropy:()=>HS,cosineProximity:()=>KS,mape:()=>ZS,meanAbsoluteError:()=>XS,meanAbsolutePercentageError:()=>YS,meanSquaredError:()=>QS,mse:()=>tN,precision:()=>jS,r2Score:()=>nN,recall:()=>qS,sparseCategoricalAccuracy:()=>WS});var I={};n.r(I),n.d(I,{modelFromJSON:()=>Jw});var S={};n.r(S),n.d(S,{l1:()=>sN,l1l2:()=>rN,l2:()=>aN});var N={};n.r(N),n.d(N,{json:()=>NN});var T={};n.r(T),n.d(T,{json:()=>TN});var E={};n.r(E),n.d(E,{json:()=>EN});var C={};n.r(C),n.d(C,{json:()=>CN});var $={};n.r($),n.d($,{json:()=>$N});var A={};n.r(A),n.d(A,{json:()=>AN});var R={};n.r(R),n.d(R,{json:()=>RN});var _={};n.r(_),n.d(_,{json:()=>_N});var M={};n.r(M),n.d(M,{json:()=>MN});var F={};n.r(F),n.d(F,{json:()=>FN});var D={};n.r(D),n.d(D,{json:()=>DN});var O={};n.r(O),n.d(O,{json:()=>ON});var L={};n.r(L),n.d(L,{json:()=>LN});var z={};n.r(z),n.d(z,{json:()=>zN});var P={};n.r(P),n.d(P,{json:()=>PN});var B={};n.r(B),n.d(B,{json:()=>BN});var V={};n.r(V),n.d(V,{json:()=>VN});var U={};n.r(U),n.d(U,{json:()=>UN});var W={};n.r(W),n.d(W,{json:()=>WN});var G={};n.r(G),n.d(G,{OP_SCOPE_SUFFIX:()=>qa,abs:()=>eu,acos:()=>Rl,acosh:()=>_l,add:()=>To,addN:()=>Ml,all:()=>Fl,any:()=>Dl,argMax:()=>Ol,argMin:()=>Ll,asin:()=>zl,asinh:()=>Pl,atan:()=>Bl,atan2:()=>Vl,atanh:()=>Ul,avgPool:()=>ac,avgPool3d:()=>ic,basicLSTMCell:()=>hc,batchNorm:()=>pc,batchNorm2d:()=>fc,batchNorm3d:()=>mc,batchNorm4d:()=>gc,batchToSpaceND:()=>dc,bincount:()=>yc,bitwiseAnd:()=>bc,booleanMaskAsync:()=>xp,broadcastArgs:()=>xc,broadcastTo:()=>wc,buffer:()=>ko,cast:()=>Io,ceil:()=>vc,clipByValue:()=>kc,clone:()=>So,complex:()=>Xa,concat:()=>oc,concat1d:()=>Ic,concat2d:()=>Sc,concat3d:()=>Nc,concat4d:()=>Tc,conv1d:()=>Cc,conv2d:()=>Ec,conv2dTranspose:()=>Ac,conv3d:()=>Rc,conv3dTranspose:()=>Mc,cos:()=>Fc,cosh:()=>Dc,cosineWindow:()=>Tp,cumprod:()=>Oc,cumsum:()=>Lc,denseBincount:()=>zc,depthToSpace:()=>Pc,depthwiseConv2d:()=>Bc,diag:()=>Vc,dilation2d:()=>Uc,div:()=>
5057Co,divNoNan:()=>Hc,dot:()=>jc,dropout:()=>Sp,einsum:()=>qc,elu:()=>Kc,enclosingPowerOfTwo:()=>Np,ensureShape:()=>Xc,equal:()=>Wc,erf:()=>Yc,euclideanNorm:()=>ch,exp:()=>hh,expandDims:()=>dh,expm1:()=>ph,eye:()=>mh,fft:()=>qd,fill:()=>Xo,floor:()=>gh,floorDiv:()=>Eo,fused:()=>m,gather:()=>yh,gatherND:()=>Ip,greater:()=>bh,greaterEqual:()=>xh,ifft:()=>Kd,imag:()=>_u,image:()=>Df,inTopKAsync:()=>Ep,irfft:()=>Xd,isFinite:()=>wh,isInf:()=>vh,isNaN:()=>kh,leakyRelu:()=>Ih,less:()=>Sh,lessEqual:()=>Nh,linalg:()=>Of,linspace:()=>Th,localResponseNormalization:()=>Eh,log:()=>Ch,log1p:()=>$h,logSigmoid:()=>Rh,logSoftmax:()=>_h,logSumExp:()=>Mh,logicalAnd:()=>Fh,logicalNot:()=>Dh,logicalOr:()=>Oh,logicalXor:()=>Lh,losses:()=>Lf,lowerBound:()=>Bh,matMul:()=>Au,max:()=>ah,maxPool:()=>Vh,maxPool3d:()=>Uh,maxPoolWithArgmax:()=>Wh,maximum:()=>su,mean:()=>Gh,meshgrid:()=>qh,min:()=>ih,minimum:()=>Kh,mirrorPad:()=>Xh,mod:()=>Yh,moments:()=>Jh,movingAverage:()=>wp,mul:()=>$o,multiRNNCell:()=>Zh,multinomial:()=>Qh,neg:()=>Mu,norm:()=>lh,notEqual:()=>ed,oneHot:()=>Ru,ones:()=>jh,onesLike:()=>td,op:()=>Ka,outerProduct:()=>nd,pad:()=>rd,pad1d:()=>sd,pad2d:()=>ad,pad3d:()=>id,pad4d:()=>od,pool:()=>ld,pow:()=>Jo,prelu:()=>cd,print:()=>No,prod:()=>hd,raggedGather:()=>dd,raggedRange:()=>pd,raggedTensorToTensor:()=>fd,rand:()=>md,randomGamma:()=>wd,randomNormal:()=>vd,randomStandardNormal:()=>kd,randomUniform:()=>Id,randomUniformInt:()=>Sd,range:()=>Nd,real:()=>Fu,reciprocal:()=>Td,relu:()=>Ed,relu6:()=>Cd,reshape:()=>sc,reverse:()=>$d,reverse1d:()=>Ad,reverse2d:()=>Rd,reverse3d:()=>_d,reverse4d:()=>Md,rfft:()=>Jd,round:()=>Fd,rsqrt:()=>Dd,scalar:()=>Bo,scatterND:()=>vp,searchSorted:()=>Ph,selu:()=>Od,separableConv2d:()=>Ld,setdiff1dAsync:()=>zd,sigmoid:()=>uc,sign:()=>Pd,signal:()=>Ff,sin:()=>Bd,sinh:()=>Vd,slice:()=>lc,slice1d:()=>Ud,slice2d:()=>Wd,slice3d:()=>Gd,slice4d:()=>Hd,softmax:()=>jd,softplus:()=>Ah,spaceToBatchND:()=>ud,sparse:()=>zf,sparseToDense:()=>kp,spectral:()=>Mf,split:()=>Yd,sqrt:()=>Ao,square:()=>Ro,squaredDifference:()=>Zd,squeeze:()=>Qd,stack:()=>ep,step:()=>tp,stridedSlice:()=>np,string:()=>Pf,sub:()=>Zo,sum:()=>oh,tan:()=>rp,tanh:()=>cc,tensor:()=>Ja,tensor1d:()=>sp,tensor2d:()=>ap,tensor3d:()=>Lu,tensor4d:()=>ip,tensor5d:()=>op,tensor6d:()=>up,tensorScatterUpdate:()=>lp,tile:()=>fh,topk:()=>cp,transpose:()=>Du,truncatedNormal:()=>hp,unique:()=>dp,unsortedSegmentSum:()=>pp,unstack:()=>fp,upperBound:()=>mp,variable:()=>gp,where:()=>Gc,whereAsync:()=>bp,zeros:()=>Hh,zerosLike:()=>_o});var H={};n.r(H),n.d(H,{CSVDataset:()=>wE,Dataset:()=>uE,FileDataSource:()=>_E,TextLineDataset:()=>pE,URLDataSource:()=>ME,array:()=>cE,csv:()=>FE,func:()=>DE,generator:()=>OE,microphone:()=>zE,version_data:()=>PE,webcam:()=>LE,zip:()=>hE});var j={};n.r(j),n.d(j,{addImpl:()=>sC,bincountImpl:()=>uC,bincountReduceImpl:()=>lC,bitwiseAndImpl:()=>cC,castImpl:()=>QE,ceilImpl:()=>gC,concatImpl:()=>xC,equalImpl:()=>wC,expImpl:()=>IC,expm1Impl:()=>TC,floorDivImpl:()=>_C,floorImpl:()=>$C,gatherNdImpl:()=>DC,gatherV2Impl:()=>OC,greaterEqualImpl:()=>BC,greaterImpl:()=>LC,lessEqualImpl:()=>jC,lessImpl:()=>WC,linSpaceImpl:()=>XC,logImpl:()=>YC,maxImpl:()=>QC,maximumImpl:()=>e$,minimumImpl:()=>r$,multiplyImpl:()=>i$,negImpl:()=>c$,notEqualImpl:()=>d$,prodImpl:()=>b$,raggedGatherImpl:()=>v$,raggedRangeImpl:()=>I$,raggedTensorToTensorImpl:()=>C$,rangeImpl:()=>$$,rsqrtImpl:()=>A$,scatterImpl:()=>M$,sigmoidImpl:()=>F$,simpleAbsImpl:()=>WE,sliceImpl:()=>L$,sparseFillEmptyRowsImpl:()=>B$,sparseReshapeImpl:()=>V$,sparseSegmentReductionImpl:()=>U$,sqrtImpl:()=>W$,squaredDifferenceImpl:()=>j$,staticRegexReplaceImpl:()=>X$,stridedSliceImpl:()=>Z$,stringNGramsImpl:()=>eA,stringSplitImpl:()=>nA,stringToHashBucketFastImpl:()=>rA,subImpl:()=>sA,tileImpl:()=>uA,topKImpl:()=>hA,transposeImpl:()=>m$,uniqueImpl:()=>dA});var q={};n.r(q),n.d(q,{assertNotComplex:()=>ED,bindCanvasToFramebuffer:()=>tD,bindColorTextureToFramebuffer:()=>nD,bindTextureToProgramUniformSampler:()=>eD,bindTextureUnit:()=>YF,bindVertexBufferToProgramAttribute:()=>XF,callAndCheck:()=>AF,canBeRepresented:()=>MF,createFragmentShader:()=>LF,createFramebuffer:()=>KF,createProgram:()=>BF,createStaticIndexBuffer:()=>GF,createStaticVertexBuffer:()=>WF,createTexture:()=>jF,createVertexShader:()=>
5057OF,getBatchDim:()=>uD,getExtensionOrThrow:()=>DF,getFramebufferErrorMessage:()=>aD,getMaxTexturesInShader:()=>xD,getNumChannels:()=>HF,getProgramUniformLocation:()=>QF,getProgramUniformLocationOrThrow:()=>ZF,getRowsCols:()=>lD,getShapeAs3D:()=>cD,getTextureShapeFromLogicalShape:()=>hD,getWebGLDisjointQueryTimerVersion:()=>wD,getWebGLErrorMessage:()=>FF,getWebGLMaxTextureSize:()=>gD,hasExtension:()=>vD,isCapableOfRenderingToFloatTexture:()=>ID,isDownloadFloatTextureEnabled:()=>SD,isReshapeFree:()=>pD,isWebGLFenceEnabled:()=>TD,isWebGLVersionEnabled:()=>kD,linkProgram:()=>VF,logShaderSourceAndInfoLog:()=>PF,resetMaxTextureSize:()=>yD,resetMaxTexturesInShader:()=>bD,unbindColorTextureFromFramebuffer:()=>rD,unbindTextureUnit:()=>JF,validateFramebuffer:()=>sD,validateProgram:()=>UF,validateTextureSize:()=>qF});var K={};n.r(K),n.d(K,{bindVertexProgramAttributeStreams:()=>bO,createBufferFromOutputTexture:()=>vO,createFloat16MatrixTexture:()=>hO,createFloat16PackedMatrixTexture:()=>yO,createFloat32MatrixTexture:()=>lO,createIndexBuffer:()=>iO,createPackedMatrixTexture:()=>mO,createUnsignedBytesMatrixTexture:()=>pO,createVertexBuffer:()=>aO,createVertexShader:()=>sO,downloadByteEncodedFloatMatrixFromOutputTexture:()=>IO,downloadFloat32MatrixFromBuffer:()=>kO,downloadMatrixFromPackedOutputTexture:()=>NO,downloadPackedMatrixFromBuffer:()=>SO,getInternalFormatForFloat16MatrixTexture:()=>cO,getInternalFormatForFloat16PackedMatrixTexture:()=>gO,getInternalFormatForFloat32MatrixTexture:()=>uO,getInternalFormatForPackedMatrixTexture:()=>fO,getInternalFormatForUnsignedBytesMatrixTexture:()=>dO,uploadDenseMatrixToTexture:()=>xO,uploadPixelDataToTexture:()=>wO});class X{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 Y{refCount(e){return J("refCount")}incRef(e){return J("incRef")}timerAvailable(){return!0}time(e){return J("time")}read(e){return J("read")}readSync(e){return J("readSync")}readToGPU(e,t){return J("readToGPU")}numDataIds(){return J("numDataIds")}disposeData(e,t){return J("disposeData")}write(e,t,n){return J("write")}move(e,t,n,r,s){return J("move")}createTensorFromGPUData(e,t,n){return J("createTensorFromGPUData")}memory(){return J("memory")}floatPrecision(){return J("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return J("dispose")}}function J(e){throw new Error(`\'${e}\' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function Z(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,ne(e,t,n)}function Q(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,ne(e,n,r),ne(t,n,r)}function ee(e,t,n){return Math.max(e,Math.min(t,n))}function te(e){return e%2==0?e:e+1}function ne(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function re(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function se(e,t){const n=Math.random();return t*n+(1-n)*e}function ae(e,t){let n=0;for(let r=0;r<e.length;r++){const s=Number(e[r])-Number(t[r]);n+=s*s}return n}function ie(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function oe(e,t,n=""){ie(de(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function ue(e){ie(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function le(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function ce(e){return 0===e.length}function he(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}function de(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function pe(e){return e%1==0}function fe(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function me(e){const t=Math.ceil(Math.sqrt(e));
5057return[t,Math.ceil(e/t)]}function ge(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Z(t),t}function ye(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function be(e,t=e=>0,n,r){return new Promise((s,a)=>{let i=0;const o=()=>{if(e())return void s();i++;const u=t(i);null!=n&&i>=n?a():null!=r?r(o,u):setTimeout(o,u)};o()})}function xe(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can\'t be a fractional number. Got ${t} / ${n}`);const s=e.slice();return s[r]=t/n,s}function we(e,t){const n=t.length;return ie((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),ie(e.every(e=>pe(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function ve(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||s?null:we(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=a){if(a[i]===t&&1!==e[t])throw new Error(`Can\'t squeeze axis ${t} since its dim \'${e[t]}\' is not 1`);(null==a[i]||a[i]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function ke(e,t){return Ie(e,t)}function Ie(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function Se(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function Ne(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function Te(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function Ee(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function Ce(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}function $e(e){return"string"==typeof e||e instanceof String}function Ae(e){return"boolean"==typeof e}function Re(e){return"number"==typeof e}function _e(e){return Array.isArray(e)?_e(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Re(e)?"float32":$e(e)?"string":Ae(e)?"bool":"float32"}function Me(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Fe(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function De(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function Oe(e,t,n,r=!1){const s=new Array;if(1===t.length){const a=t[0]*(r?2:1);for(let t=0;t<a;t++)s[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce((e,t)=>e*t)*(r?2:1);for(let t=0;t<a;t++)s[t]=Oe(e+t*o,i,n,r)}return s}function Le(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce((e,t)=>e*t)*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return Oe(0,e,t,n)}function ze(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Pe(e,t){const n=Be(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function Be(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function Ve(e,t){const n=e.reduce((e,t)=>
vendor: 7,014 bytes, line 5057
5057e*t,1);if(null==t||"float32"===t)return Le(e,new Float32Array(n));if("int32"===t)return Le(e,new Int32Array(n));if("bool"===t)return Le(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ue(e){e.forEach(t=>{ie(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function We(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function Ge(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r}function He(e){return e&&e.then&&"function"==typeof e.then}const je="tfjsflags";class qe{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Ke,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(He(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag \'${e}\': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);je in e&&e[je].split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)})}}function Ke(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}function Xe(){return Je}let Ye,Je=null;function Ze(){if(null==Ye){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Ye=e}return Ye}function Qe(e,t){const n=function(){const e=Ze();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const et="Abs",tt="Acos",nt="Acosh",rt="Add",st="AddN",at="All",it="Any",ot="ArgMax",ut="ArgMin",lt="Asin",ct="Asinh",ht="Atan",dt="Atanh",pt="Atan2",ft="AvgPool",mt="AvgPoolGrad",gt="AvgPool3D",yt="AvgPool3DGrad",bt="BatchMatMul",xt="BatchToSpaceND",wt="Bincount",vt="BitwiseAnd",kt="BroadcastTo",It="BroadcastArgs",St="Cast",Nt="Ceil",Tt="ClipByValue",Et="Complex",Ct="ComplexAbs",$t="Concat",At="Conv2D",Rt="Conv2DBackpropFilter",_t="Conv2DBackpropInput",Mt="Conv3D",Ft="Conv3DBackpropFilterV2",Dt="Conv3DBackpropInputV2",Ot="Cos",Lt="Cosh",zt="Cumprod",Pt="Cumsum",Bt="CropAndResize",Vt="DenseBincount",Ut="DepthToSpace",Wt="DepthwiseConv2dNative",Gt="DepthwiseConv2dNativeBackpropFilter",Ht="DepthwiseConv2dNativeBackpropInput",jt="Diag",qt="Dilation2D",Kt="Dilation2DBackpropInput",Xt="Dilation2DBackpropFilter",Yt="Draw",Jt="RealDiv",Zt="Einsum",Qt="Elu",en="EluGrad",tn="Erf",nn="Equal",rn="Exp",sn="ExpandDims",an="Expm1",on="FFT",un="Fill",ln="FlipLeftRight",cn="Floor",hn="FloorDiv",dn="FusedBatchNorm",pn="GatherV2",fn="GatherNd",mn="Greater",gn="GreaterEqual",yn="Identity",bn="IFFT",xn="Imag",wn="IsFinite",vn="IsInf",kn="IsNan",In="LeakyRelu",Sn="Less",Nn="LessEqual",Tn="LinSpace",En="Log",Cn="Log1p",$n="LogicalAnd",An="LogicalNot",Rn="LogicalOr",_n="LogicalXor",Mn="LogSoftmax",Fn="LowerBound",Dn="LRN",On="LRNGrad",Ln="MatrixBandPart",zn="Max",Pn="Maximum",Bn="MaxPool",Vn="MaxPoolGrad",Un="MaxPool3D",Wn="MaxPool3DGrad",Gn="MaxPoolWithArgmax",Hn="Mean",jn="Min",qn="Minimum",Kn="MirrorPad",Xn="Mod",Yn="Multinomial",Jn="Multiply",Zn="Neg",Qn="NotEqual",er="NonMaxSuppressionV3",tr="NonMaxSuppressionV4",nr="NonMaxSuppressionV5",rr="OnesLike",sr="OneHot",ar="Pack",ir="PadV2",or="Pool",ur="Pow",lr="Prelu",cr="Prod",hr="RaggedGather",dr="RaggedRange",pr="RaggedTensorToTensor",fr="Range",mr="Real",gr="Reciprocal",yr="Relu",br="Reshape",xr="ResizeNearestNeighbor",wr="ResizeNearestNeighborGrad",vr="ResizeBilinear",kr="ResizeBilinearGrad",Ir="Relu6",Sr="Reverse",Nr="Round",Tr="Rsqrt",Er="ScatterNd",Cr="TensorScatterUpdate",$r="SearchSorted",Ar="Select",Rr="Selu",_r="Slice",Mr="Sin",Fr="Sinh",Dr="Sign",Or="Sigmoid",Lr="Softplus",zr="Sqrt",Pr="Sum",Br="SpaceToBatchND",Vr="SplitV",Ur="Softmax",Wr="SparseFillEmptyRows",Gr="SparseReshape",Hr="SparseSegmentMean",jr="SparseSegmentSum",qr="SparseToDense",Kr="SquaredDifference",Xr="Square",Yr="StaticRegexReplace",Jr="StridedSlice",Zr="StringNGrams",Qr="StringSplit",es="StringToHashBucketFast",ts="Sub",ns="Tan",rs="Tanh",ss="Tile",as="TopK",is="Transform",os="Transpose",us="Unique",ls="Unpack",cs="UnsortedSegmentSum",hs="UpperBound",ds="ZerosLike",ps="Step",fs="FromPixels",ms="RotateWithOffset",gs="_FusedMatMul",ys="FusedConv2D",bs="FusedDepthwiseConv2D";function xs(...e){Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.warn(...e)}function ws(...e){Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.log(...e)}const vs=Qe("kernelRegistry",()=>new Map),ks=Qe("gradRegistry",()=>new Map);function Is(e,t){const n=Rs(e,t);return vs.get(n)}function Ss(e){return ks.get(e)}function Ns(e){const t=vs.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[a,i]=s,[o]=a.split("_");o===e&&n.push(i)}return n}function Ts(e){const{kernelName:t,backendName:n}=e,r=Rs(t,n);vs.has(r)&&xs(`The kernel \'${t}\' for backend \'${n}\' is already registered`),vs.set(r,e)}function Es(e){const{kernelName:t}=e;ks.has(t)&&Xe().getBool("DEBUG")&&xs(`Overriding the gradient for \'${t}\'`),ks.set(t,e)}function Cs(e,t){const n=Rs(e,t);if(!vs.has(n))throw new Error(`The kernel \'${e}\' for backend \'${t}\' is not registered`);vs.delete(n)}function $s(e){if(!ks.has(e))throw new Error(`The gradient \'${e}\' for backend is not registered`);ks.delete(e)}
vendor: 4,846 bytes, line 5057
5057function As(e,t){Ns(e).forEach(e=>{Ts(Object.assign({},e,{backendName:t}))})}function Rs(e,t){return`${t}_${e}`}function _s(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Ms=n(570);const Fs=n.n(Ms)()||Ms;function Ds(e){return Fs.fromString(e,!0,16)}const Os=Ds("c3a5c85c97cb3127"),Ls=Ds("b492b66fbe98f273"),zs=Ds("9ae16a3b2f90404f");function Ps(e){return e.xor(e.shru(47))}function Bs(e,t,n){const r=e.slice(t,t+n);return Fs.fromBytes(Array.from(r),!0,!0)}function Vs(e,t){return Bs(e,t,8)}function Us(e,t){return Bs(e,t,4)}function Ws(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Gs(e,t,n=Ds("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function Hs(e,t,n,r){return function(e,t,n,r,s,a){s=s.add(e),a=Ws(a.add(s).add(r),21);const i=s;return s=(s=s.add(t)).add(n),a=a.add(Ws(s,44)),[s.add(r),a.add(i)]}(Vs(e,t),Vs(e,t+8),Vs(e,t+16),Vs(e,t+24),n,r)}function js(e,t=e.length){const n=Fs.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=zs.add(2*t),r=Vs(e,0).add(zs),s=Vs(e,t-8);return Gs(Ws(s,37).mul(n).add(r),Ws(r,25).add(s).mul(n),n)}if(t>=4){const n=zs.add(2*t);return Gs(Us(e,0).shl(3).add(t),Us(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Ps(zs.mul(n).xor(Os.mul(r))).mul(zs)}return zs}(e,t):function(e,t=e.length){const n=zs.add(2*t),r=Vs(e,0).mul(Ls),s=Vs(e,8),a=Vs(e,t-8).mul(n),i=Vs(e,t-16).mul(zs);return Gs(Ws(r.add(s),43).add(Ws(a,30)).add(i),r.add(Ws(s.add(zs),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=zs.add(2*t),r=Vs(e,0).mul(zs),s=Vs(e,8),a=Vs(e,t-8).mul(n),i=Vs(e,t-16).mul(zs),o=Ws(r.add(s),43).add(Ws(a,30)).add(i),u=Gs(o,r.add(Ws(s.add(zs),18)).add(a),n),l=Vs(e,16).mul(n),c=Vs(e,24),h=o.add(Vs(e,t-32)).mul(n),d=u.add(Vs(e,t-24)).mul(n);return Gs(Ws(l.add(c),43).add(Ws(h,30)).add(d),l.add(Ws(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(Ls).add(113),a=Ps(s.mul(zs).add(113)).mul(zs),i=[Fs.UZERO,Fs.UZERO],o=[Fs.UZERO,Fs.UZERO];r=r.mul(zs).add(Vs(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=Ws(r.add(s).add(i[0]).add(Vs(e,u+8)),37).mul(Ls),s=Ws(s.add(i[1]).add(Vs(e,u+48)),42).mul(Ls),r=r.xor(o[1]),s=s.add(i[0]).add(Vs(e,u+40)),a=Ws(a.add(o[0]),33).mul(Ls),i=Hs(e,u,i[1].mul(Ls),r.add(o[0])),o=Hs(e,u+32,a.add(o[1]),s.add(Vs(e,u+16))),[a,r]=[r,a],u+=64}while(u!==l);const h=Ls.add(a.and(255).shl(1));return u=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),r=Ws(r.add(s).add(i[0]).add(Vs(e,u+8)),37).mul(h),s=Ws(s.add(i[1]).add(Vs(e,u+48)),42).mul(h),r=r.xor(o[1].mul(9)),s=s.add(i[0].mul(9).add(Vs(e,u+40))),a=Ws(a.add(o[0]),33).mul(h),i=Hs(e,u,i[1].mul(h),r.add(o[0])),o=Hs(e,u+32,a.add(o[1]),s.add(Vs(e,u+16))),[a,r]=[r,a],Gs(Gs(i[0],o[0],h).add(Ps(s).mul(Os)).add(a),Gs(i[1],o[1],h).add(r),h)}function qs(e,t){return"string"===t?Js(e):Ks([e],t)}function Ks(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ea(e)),Xe().getBool("DEBUG")&&Se(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Xs(){return Xe().platform.now()}function Ys(e,t){return Xe().platform.fetch(e,t)}function Js(e,t="utf-8"){return t=t||"utf-8",Xe().platform.encode(e,t)}function Zs(e,t="utf-8"){return t=t||"utf-8",Xe().platform.decode(e,t)}function Qs(e){return null!=Xe().platform.isTypedArray?Xe().platform.isTypedArray(e):_s(e)}function ea(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||He(e)||null==e||Qs(e)&&n)t.push(e);else if(Array.isArray(e)||Qs(e))for(let r=0;r<e.length;++r)ea(e[r],t,n);else{let r=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(r=Math.max(r,Number(t)));for(let s=0;s<=r;s++)ea(e[s],t,n)}return t}class ta{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new ra)}profileKernel(e,t,n){let r;const s=()=>{r=n()};let a;const i=Xs();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();a=Promise.resolve({kernelMs:Xs()-i})}if(Xe().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then(t=>{na(t,n.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then(e=>e.kernelMs),extraInfo:a.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;
vendor: 4,645 bytes, line 5057
5057n.forEach(e=>{Promise.all([e.data(),r,a]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])})})}}function na(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of \'${n}\'`),!0}return!1}class ra{logKernelProfile(e,t,n,r,s,a){const i="number"==typeof r?ye(`${r}ms`,9):r.error,o=ye(e,25),u=t.rank,l=t.size,c=ye(t.shape.toString(),14);let h="";for(const e in s){const n=s[e];if(null!=n){const r=n.shape||t.shape,s=r.length;h+=`${e}: ${s}D ${s>0?r:""} `}}console.log(`%c${o}\\t%c${i}\\t%c${u}D ${c}\\t%c${l}\\t%c${h}\\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function sa(e,t,n,r){const s=De(t),a=function(e,t,n,r){const s=le(t),a=r[r.length-1],i=new Array(a).fill(0),o=t.length,u="complex64"===n?ua(e):e;if(o>1)for(let e=0;e<s/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],aa(u[t+e],0,n).length)}return i}(e,t,n,s),i=t.length,o=oa(e,t,n,s,a),u=["Tensor"];return r&&(u.push(`  dtype: ${n}`),u.push(`  rank: ${i}`),u.push(`  shape: [${t}]`),u.push("  values:")),u.push(o.map(e=>"    "+e).join("\\n")),u.join("\\n")}function aa(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:$e(e)?`\'${e}\'`:"bool"===n?ia(e):parseFloat(e.toFixed(7)).toString(),ye(r,t)}function ia(e){return 0===e?"false":"true"}function oa(e,t,n,r,s,a=!0){const i="complex64"===n?2:1,o=t[0],u=t.length;if(0===u)return"complex64"===n?[aa(ua(e)[0],0,n)]:"bool"===n?[ia(e[0])]:[e[0].toString()];if(1===u){if(o>20){const t=3*i;let r=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(r=ua(r),a=ua(a)),["["+r.map((e,t)=>aa(e,s[t],n)).join(", ")+", ..., "+a.map((e,t)=>aa(e,s[o-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?ua(e):Array.from(e)).map((e,t)=>aa(e,s[t],n)).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),h=r[0]*i,d=[];if(o>20){for(let t=0;t<3;t++){const r=t*h,a=r+h;d.push(...oa(e.slice(r,a),l,n,c,s,!1))}d.push("...");for(let t=o-3;t<o;t++){const r=t*h,a=r+h;d.push(...oa(e.slice(r,a),l,n,c,s,t===o-1))}}else for(let t=0;t<o;t++){const r=t*h,a=r+h;d.push(...oa(e.slice(r,a),l,n,c,s,t===o-1))}const p=2===u?",":"";d[0]="["+(o>0?d[0]+p:"");for(let e=1;e<d.length-1;e++)d[e]=" "+d[e]+p;let f=",\\n";for(let e=2;e<u;e++)f+="\\n";return d[d.length-1]=" "+d[d.length-1]+"]"+(a?"":f),d}function ua(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class la{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=le(e),null!=n){const e=n.length;ie(e===this.size,()=>`Length of values \'${e}\' does not match the size inferred by the shape \'${this.size}\'.`)}if("complex64"===t)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=n||Ie(t,this.size),this.strides=De(e)}set(e,...t){0===t.length&&(t=[0]),ie(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}.   Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return ca().makeTensor(this.values,this.shape,this.dtype)}}let ca=null,ha=null,da=null;class pa{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=le(e),this.strides=De(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return ha.buffer(this.shape,this.dtype,e)}bufferSync(){return ha.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Le(this.shape,e,"complex64"===this.dtype)}arraySync(){return Le(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=ca().read(this.dataId);if("string"===this.dtype){const t=await e;
vendor: 4,549 bytes, line 5057
5057try{return t.map(e=>Zs(e))}catch(e){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(),ca().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=ca().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>Zs(e))}catch(e){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 ca().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),ca().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return ha.print(this,e)}clone(){return this.throwIfDisposed(),ha.clone(this)}toString(e=!1){return sa(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),ha.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ca().makeVariable(this,e,t,n)}}function fa(){return Qe("Tensor",()=>pa)}Object.defineProperty(pa,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),fa();class ma extends pa{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}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(!de(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ca().disposeTensor(this),this.dataId=e.dataId,ca().incRef(this,null)}dispose(){ca().disposeVariable(this),this.isDisposedInternal=!0}}var ga,ya,ba,xa,wa;Object.defineProperty(ma,Symbol.hasInstance,{value:e=>e instanceof pa&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(ga||(ga={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(ya||(ya={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(ba||(ba={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(xa||(xa={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(wa||(wa={}));const va={float32:xa,int32:ya,bool:ba,complex64:wa};function ka(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return va[e][t]}function Ia(e){return ka(e,"int32")}function Sa(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Na(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Ta(e,t){if(e.dtype===t.dtype)return[e,t];const n=ka(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Ea(e,t){ie(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Ca(e,t){return t.some(t=>t.id===e.id)}function $a(e){const t=[];return Aa(e,t,new Set),t}function Aa(e,t,n){if(null==e)return;if(e instanceof pa)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),Aa(r,t,n))}}function Ra(e){return null!=e.kernelName}class _a{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 Ma{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new _a}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}
vendor: 1,160 bytes, line 5057
5057get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend \'${this.backendName}\' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend \'${e}\' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(xs(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name \'${e}\' not found in registry`);
vendor: 9,314 bytes, line 5057
5057if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new ta(this.backendInstance),!0}setupRegisteredKernels(){Ns(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Ns(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof Y||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then(n=>!(t<this.pendingBackendInitId||(this.registry[e]=n,this.pendingBackendInit=null,0))).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,xs(`Initialization of backend ${e} failed`),xs(n.stack||n.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return xs(`Initialization of backend ${e} failed`),xs(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,s=this.readSync(t),a=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Ma.nextTensorId++}nextVariableId(){return Ma.nextVariableId++}clone(e){const t=Da.runKernel(yn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e};return Da.runKernel(St,t,{dtype:"float32"})}}),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==Is(e,this.backendName))throw new Error(`Kernel \'${e}\' not registered for backend \'${this.backendName}\'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let s=0;n.forEach(e=>{s+="complex64"===e.dtype?3:1});const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-t-s-a;if(i>0)throw new Error(`Backend \'${this.backendName}\' has an internal memory leak (${i} data ids) after running \'${e}\'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Ra(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Ra(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const u=Is(t,this.backendName);ie(null!=u,()=>`Cannot find registered kernel \'${t}\' for backend \'${this.backendName}\'`),i=()=>{const e=this.backend.numDataIds();o=u.kernelFunc({inputs:s,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const l=i.map(e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e));if(r){const e=this.getTensorsForGradient(t,s,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy(()=>t(this.backend,s));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:c}=e,h=Ra(e)?null:e.backwardsFunc;let d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(d=this.profiler.profileKernel(u,l,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()}),r&&this.addTapeNode(u,l,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(e=>null!=l[e]?l[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map(e=>this.keep(this.clone(e)));return t}getTensorsForGradient(e,t,n){const r=Ss(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(ie(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(e=>t[e])):a=e.map(e=>t[e]);const i=n.filter((e,t)=>s[t]);return a.concat(i)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;"string"===n&&$e(e[0])&&(s=e.map(e=>Js(e)));const a=r.write(s,t,n),i=new pa(t,n,a,this.nextTensorId());if(this.trackTensor(i,r),"string"===n){const e=this.state.tensorInfo.get(a),t=Ce(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,r){const s={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:s}=e,a=new pa(r,s,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new ma(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*Ee(e.dtype)),this.state.numBytes+=n,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:n})),e instanceof ma||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--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*Ee(e.dtype);this.state.numBytes-=t}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),null!=this.state.registeredVariables[e.name]&&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,null==e.reasons&&(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,n=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(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>
50570&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},o=Ss(e);null!=o&&(r=o.gradFunc),null!=r&&(i.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=Be(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],s,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(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=$a(e),n=new Set(t.map(e=>e.id));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(e=>{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(ie(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have \'float32\' dtype, but has \'${n.dtype}\'`);const s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));ie(s instanceof pa,()=>"The result y returned by f() must be a tensor.");const a=function(e,t,n){const r={},s={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const a=e[n],i=a.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(r[n.id]){a.outputs.forEach(e=>r[e.id]=!0),o=!0,s[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(a[n.outputs[e].id]){for(const e in r)a[r[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(s[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const s=n.inputs[t];r[s.id]&&(e[t]=s)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,s);if(!r&&0===a.length&&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 e={};e[s.id]=null==n?function(e){const t=Pe(le(e),"float32");return Da.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const a=t[s],i=[];if(a.outputs.forEach(t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)}),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const s=n(()=>o[t]());if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have \'float32\' dtype, but has \'${s.dtype}\'`);const i=a.inputs[t];if(!de(s.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input \'${t}\' has shape \'${s.shape}\', which does not match the shape of the input \'${i.shape}\'`);if(null==e[i.id])e[i.id]=s;else{const t=e[i.id];e[i.id]=r(t,s),t.dispose()}}}}(e,a,e=>this.tidy(e),Oa);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:s,grads:r}})}customGrad(e){return ie(Me(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;ie(t.every(e=>e instanceof pa),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};return t.forEach((e,t)=>{r[t]=e}),this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),ie(n.value instanceof pa,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),ie(Me(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const s=n.gradFunc(e,r),a=Array.isArray(s)?s:[s];ie(a.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(...)."),ie(a.every(e=>e instanceof pa),()=>"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 i={};return a.forEach((e,t)=>{i[t]=()=>e}),i},inputs:r})}}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=Xs(),n=await this.backend.time(e);return n.wallMs=Xs()-t,n}track(e){return null!=this.state.activeScope&&(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 _a;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}}function Fa(){const e=Ze();if(null==e._tfengine){const t=new qe(e);e._tfengine=new Ma(t)}var t;return t=e._tfengine.ENV,Je=t,ca=()=>e._tfengine,e._tfengine}Ma.nextTensorId=0,Ma.nextVariableId=0;const Da=Fa();function Oa(e,t){const n={a:e,b:t};return Da.runKernel(rt,n)}let La;function za(e){La=e}function Pa(e){if(void 0!==La)return La;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-
5057)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i.test(t.substr(0,4))}return!1}function Ba(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const Va=Xe();function Ua(e,t){let n=e;if(Qs(e))return"string"===t?[]:[e.length];if(Sa(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Na(e))return[e.buffer.size/(null==t?4:Ee(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Qs(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Xe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Wa(e,r,[]),r}function Wa(e,t,n){if(n=n||[],!Array.isArray(e)&&!Qs(e))return void ie(0===t.length,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);ie(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),ie(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let t=0;t<e.length;++t)Wa(e[t],r,n.concat(t))}function Ga(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument \'${n}\' passed to \'${r}\' must be ${e} tensor, but got ${t} tensor`)}}function Ha(e,t,n,r="numeric"){if(e instanceof fa())return Ga(r,e.dtype,t,n),e;let s=_e(e);if("string"!==s&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),Ga(r,s,t,n),null==e||!Qs(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument \'${t}\' passed to \'${n}\' must be a Tensor or TensorLike, but got \'${r}\'`)}const a=Ua(e,s);Qs(e)||Array.isArray(e)||(e=[e]);const i="string"!==s?Ks(e,s):ea(e,[],!0);return Da.makeTensor(i,a,s)}function ja(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \\`Tensor[]\\` or \\`TensorLike[]\\``);return e.map((e,s)=>Ha(e,`${t}[${s}]`,n,r))}Va.registerFlag("DEBUG",()=>!1,e=>{e&&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.")}),Va.registerFlag("IS_BROWSER",()=>Ba()),Va.registerFlag("IS_NODE",()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node),Va.registerFlag("IS_CHROME",()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Va.registerFlag("IS_SAFARI",()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Va.registerFlag("PROD",()=>!1),Va.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Va.getBool("DEBUG")),Va.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Va.registerFlag("IS_TEST",()=>!1),Va.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Va.getBool("DEBUG")),Va.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Va.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Va.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const qa="__op";function Ka(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=qa;const s=(...e)=>{Da.startScope(n);try{const t=r(...e);return He(t)&&console.error("Cannot return a Promise inside of tidy."),Da.endScope(t),t}catch(e){throw Da.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const Xa=Ka({complex_:function(e,t){const n=Ha(e,"real","complex"),r=Ha(t,"imag","complex");oe(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return Da.runKernel(Et,s)}});function Ya(e,t,n,r){if(null==r)r=_e(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
vendor: 4,137 bytes, line 5057
5057if(Na(e)||Sa(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports \'float32\'|\'int32\' dtype, while the dtype is ${r}.`);return Da.backend.createTensorFromGPUData(e,t||n,r)}if(!Qs(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)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(null!=t){Ue(t);const e=le(t),r=le(n);ie(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let e=0;e<n.length;++e){const r=n[e],s=e!==n.length-1||r!==le(t.slice(e));ie(n[e]===t[e]||!s,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return Qs(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Ks(e,r):ea(e,[],!0),Da.makeTensor(e,t,r)}function Ja(e,t,n){return Ya(e,t,Ua(e,n),n)}const Za={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Qa{static join(e){return new Qa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map(e=>Qs(e)?e.buffer:e)).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const r=e[n];n!==e.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const s=t+r.byteLength;this.shards.push({buffer:r,start:t,end:s}),t=s}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const r=new ArrayBuffer(t-e),s=new Uint8Array(r);let a=0;for(let r=n;r<this.shards.length;r++){const n=this.shards[r],i=e+a-n.start,o=a,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,i,u-i);if(s.set(l,o),a+=l.length,t<n.end)break}return r}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const s=Math.floor((r-n)/2)+n,a=t(e[s]);if(0===a)return s;a<0?r=s:n=s+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function ei(){Xe().set("PROD",!0)}function ti(){Xe().set("DEBUG",!0)}function ni(){Xe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function ri(e){Xe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function si(){Da.disposeVariables()}function ai(){return Da}function ii(){return Da.memory()}function oi(e){return Da.profile(e)}function ui(e,t){return Da.tidy(e,t)}function li(e){$a(e).forEach(e=>e.dispose())}function ci(e){return Da.keep(e)}function hi(e){return Da.time(e)}function di(e){return Da.setBackend(e)}function pi(){return Da.ready()}function fi(){return Da.backendName}function mi(e){Da.removeBackend(e)}function gi(e){return Da.findBackend(e)}function yi(e){return Da.findBackendFactory(e)}function bi(e,t,n=1){return Da.registerBackend(e,t,n)}function xi(){return Da.backend}function wi(e,t){Xe().setPlatform(e,t)}da=ri;const vi=4;async function ki(e,t){const n=[],r=[],s=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);for(let a=0;a<s.length;++a){const i=s[a],o=Array.isArray(e)?e[a].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight \'${i}\': ${o.dtype}`);const u={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise(async e=>{const t=await o.bytes(),n=t.reduce((e,t)=>
vendor: 14,955 bytes, line 5057
5057e+t.length,0)+vi*t.length,r=new Uint8Array(n);let s=0;for(let e=0;e<t.length;e++){const n=t[e],a=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(a,s),s+=vi,r.set(n,s),s+=n.length}e(r)});r.push(e)}else r.push(o.data());null!=t&&(u.group=t),n.push(u)}return{data:$i(await Promise.all(r)),specs:n}}function Ii(e,t){const n=new Qa(e),r={};let s=0;for(const e of t){const t=Si(e,(e,t)=>n.slice(s+e,s+t));r[e.name]=Ti(e,n.slice(s,s+t)),s+=t}return r}function Si(e,t){const n=le(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Za[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=vi+new Uint32Array(t(e,e+vi))[0];return e}r=Za[e.dtype]}return n*r}async function Ni(e,t){const n=le(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Za[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=vi+new Uint32Array(await t(e,e+vi))[0];return e}r=Za[e.dtype]}return n*r}function Ti(e,t){const n=e.name,r=e.dtype,s=e.shape,a=le(s);let i,o=0;if("quantization"in e){const s=e.quantization;if("uint8"===s.dtype||"uint16"===s.dtype){if(!("min"in s)||!("scale"in s))throw new Error(`Weight ${e.name} with quantization ${s.dtype} doesn\'t have corresponding metadata min and scale.`)}else{if("float16"!==s.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${s.dtype}. Supported quantization dtypes are: \'uint8\', \'uint16\', and \'float16\'.`);if("float32"!==r)throw new Error(`Weight ${e.name} is quantized with ${s.dtype} which only supports weights of type float32 not ${r}.`)}const u=Za[s.dtype],l="uint8"===s.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===r)if("uint8"===s.dtype||"uint16"===s.dtype){i=new Float32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=t*s.scale+s.min}}else{if("float16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;!(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let s=0;s<r.length;s++){const i=r[s],o=e[n[i>>10]+(1023&i)]+t[i>>10];a[s]=o}return new Float32Array(s)}}();i=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight \'${n}\': ${r}`);if("uint8"!==s.dtype&&"uint16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type int32.`);i=new Int32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=Math.round(t*s.scale+s.min)}}o+=a*u}else if("string"===r){const n=le(e.shape);i=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+vi))[0];o+=vi;const n=new Uint8Array(t.slice(o,o+e));i.push(n),o+=e}}else{const e=Za[r];if("float32"===r)i=new Float32Array(t);else if("int32"===r)i=new Int32Array(t);else{if("bool"!==r){if("complex64"===r){i=new Float32Array(t);const e=new Float32Array(i.length/2),n=new Float32Array(i.length/2);for(let t=0;t<e.length;t++)e[t]=i[2*t],n[t]=i[2*t+1];const r=Ja(e,s,"float32"),a=Ja(n,s,"float32"),o=Xa(r,a);return r.dispose(),a.dispose(),o}throw new Error(`Unsupported dtype in weight \'${n}\': ${r}`)}i=new Uint8Array(t)}o+=a*e}return Ja(i,s,r)}async function Ei(e,t,n){let r=new Uint8Array(t);for(;r.byteLength<n;){const{done:t,value:s}=await e.read();if(t&&null==s){const e=n-r.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const a=new Uint8Array(r.length+s.byteLength);a.set(r,0),a.set(new Uint8Array(s),r.length),r=a}return r.buffer}async function Ci(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await Ni(e,async(e,t)=>(s=await Ei(r,s,t),s.slice(e,t)));s=await Ei(r,s,t);const a=s.slice(0,t);s=s.slice(t);const i=Ti(e,a);if(n[e.name]=i,"webgpu"===fi()){const e=xi();"uploadToGPU"in e&&le(i.shape)>=Xe().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(i.dataId)}}return n}function $i(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)});const r=new Uint8Array(t);let s=0;return n.forEach(e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength}),r.buffer}const Ai="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Ri(e){return Ai?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function _i(e){return Qa.join(e)}function Mi(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Fi(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function Di(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function Oi(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),Di(e,n,r)}function Li(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Ri(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Ri(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new Qa(e.weightData).byteLength}}function zi(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Pi{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Pi.instance&&(Pi.instance=new Pi),Pi.instance}static registerSaveRouter(e){Pi.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Pi.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Pi.getHandlers(e,"save")}static getLoadHandlers(e,t){return Pi.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Pi.getInstance().loadRouters:Pi.getInstance().saveRouters).forEach(t=>{const s=t(e,n);null!==s&&r.push(s)}),r}}const Bi=e=>Pi.registerSaveRouter(e),Vi=e=>Pi.registerLoadRouter(e),Ui=e=>Pi.getSaveHandlers(e),Wi=(e,t)=>Pi.getLoadHandlers(e,t),Gi="tensorflowjs",Hi="models_store",ji="model_info_store";function qi(){if(!Xe().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Ki(e){const t=e.result;t.createObjectStore(Hi,{keyPath:"modelPath"}),t.createObjectStore(ji,{keyPath:"modelPath"})}class Xi{constructor(e){if(this.indexedDB=qi(),null==e||!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((e,n)=>{const r=this.indexedDB.open(Gi,1);r.onupgradeneeded=()=>Ki(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction(Hi,"readonly"),r=t.objectStore(Hi).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path \'${this.modelPath}\' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{t.weightData=Qa.join(t.weightData);const r=Li(t),a=s.transaction(ji,"readwrite");let i,o,u=a.objectStore(ji);try{i=u.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}i.onsuccess=()=>{o=s.transaction(Hi,"readwrite");const i=o.objectStore(Hi);let l;try{l=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(e){return n(e)}l.onsuccess=()=>e({modelArtifactsInfo:r}),l.onerror=e=>{u=a.objectStore(ji);const t=u.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(l.error)),t.onerror=e=>(s.close(),n(l.error))}},i.onerror=e=>(s.close(),n(i.error)),a.oncomplete=()=>{null==o?s.close():o.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)})}}Xi.URL_SCHEME="indexeddb://";const Yi=e=>{return Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Xi.URL_SCHEME)?(t=e.slice(Xi.URL_SCHEME.length),new Xi(t)):null;var t};Pi.registerSaveRouter(Yi),Pi.registerLoadRouter(Yi);class Ji{constructor(){this.indexedDB=qi()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(Gi,1);n.onupgradeneeded=()=>Ki(n),n.onsuccess=()=>{const r=n.result,s=r.transaction(ji,"readonly"),a=s.objectStore(ji).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(r.close(),t(a.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(Xi.URL_SCHEME)?t.slice(Xi.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open(Gi,1);r.onupgradeneeded=()=>Ki(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(ji,"readwrite"),i=a.objectStore(ji),o=i.get(e);let u;o.onsuccess=()=>{if(null==o.result)return s.close(),n(new Error(`Cannot find model with path \'${e}\' in IndexedDB.`));{const r=i.delete(e),a=()=>{u=s.transaction(Hi,"readwrite");const r=u.objectStore(Hi).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=a,r.onerror=e=>(a(),s.close(),n(o.error))}},o.onerror=e=>(s.close(),n(o.error)),a.oncomplete=()=>{null==u?s.close():u.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)})}}const Zi="/",Qi="tensorflowjs_models",eo="info",to="model_topology",no="weight_specs",ro="weight_data",so="model_metadata";function ao(e){return{info:[Qi,e,eo].join(Zi),topology:[Qi,e,to].join(Zi),weightSpecs:[Qi,e,no].join(Zi),weightData:[Qi,e,ro].join(Zi),modelMetadata:[Qi,e,so].join(Zi)}}function io(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function oo(e){const t=e.split(Zi);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zi)}class uo{constructor(e){if(!Xe().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=ao(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),n=JSON.stringify(e.weightSpecs),r=Li(e),s=Qa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Ai)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(s));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw io(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=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name \'${this.modelPath}\'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model \'${this.modelPath}\' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model \'${this.modelPath}\' are missing.`);t.weightSpecs=r;const s=this.LS.getItem(this.keys.modelMetadata);if(null!=s){const e=JSON.parse(s);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const a=this.LS.getItem(this.keys.weightData);if(null==a)throw new Error(`In local storage, the binary weight values of model \'${this.modelPath}\' are missing.`);return t.weightData=function(e){if(Ai){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(a),t}}uo.URL_SCHEME="localstorage://";const lo=e=>
5057{return Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(uo.URL_SCHEME)?(t=e.slice(uo.URL_SCHEME.length),new uo(t)):null;var t};Pi.registerSaveRouter(lo),Pi.registerLoadRouter(lo);class co{constructor(){ie(Xe().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),ie("undefined"==typeof window||void 0!==window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Qi+Zi,n=Zi+eo;for(let r=0;r<this.LS.length;++r){const s=this.LS.key(r);s.startsWith(t)&&s.endsWith(n)&&(e[oo(s)]=JSON.parse(this.LS.getItem(s)))}return e}async removeModel(e){var t;const n=ao(e=(t=e).startsWith(uo.URL_SCHEME)?t.slice(uo.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path \'${e}\'`);const r=JSON.parse(this.LS.getItem(n.info));return io(n),r}}const ho="://";class po{constructor(){this.managers={}}static getInstance(){return null==po.instance&&(po.instance=new po),po.instance}static registerManager(e,t){ie(null!=e,()=>"scheme must not be undefined or null."),e.endsWith(ho)&&(e=e.slice(0,e.indexOf(ho))),ie(e.length>0,()=>"scheme must not be an empty string.");const n=po.getInstance();ie(null==n.managers[e],()=>`A model store manager is already registered for scheme \'${e}\'.`),n.managers[e]=t}static getManager(e){const t=po.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme \'${e}\'`);return t}static getSchemes(){return Object.keys(po.getInstance().managers)}}function fo(e){if(-1===e.indexOf(ho))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${po.getSchemes().join(",")}`);return{scheme:e.split(ho)[0],path:e.split(ho)[1]}}async function mo(e,t,n=!1){ie(e!==t,()=>`Old path and new path are the same: \'${e}\'`);const r=Pi.getLoadHandlers(e);ie(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),ie(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const s=r[0],a=Pi.getSaveHandlers(t);ie(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),ie(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const i=a[0],o=fo(e).scheme,u=fo(e).path,l=o===fo(e).scheme,c=await s.load();n&&l&&await po.getManager(o).removeModel(u);const h=await i.save(c);return n&&!l&&await po.getManager(o).removeModel(u),h.modelArtifactsInfo}async function go(){const e=po.getSchemes(),t={};for(const n of e){const e=await po.getManager(n).listModels();for(const r in e)t[n+ho+r]=e[r]}return t}async function yo(e){const t=fo(e);return po.getManager(t.scheme).removeModel(t.path)}async function bo(e,t){return mo(e,t,!1)}async function xo(e,t){return mo(e,t,!0)}class wo{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("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser\'s encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Xe().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",e=>{e.source===window&&e.data.name===this.messageName&&(e.stopPropagation(),(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))},!0))):setTimeout(e,t)}isTypedArray(e){return _s(e)}}if(Xe().get("IS_BROWSER")){Xe().setPlatform("browser",new wo);try{po.registerManager(uo.URL_SCHEME,new co)}catch(e){}try{po.registerManager(Xi.URL_SCHEME,new Ji)}catch(e){}}let vo;function ko(e,t="float32",n){return t=t||"float32",Ue(e),new la(e,t,n)}
5057Xe().get("IS_NODE")&&!Xe().get("IS_BROWSER")&&Xe().setPlatform("node",new class{constructor(){this.util=n(590),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Xe().global.fetch?Xe().global.fetch(e,t):(null==vo&&(vo=n(817)),vo(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":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)}});const Io=Ka({cast_:function(e,t){const n=Ha(e,"x","cast");if(!Ne(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},s={dtype:t};return Da.runKernel(St,r,s)}}),So=Ka({clone_:function(e){const t={x:Ha(e,"x","clone","string_or_numeric")};return Da.runKernel(yn,t)}});function No(e,t=!1){console.log(e.toString(t))}Fa(),ha={buffer:ko,cast:Io,clone:So,print:No};const To=Ka({add_:function(e,t){let n=Ha(e,"a","add"),r=Ha(t,"b","add");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(rt,s)}}),Eo=Ka({floorDiv_:function(e,t){let n=Ha(e,"a","floorDiv"),r=Ha(t,"b","floorDiv");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(hn,s)}}),Co=Ka({div_:function(e,t){let n=Ha(e,"a","div"),r=Ha(t,"b","div");if([n,r]=Ta(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Eo(n,r);const s={a:n,b:r};return Da.runKernel(Jt,s,{})}}),$o=Ka({mul_:function(e,t){let n=Ha(e,"a","mul"),r=Ha(t,"b","mul");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(Jn,s)}}),Ao=Ka({sqrt_:function(e){const t={x:Ha(e,"x","sqrt","float32")};return Da.runKernel(zr,t)}}),Ro=Ka({square_:function(e){const t=Ha(e,"x","square");return Da.runKernel("Square",{x:t},{})}}),_o=Ka({zerosLike_:function(e){const t={x:Ha(e,"x","zerosLike")};return Da.runKernel(ds,t)}});function Mo(e){return ie(Me(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const r=Ha(t,"x","tf.grad","string_or_numeric"),s=null!=n?Ha(n,"dy","tf.grad"):null;return Da.tidy(()=>{const{value:t,grads:n}=Da.gradients(()=>e(r),[r],s);return null!=s&&oe(t.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Po(n),n[0]})}}function Fo(e){return ie(Me(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{ie(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=ja(t,"args","tf.grads","string_or_numeric"),s=null!=n?Ha(n,"dy","tf.grads"):null;return Da.tidy(()=>{const{value:t,grads:n}=Da.gradients(()=>e(...r),r,s);return null!=s&&oe(t.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Po(n),n})}}function Do(e){return ie(Me(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{ie(t instanceof pa,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),ie(null==n||n instanceof pa,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:s}=Da.gradients(()=>e(t),[t],n);return Po(r),{grad:r[0],value:s}}}function Oo(e){return ie(Me(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{ie(Array.isArray(t)&&t.every(e=>e instanceof pa),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),ie(null==n||n instanceof pa,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=Da.gradients(()=>e(...t),t,n);return null!=n&&oe(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Po(r.grads),r}}function Lo(e,t){ie(Me(e),()=>"The f passed in variableGrads(f) must be a function"),ie(null==t||Array.isArray(t)&&t.every(e=>e instanceof ma),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=null!=t;if(!n){t=[];for(const e in Da.registeredVariables)t.push(Da.registeredVariables[e])}const r=n?t.filter(e=>!e.trainable):null,s=t.length;t=t.filter(e=>e.trainable),ie(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);const{value:a,grads:i}=Da.gradients(e,t,null,!0);ie(i.some(e=>null!=e),()=>"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()."),ie(0===a.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const o={};return t.forEach((e,t)=>{null!=i[t]&&(o[e.name]=i[t])}
5057),null!=r&&r.forEach(e=>o[e.name]=null),{value:a,grads:o}}function zo(e){return Da.customGrad(e)}function Po(e){if(e.filter(e=>null==e).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\\n    the f you passed encloses all operations that lead from x to y.")}function Bo(e,t){if((Qs(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Qs(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ya(e,[],[],t)}const Vo=new Map,Uo=new Map;class Wo{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Go{constructor(){this.classNameMap={}}static getMap(){return null==Go.instance&&(Go.instance=new Go),Go.instance}static register(e){Go.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Ho(e,t,n){ie(null!=e.className,()=>"Class being registered does not have the static className property defined."),ie("string"==typeof e.className,()=>"className is required to be a string, but got type "+typeof e.className),ie(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),void 0===t&&(t="Custom"),void 0===n&&(n=e.className);const r=t+">"+n;return Go.register(e),Vo.set(r,e),Uo.set(e,r),e}function jo(e){return Uo.has(e)?Uo.get(e):e.className}class qo extends Wo{minimize(e,t=!1,n){const{value:r,grads:s}=this.computeGradients(e,n);if(null!=n){const e=n.map(e=>({name:e.name,tensor:s[e.name]}));this.applyGradients(e)}else this.applyGradients(s);return li(s),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Lo(e,t)}dispose(){null!=this.iterations_&&li(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Bo(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(qo,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Ko extends qo{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Da.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Da.registeredVariables[t],s=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:ui(()=>_o(r).variable(s))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:ui(()=>_o(r).variable(s))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;ui(()=>{const e=To($o(i,this.rho),$o(Ro(a),1-this.rho)),t=$o(Co(Ao(To(o,this.epsilon)),Ao(To(i,this.epsilon))),a),n=To($o(o,this.rho),$o(Ro(t),1-this.rho));i.assign(e),o.assign(n);const s=To($o(t,-this.learningRate),r);r.assign(s)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(li(this.accumulatedGrads.map(e=>e.variable)),li(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}function Xo(e,t,n){Ue(e);const r={shape:e,value:t,dtype:n=n||_e(t)};return Da.runKernel(un,{},r)}class Yo extends qo{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(e=>
5057e.name):Object.keys(e)).forEach((t,n)=>{const r=Da.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:ui(()=>Xo(r.shape,this.initialAccumulatorValue).variable(e))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=this.accumulatedGrads[n].variable;ui(()=>{const e=To(a,Ro(s));a.assign(e);const t=To($o(Co(s,Ao(To(e,Da.backend.epsilon()))),-this.learningRate),r);r.assign(t)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&li(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),this.accumulatedGrads=e.map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}const Jo=Ka({pow_:function(e,t){let n=Ha(e,"base","pow"),r=Ha(t,"exp","pow");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(ur,s)}}),Zo=Ka({sub_:function(e,t){let n=Ha(e,"a","sub"),r=Ha(t,"b","sub");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(ts,s)}});class Qo extends qo{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],ui(()=>{this.accBeta1=Bo(t).variable(),this.accBeta2=Bo(n).variable()}),null==r&&(this.epsilon=Da.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);ui(()=>{const n=Zo(1,this.accBeta1),r=Zo(1,this.accBeta2);t.forEach((t,s)=>{const a=Da.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:ui(()=>_o(a).variable(i))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:`${t}/v`,variable:ui(()=>_o(a).variable(i))});const o=Array.isArray(e)?e[s].tensor:e[t];if(null==o)return;const u=this.accumulatedFirstMoment[s].variable,l=this.accumulatedSecondMoment[s].variable,c=To($o(u,this.beta1),$o(o,1-this.beta1)),h=To($o(l,this.beta2),$o(Ro(o),1-this.beta2)),d=Co(c,n),p=Co(h,r);u.assign(c),l.assign(h);const f=To($o(Co(d,To(Ao(p),this.epsilon)),-this.learningRate),a);a.assign(f)}),this.accBeta1.assign($o(this.accBeta1,this.beta1)),this.accBeta2.assign($o(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&li(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedSecondMoment&&li(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e),ui(()=>{this.accBeta1.assign(Jo(this.beta1,this.iterations_+1)),this.accBeta2.assign(Jo(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}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)}}const eu=Ka({abs_:function(e){const t=Ha(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Da.runKernel(Ct,e)}{const e={x:t};return Da.runKernel(et,e)}}});function tu(e,t){const n=e.length,r=[];for(let s=0;s<n;s++){const a=n-1-s,i=e[a]||1;(t[t.length-1-s]||1)>1&&1===i&&r.unshift(a)}return r}function nu(e,t){const n=[];for(let r=0;r<t.length;r++){const s=e[e.length-r-1],a=t.length-r-1,i=t[a];(null==s||1===s&&i>1)&&n.unshift(a)}return n}function ru(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let s=0;s<n;s++){let a=e[e.length-s-1];null==a&&(a=1);let i=t[t.length-s-1];if(null==i&&(i=1),1===a)r[n-s-1]=i;else if(1===i)r[n-s-1]=a;else{if(a!==i)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);r[n-s-1]=a}}return r}const su=Ka({maximum_:function(e,t){let n=Ha(e,"a","maximum"),r=Ha(t,"b","maximum");[n,r]=Ta(n,r),"bool"===n.dtype&&(n=Io(n,"int32"),r=Io(r,"int32")),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Pn,s)}});class au extends qo{static get className(){return"Adamax"}constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],ui(()=>{this.iteration=Bo(0).variable(),this.accBeta1=Bo(t).variable()}),null==r&&(this.epsilon=Da.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);ui(()=>{const n=Zo(1,this.accBeta1),r=Co(-this.learningRate,To($o(this.iteration,this.decay),1));t.forEach((t,s)=>{const a=Da.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:_o(a).variable(i)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:`${t}/v`,variable:_o(a).variable(i)});const o=Array.isArray(e)?e[s].tensor:e[t];if(null==o)return;const u=this.accumulatedFirstMoment[s].variable,l=this.accumulatedWeightedInfNorm[s].variable,c=To($o(u,this.beta1),$o(o,1-this.beta1)),h=$o(l,this.beta2),d=eu(o),p=su(h,d);u.assign(c),l.assign(p);const f=To($o(Co(r,n),Co(c,To(p,this.epsilon))),a);a.assign(f)}),this.iteration.assign(To(this.iteration,1)),this.accBeta1.assign($o(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&li(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedWeightedInfNorm&&li(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)}}class iu extends qo{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}
5057applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const s=Da.registeredVariables[t];ui(()=>{const e=To($o(this.c,r),s);s.assign(e)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=ci(Bo(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class ou extends iu{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Bo(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Da.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:ui(()=>_o(r).variable(e))}}const s=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&ui(()=>{let e;const t=To($o(this.m,s),a);e=this.useNesterov?To($o(this.c,To(a,$o(t,this.m))),r):To($o(this.c,t),r),s.assign(t),r.assign(e)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&li(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),this.accumulations=e.map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class uu extends qo{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,null==r&&(this.epsilon=Da.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Da.registeredVariables[t],s=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:ui(()=>_o(r).variable(s))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:ui(()=>_o(r).variable(s))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:ui(()=>_o(r).variable(s))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;ui(()=>{const e=To($o(i,this.decay),$o(Ro(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,s=To($o(t,this.decay),$o(a,1-this.decay)),u=Co($o(a,this.learningRate),Ao(Zo(e,To(Ro(s),this.epsilon)))),l=To($o(o,this.momentum),u);i.assign(e),t.assign(s),o.assign(l);const c=Zo(r,l);r.assign(c)}else{const e=To($o(i,this.decay),$o(Ro(a),1-this.decay)),t=To($o(o,this.momentum),Co($o(a,this.learningRate),Ao(To(e,this.epsilon))));i.assign(e),o.assign(t);const n=Zo(r,t);r.assign(n)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&li(this.accumulatedMeanSquares.map(e=>e.variable)),null!=this.accumulatedMeanGrads&&this.centered&&li(this.accumulatedMeanGrads.map(e=>e.variable)),null!=this.accumulatedMoments&&li(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(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})))}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)}}const lu=[Ko,Yo,Qo,au,ou,uu,iu];function cu(e){return new Promise(e=>setTimeout(e)).then(e)}
5057class hu{constructor(e){if(!Xe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(hu.URL_SCHEME)&&(e=e.slice(hu.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Qa.join(e.weightData),n=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 t=Fi(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await cu(()=>s.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await cu(()=>e.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Li(e)}}}}hu.URL_SCHEME="downloads://";class du{constructor(e){if(null==e||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 n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),s=r.modelTopology;if(null==s)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:s});const a=Oi(r,e=>this.loadWeights(e));e(a)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file \'${this.jsonFile.name}\'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),s=n.map(e=>this.loadWeightsFile(e,r[e]));return Promise.all(s).then(e=>[t,e])}loadWeightsFile(e,t){return new Promise((n,r)=>{const s=new FileReader;s.onload=e=>{const t=e.target.result;n(t)},s.onerror=t=>r(`Failed to weights data from file of path \'${e}\'.`),s.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map(e=>Mi(e.name)),r={};for(const s of e)s.paths.forEach(e=>{const s=Mi(e);if(-1!==t.indexOf(s))throw new Error(`Duplicate file basename found in weights manifest: \'${s}\'`);if(t.push(s),-1===n.indexOf(s))throw new Error(`Weight file with basename \'${s}\' is not provided.`);r[e]=this.weightsFiles[n.indexOf(s)]});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 r}}function pu(e){return new du(e)}function fu(e,t,n,r){!function(e){ie(null!=e&&Array.isArray(e)&&e.length>0,()=>"promises must be a none empty array")}(e),function(e,t){ie(e>=0&&e<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`),ie(t>=0&&t<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`),ie(t>=e,()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`)}(n=null==n?0:n,r=null==r?1:r);let s=0;return Promise.all(e.map(a=>(a.then(a=>{const i=n+ ++s/e.length*(r-n);return t(i),a}),a)))}async function mu(e,t){null==t&&(t={});const n=null==t.fetchFunc?Xe().platform.fetch:t.fetchFunc,r=e.map(e=>n(e,t.requestInit,{isBinary:!0})),s=(null==t.onProgress?await Promise.all(r):await fu(r,t.onProgress,0,.5)).map(e=>e.arrayBuffer());return null==t.onProgress?await Promise.all(s):await fu(s,t.onProgress,.5,1)}async function gu(e,t="",n,r){return yu(e=>mu(e,{requestInit:r}))(e,t,n)}function yu(e){return async(t,n="",r)=>{const s=t.map(()=>!1),a={},i=null!=r?r.map(()=>!1):[],o=[];if(t.forEach((e,t)=>{let n=0;
5057e.weights.forEach(e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=Za[u]*le(e.shape),c=()=>{s[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach((t,n)=>{t===e.name&&(c(),i[n]=!0)}):c(),o.push(e.name),n+=l})}),!i.every(e=>e)){const e=r.filter((e,t)=>!i[t]);throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \\nManifest JSON has weights with names: ${o.join(", ")}.`)}const u=s.reduce((e,t,n)=>(t&&e.push(n),e),[]),l=[];u.forEach(e=>{t[e].paths.forEach(e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)})});const c=await e(l),h={};let d=0;return u.forEach(e=>{const n=t[e].paths.length,r=new Qa(c.slice(d,d+n));a[e].forEach(e=>{const t=Ii(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]}),d+=n}),h}}Pi.registerSaveRouter(e=>Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(hu.URL_SCHEME)?function(e="model"){return new hu(e)}(e.slice(hu.URL_SCHEME.length)):null);class bu{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(ie("function"==typeof t.fetchFunc,()=>"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=Xe().platform.fetch,ie(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&ie(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)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 n=Fi(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=Qa.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Li(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.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(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the \'pb2json\'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){return this.loadOptions.streamWeights?this.loadStream():Oi(await this.loadModelJSON(),e=>this.loadWeights(e))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=zi(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?Xe().platform.fetch:t.fetchFunc;let s,a=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var i;a<e.length;){if(!s){const n=(await r(e[a],t.requestInit,{isBinary:!0})).body;s=n.getReader()}const{done:o,value:u}=await s.read();if(!o)return void n.enqueue(u);a++,s=void 0,null===(i=t.onProgress)||void 0===i||i.call(t,a/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),s=this.weightPathPrefix||n,a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(s+e+r);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e);return[zi(e),await mu(t,this.loadOptions)]}}function xu(e){return null!=e.match(bu.URL_SCHEME_REGEX)}bu.URL_SCHEME_REGEX=/^https?:\\/\\//;const wu=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every(e=>xu(e)):xu(e),n)return vu(e,t)}return null};function vu(e,t){return new bu(e,t)}function ku(e,t){return vu(e,t)}Pi.registerSaveRouter(wu),Pi.registerLoadRouter(wu);class Iu{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class Su{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class Nu{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Tu(e,t,n,r){return new Nu(Eu(...arguments))}function Eu(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new Iu(e):(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 Iu({modelTopology:e})):(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 Iu({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}function Cu(e){return new Su(e)}function $u(e){return new Su(e)}const Au=Ka({matMul_:function(e,t,n=!1,r=!1){let s=Ha(e,"a","matMul"),a=Ha(t,"b","matMul");[s,a]=Ta(s,a);const i={a:s,b:a},o={transposeA:n,transposeB:r};return Da.runKernel(bt,i,o)}}),Ru=Ka({oneHot_:function(e,t,n=1,r=0,s="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:Ha(e,"indices","oneHot","int32")},i={dtype:s,depth:t,onValue:n,offValue:r};return Da.runKernel(sr,a,i)}}),_u=Ka({imag_:function(e){const t={input:Ha(e,"input","imag")};return Da.runKernel(xn,t)}}),Mu=Ka({neg_:function(e){const t={x:Ha(e,"x","neg")};return Da.runKernel(Zn,t)}}),Fu=Ka({real_:function(e){const t={input:Ha(e,"input","real")};return Da.runKernel(mr,t)}}),Du=Ka({transpose_:function(e,t,n){const r=Ha(e,"x","transpose");if(null==t&&(t=r.shape.map((e,t)=>t).reverse()),ie(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}
5057.`),t.forEach(e=>{ie(e>=0&&e<r.rank,()=>"All entries in \'perm\' must be between 0 and "+(r.rank-1)+` but got ${t}`)}),r.rank<=1)return r.clone();const s={x:r},a={perm:t};return"complex64"===r.dtype?ui(()=>{let e=Fu(r),t=_u(r);return e=Da.runKernel(os,{x:e},a),t=Da.runKernel(os,{x:t},a),n&&(t=Mu(t)),Xa(e,t)}):Da.runKernel(os,s,a)}}),Ou=Ka({confusionMatrix_:function(e,t,n){const r=Ha(e,"labels","confusionMatrix"),s=Ha(t,"predictions","confusionMatrix");ie(null==n||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),ie(1===r.rank,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),ie(1===s.rank,()=>`Expected the rank of predictions to be 1, but got ${s.rank}`),ie(r.shape[0]===s.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`),ie(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const a=Ru(Io(r,"int32"),n),i=Ru(Io(s,"int32"),n),o=Du(a),u=Au(o,i);return Io(u,"int32")}});function Lu(e,t,n){if(ue(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Ua(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ya(e,t,r,n)}let zu,Pu=!1;function Bu(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))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 ${e.constructor.name}`);o=!0}if(null!=Is(fs,Da.backendName)){const n={pixels:e},r={numChannels:t};return Da.runKernel(fs,n,r)}const[u,l]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(a||s||o){if(null==zu)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");zu=new OffscreenCanvas(1,1).getContext("2d")}else zu=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});zu.canvas.width=u,zu.canvas.height=l,zu.drawImage(e,0,0,u,l),c=zu.getImageData(0,0,u,l).data}if(4===t)h=new Int32Array(c);else{const e=u*l;h=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)h[n*t+e]=c[4*n+e]}return Lu(h,[l,u,t],"int32")}async function Vu(e,t=3){let n=null;if(Xe().getBool("WRAP_TO_IMAGEBITMAP")&&function(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return Bu(n,t)}function Uu(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}async function Wu(e,t){let n=Ha(e,"img","toPixels");if(!(e instanceof pa)){const e=n;n=Io(e,"int32"),e.dispose()}Uu(n);const[r,s]=n.shape.slice(0,2),a=2===n.rank?1:n.shape[2],i=await n.data(),o="float32"===n.dtype?255:1,u=new Uint8ClampedArray(s*r*4);for(let e=0;e<r*s;++e){const t=[0,0,0,255];for(let r=0;r<a;r++){const s=i[e*a+r];
vendor: 9,593 bytes, line 5057
5057if("float32"===n.dtype){if(s<0||s>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===n.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===a?(t[0]=s*o,t[1]=s*o,t[2]=s*o):t[r]=s*o}const r=4*e;u[r+0]=Math.round(t[0]),u[r+1]=Math.round(t[1]),u[r+2]=Math.round(t[2]),u[r+3]=Math.round(t[3])}if(null!=t){Pu||null!=Is(Yt,Da.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Pu=!0),t.width=s,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,s,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}function Gu(e,t,n){let r=Ha(e,"img","draw");if(!(e instanceof pa)){const e=r;r=Io(e,"int32"),e.dispose()}Uu(r),function(e){const t=(null==e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null==n?void 0:n.imageOptions);const s={image:r},a={canvas:t,options:n};Da.runKernel(Yt,s,a)}const Hu=Ka({fromPixels_:Bu});function ju(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===le(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,a=s[s.length-1];let i=1;for(let e=0;e<s.length-1;++e)i*=s[e];const o=e.shape,u=s.slice();u.pop();let l=1;for(let e=a;e<n;++e)l*=o[e],u.push(o[e]);const c=[...De(e.shape).map(e=>e/l),1].slice(0,a);return[u,i,l,c]}function qu(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank<s)throw new Error(a+` update.rank < ${s}. `);if(e.length<r+(n.rank-s))throw new Error(a+` Output shape length < ${r+(n.rank-s)}`);if(n.rank!==s+e.length-r)throw new Error(a+" update.rank != "+(s+e.length-r));for(let e=0;e<s;++e)if(n.shape[e]!==t.shape[e])throw new Error(a+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-s;++t)if(n.shape[t+s]!==e[t+r])throw new Error(a+` updates.shape[${t+s}] (${n.shape[t+s]}) != shape[${t+s}] (${e[t+s]})`)}function Ku(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of \'indices\' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}qu(n,t,e)}function Xu(e,t,n){const r=t.shape.length,s=r>1?t.shape[r-1]:1,a=n.length;let i=1;for(let e=s;e<a;++e)i*=n[e];const o=s<1?1:s;return{sliceRank:s,numUpdates:le(t.shape)/o,sliceSize:i,strides:[...De(n.slice(0,s)),1],outputSize:le(n)}}const Yu=-2,Ju=-1;function Zu(e,t,n){const r=e.shape.length;ie(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),ie(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let s=0;s<r;++s)ie(t[s]+n[s]<=e.shape[s],()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`)}function Qu(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function el(e,t,n){const r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}function tl(e,t,n,r){const s=[...e];for(let e=s.length;e<r.length;e++)s.push(1);for(let e=0;e<n;e++)0===e?s[t]=1:(s.splice(t,0,1),s.pop());return s}function nl(e,t,n){return n<=e?n:n-(t-1)}function rl(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function sl(e,t,n,r,s,a,i,o,u){const l=e.length;let c=new Array(l),h=new Array(l),d=new Array(l);if(t.length&&n>0){const u=t[0],l=n+1;c=al(i,u,l,r,e),h=il(o,u,l,s,e),d=tl(a,u,l,e)}else for(let t=0;t<l;t++)c[t]=ul(i,r,a,e,t,u),h[t]=ll(o,s,a,e,t,u),d[t]=ol(a,t,u);return{begin:c,end:h,strides:d}}function al(e,t,n,r,s){const a=[...s],i=rl(n,t);for(let s=0;s<a.length;s++)if(i.indexOf(s)>-1)a[s]=0;else{const i=nl(t,n,s);let o=r[i];e&1<<i&&(o=0),a[s]=o}return a}function il(e,t,n,r,s){const a=[...s],i=rl(n,t);for(let s=0;s<a.length;s++)if(i.indexOf(s)>-1)a[s]=Number.MAX_SAFE_INTEGER;else{const i=nl(t,n,s);let o=r[i];e&1<<i&&(o=Number.MAX_SAFE_INTEGER),a[s]=o}for(let e=0;e<a.length;e++){const t=s[e];a[e]<0&&(a[e]+=t),a[e]=ee(0,a[e],s[e])}return a}function ol(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function ul(e,t,n,r,s,a){let i=t[s];const o=n[s]||1;(e&1<<s||a&1<<s||null==i)&&(i=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=ee(0,i,u-1),i}function ll(e,t,n,r,s,a){let i=t[s];const o=n[s]||1;(e&1<<s||a&1<<s||null==i)&&(i=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=o>0?ee(0,i,u):ee(-1,i,u-1),i}function cl(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0}function hl(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function dl(e,t,n){let r;const s=e.shape.length;let a;return r="number"==typeof t?[t,...new Array(s-1).fill(0)]:t.length<s?t.concat(new Array(s-t.length).fill(0)):t.slice(),r.forEach(e=>{ie(-1!==e,()=>"slice() does not support negative begin indexing.")}),a=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.length<s?n.concat(new Array(s-n.length).fill(-1)):n,a=a.map((t,n)=>t>=0?t:(ie(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,a]}function pl(e,t,n,r,s,a,i,o,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=i&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};for(let e=0;e<h.dims;e++)c&&1<<e&o&&h.numAddAxisAfterEllipsis++,1<<e&i&&(c=!0);c||(h.ellipsisMask|=1<<h.dims,h.dims++);const d={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const s=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<s;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(Yu),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(Ju),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(h,d);let p=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===d.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(d.shrinkAxisMask&1<<t),r=e[t];if(-1===r){g.push(n?1:-1);continue}const s=[d.beginMask&1<<t,d.endMask&1<<t],a=[d.strides[t]>0?0:-1,d.strides[t]>0?r:r-1];if(n&&d.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===d.strides[t];const i=!!(d.beginMask&1<<t&&d.endMask&1<<t);if(d.beginValid&&d.endValid){if(n){const e=d.begin[t]<0?r+d.begin[t]:d.begin[t];if(d.begin[t]=e,d.end[t]=d.begin[t]+1,e<0||e>=r)throw Error(`slice index ${d.begin[t]} of dimension ${t} out of bounds.`)}else d.begin[t]=fl(d.begin[t],0,d.strides[t],r,s,a),d.end[t]=fl(d.end[t],1,d.strides[t],r,s,a);const e=1===d.strides[t]&&0===d.begin[t]&&d.end[t]===r;p=p&&e,f=f&&(0===t&&1===d.strides[t]||e)}else p=p&&1===d.strides[t]&&i,f=f&&(0===t&&1===d.strides[t]||i);let o,u=!1;if(d.beginValid&&d.endValid?(o=d.end[t]-d.begin[t],u=!0):n?(o=1,u=!0):i&&r>=0&&(o=d.strides[t]<0?-r:r,u=!0),u){let e;e=0===o||o<0!=d.strides[t]<0?0:Math.trunc(o/d.strides[t])+(o%d.strides[t]!==0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<d.finalShapeGatherIndices.length;++e){const t=d.finalShapeGatherIndices[e];t>=0?y.push(g[t]):t===Yu&&y.push(1)}return{finalShapeSparse:y.filter((e,t)=>
5057d.finalShapeGatherIndices[t]!==Yu),finalShape:y,isIdentity:p,sliceDim0:f,isSimpleSlice:m,begin:d.begin,end:d.end,strides:d.strides}}function fl(e,t,n,r,s,a){if(s[t])return n>0?a[t]:a[t+1&1];{const t=e<0?r+e:e;return t<a[0]?a[0]:t>a[1]?a[1]:t}}const ml=.001,gl=.1;function yl(e,t,n){return null==n&&(n=bl()),xl(e,t,(e,t)=>Il(e,t,n))}function bl(){return 32===Da.backend.floatPrecision()?ml:gl}function xl(e,t,n){let r=!0;if((Qs(e)||Qs(t))&&(r=!1),Qs(e)&&Qs(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${r}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=Ua(e),r=Ua(t);if(!de(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const s=Qs(e)?e:ea(e),a=Qs(t)?t:ea(t);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.\\nActual:   ${s}.\\nExpected: ${a}.`);for(let e=0;e<a.length;++e){const t=s[e],r=a[e];if(!n(t,r))throw new Error(`Arrays differ: actual[${e}] = ${t}, expected[${e}] = ${r}.\\nActual:   ${s}.\\nExpected: ${a}.`)}"undefined"!=typeof expect&&expect().nothing()}function wl(e,t){e().then(()=>t.fail(),()=>t()),"undefined"!=typeof expect&&expect().nothing()}function vl(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return $e(e)||$e(e[0])||$e(t)||$e(t[0])?xl(e,n,(e,t)=>e==t):xl(e,t,(e,t)=>Il(e,t,0))}function kl(e,t,n){if(null==n&&(n=bl()),!Il(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()}function Il(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function Sl(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function Nl(e,t){const n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let e=0;e<r.length;e++)if(n[e]!==r[e])throw new Error(`Expected ArrayBuffer value at ${e} to be ${r[e]} but got ${n[e]} instead`)}function Tl(e){for(let t=0;t<e.length;t++){const n=e[t];Array.isArray(n)?Tl(n):e[t]=Js(n)}return e}function El(e){const t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise(e=>{t.addEventListener("loadeddata",n=>e(t)),t.load()})}async function Cl(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}const $l="4.22.0";class Al{static sgd(e){return new iu(e)}static momentum(e,t,n=!1){return new ou(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new uu(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new Qo(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Ko(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new au(e,t,n,r,s)}static adagrad(e,t=.1){return new Yo(e,t)}}const Rl=Ka({acos_:function(e){const t={x:Ha(e,"x","acos")};return Da.runKernel(tt,t)}}),_l=Ka({acosh_:function(e){const t={x:Ha(e,"x","acosh")};return Da.runKernel(nt,t)}}),Ml=Ka({addN_:function(e){ie(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),ie(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((e,t)=>Ha(e,`tensors${t}`,"addN")),n=t[0];t.forEach(e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(e=>{if(!de(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=t;return Da.runKernel(st,r)}}),Fl=Ka({all_:function(e,t=null,n=!1){const r={x:Ha(e,"x","all","bool")},s={axis:t,keepDims:n};return Da.runKernel(at,r,s)}}),Dl=Ka({any_:function(e,t=null,n=!1){const r={x:Ha(e,"x","any","bool")},s={axis:t,keepDims:n};return Da.runKernel(it,r,s)}}),Ol=Ka({argMax_:function(e,t=0){const n={x:Ha(e,"x","argMax")},r={axis:t};return Da.runKernel(ot,n,r)}}),Ll=Ka({argMin_:function(e,t=0){const n={x:Ha(e,"x","argMin")},r={axis:t};return Da.runKernel(ut,n,r)}}),zl=Ka({asin_:function(e){const t={x:Ha(e,"x","asin")};return Da.runKernel(lt,t)}}),Pl=Ka({asinh_:function(e){const t={x:Ha(e,"x","asinh")};return Da.runKernel(ct,t)}}),Bl=Ka({atan_:function(e){const t={x:Ha(e,"x","atan")};return Da.runKernel(ht,t)}}),Vl=Ka({atan2_:function(e,t){let n=Ha(e,"a","atan2"),r=Ha(t,"b","atan2");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(pt,s)}}),Ul=Ka({atanh_:function(e){const t={x:Ha(e,"x","atanh")};return Da.runKernel(dt,t)}});function Wl(e,t,n,r,s="NHWC",a){return jl(e,[...t,e[3]],n,a,r,null,null,nc(s))}function Gl(e,t,n,r,s,a,i="channelsLast"){const[o,u]=Xl(t);let l;if("channelsLast"===i)l=[o,u,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);l=[o,u,e[1],e[1]]}return jl(e,l,n,r,s,a,!1,i)}function Hl(e,t,n,r,s,a,i="NDHWC"){const[o,u,l]=Yl(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,u,l,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,u,l,e[1],e[1]]}return ql(e,c,n,r,s,!1,h,a)}function jl(e,t,n,r,s,a,i=!1,o="channelsLast"){let[u,l,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,h,l,c]=e}
vendor: 4,359 bytes, line 5057
5057const[d,p,,f]=t,[m,g]=Xl(n),[y,b]=Xl(r),x=Jl(d,y),w=Jl(p,b),{padInfo:v,outHeight:k,outWidth:I}=function(e,t,n,r,s,a,i,o,u){let l,c,h;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=Kl(e,t,n));const a=e[1];return[Zl((e[0]-t+2*r)/n+1,s),Zl((a-t+2*r)/n+1,s)]}([t,n],a,r,e,o);c=s[0],h=s[1]}else if("same"===e){c=Math.ceil(t/r),h=Math.ceil(n/s);const e=Math.max(0,(c-1)*r+a-t),o=Math.max(0,(h-1)*s+i-n),u=Math.floor(e/2),d=e-u,p=Math.floor(o/2);l={top:u,bottom:d,left:p,right:o-p,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/r),h=Math.ceil((n-i+1)/s);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const d="channelsLast"===u?e[1][0]:e[2][0],p="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:d,bottom:p,left:f,right:m,type:0===d&&0===p&&0===f&&0===m?"VALID":"EXPLICIT"},c=Zl((t-a+d+p)/r+1,o),h=Zl((n-i+f+m)/s+1,o)}}return{padInfo:l,outHeight:c,outWidth:h}}(s,l,c,m,g,x,w,a,o),S=i?f*h:f;let N;return"channelsFirst"===o?N=[u,S,k,I]:"channelsLast"===o&&(N=[u,k,I,S]),{batchSize:u,dataFormat:o,inHeight:l,inWidth:c,inChannels:h,outHeight:k,outWidth:I,outChannels:S,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:p,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:N,filterShape:t}}function ql(e,t,n,r,s,a=!1,i="channelsLast",o){let[u,l,c,h,d]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,h,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,d,l,c,h]=e}const[p,f,m,,g]=t,[y,b,x]=Yl(n),[w,v,k]=Yl(r),I=Jl(p,w),S=Jl(f,v),N=Jl(m,k),{padInfo:T,outDepth:E,outHeight:C,outWidth:$}=function(e,t,n,r,s,a,i,o,u,l,c){let h,d,p,f;if("valid"===e&&(e=0),"number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,s,a){null==s&&(s=Kl(e,t[0],r[0]));const i=[0,0,0,1];for(let n=0;n<3;n++)e[n]+2*s>=t[n]&&(i[n]=Zl((e[n]-t[n]+2*s)/r[n]+1,a));return i}([t,n,r,1],[o,u,l],0,[s,a,i],e,c);d=m[0],p=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{d=Math.ceil(t/s),p=Math.ceil(n/a),f=Math.ceil(r/i);const e=(d-1)*s+o-t,c=(p-1)*a+u-n,m=(f-1)*i+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}}return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}(s,l,c,h,y,b,x,I,S,N,o),A=a?g*d:g;let R;return"channelsFirst"===i?R=[u,A,E,C,$]:"channelsLast"===i&&(R=[u,E,C,$,A]),{batchSize:u,dataFormat:i,inDepth:l,inHeight:c,inWidth:h,inChannels:d,outDepth:E,outHeight:C,outWidth:$,outChannels:A,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:S,effectiveFilterWidth:N,dilationDepth:w,dilationHeight:v,dilationWidth:k,inShape:e,outShape:R,filterShape:t}}function Kl(e,t,n,r=1){const s=Jl(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function Xl(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Yl(e){return"number"==typeof e?[e,e,e]:e}function Jl(e,t){return t<=1?e:e+(e-1)*(t-1)}function Zl(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Ql(e){const[t,n,r]=Xl(e);return 1===t&&1===n&&1===r}function ec(e,t){return Ql(e)||Ql(t)}function tc(e){return Xl(e).every(e=>e>0)}function nc(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function rc(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)ie(pe(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach(t=>{t.forEach(t=>{ie(pe(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`)})})}}}const sc=Ka({reshape_:function(e,t){const n={x:Ha(e,"x","reshape","string_or_numeric")},r={shape:t};return Da.runKernel(br,n,r)}}
5057),ac=Ka({avgPool_:function(e,t,n,r,s){const a=Ha(e,"x","avgPool","float32");ie(ec(n,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations \'1\'`);let i=a,o=!1;3===a.rank&&(o=!0,i=sc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),rc("avgPool",r,s);const u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let c=Da.runKernel(ft,u,l);return c=Io(c,a.dtype),o?sc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),ic=Ka({avgPool3d_:function(e,t,n,r,s,a="NDHWC"){const i=Ha(e,"x","avgPool3d","float32");let o=i,u=!1;4===i.rank&&(u=!0,o=sc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),ie("NDHWC"===a,()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),ie("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got \'${n}\'`),rc("avgPool3d",r,s);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a};let h=Da.runKernel(gt,l,c);return h=Io(h,o.dtype),u?sc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),oc=Ka({concat_:function(e,t=0){ie(e.length>=1,()=>"Pass at least one tensor to concat");const n=ja(e,"tensors","concat","string_or_numeric");
5057if("complex64"===n[0].dtype&&n.forEach(e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\\n          with dtype ${e.dtype}. `)}),1===n.length)return So(n[0]);const r=n,s={axis:t};return Da.runKernel($t,r,s)}}),uc=Ka({sigmoid_:function(e){const t={x:Ha(e,"x","sigmoid","float32")};return Da.runKernel(Or,t)}}),lc=Ka({slice_:function(e,t,n){const r=Ha(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},a={begin:t,size:n};return Da.runKernel(_r,s,a)}}),cc=Ka({tanh_:function(e){const t={x:Ha(e,"x","tanh","float32")};return Da.runKernel(rs,t)}}),hc=Ka({basicLSTMCell_:function(e,t,n,r,s,a){const i=Ha(e,"forgetBias","basicLSTMCell"),o=Ha(t,"lstmKernel","basicLSTMCell"),u=Ha(n,"lstmBias","basicLSTMCell"),l=Ha(r,"data","basicLSTMCell"),c=Ha(s,"c","basicLSTMCell"),h=Ha(a,"h","basicLSTMCell"),d=oc([l,h],1),p=Au(d,o),f=To(p,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=lc(f,[0,0],y),x=lc(f,[0,g],y),w=lc(f,[0,2*g],y),v=lc(f,[0,3*g],y),k=To($o(uc(b),cc(x)),$o(c,uc(To(i,w))));return[k,$o(cc(k),uc(v))]}}),dc=Ka({batchToSpaceND_:function(e,t,n){const r=Ha(e,"x","batchToSpaceND"),s=t.reduce((e,t)=>e*t);ie(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),ie(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length  ${t.length}`),ie(r.shape[0]%s===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);const a={x:r},i={blockShape:t,crops:n};return Da.runKernel(xt,a,i)}}),pc=Ka({batchNorm_:function(e,t,n,r,s,a){null==a&&(a=.001);const i=Ha(e,"x","batchNorm"),o=Ha(t,"mean","batchNorm"),u=Ha(n,"variance","batchNorm");let l,c;null!=s&&(l=Ha(s,"scale","batchNorm")),null!=r&&(c=Ha(r,"offset","batchNorm")),ie(o.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),ie(null==c||o.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),ie(null==l||o.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h={x:function(e){let t;return t=0===e.rank||1===e.rank?sc(e,[1,1,1,e.size]):2===e.rank?sc(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?sc(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:l,offset:c,mean:o,variance:u},d={varianceEpsilon:a},p=Da.runKernel(dn,h,d);return sc(p,i.shape)}}),fc=Ka({batchNorm2d_:function(e,t,n,r,s,a){const i=Ha(e,"x","batchNorm"),o=Ha(t,"mean","batchNorm"),u=Ha(n,"variance","batchNorm");let l,c;return null!=s&&(l=Ha(s,"scale","batchNorm")),null!=r&&(c=Ha(r,"offset","batchNorm")),ie(2===i.rank,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),ie(2===o.rank||1===o.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),ie(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),null!=l&&ie(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),null!=c&&ie(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),pc(i,o,u,c,l,a)}}),mc=Ka({batchNorm3d_:function(e,t,n,r,s,a){const i=Ha(e,"x","batchNorm"),o=Ha(t,"mean","batchNorm"),u=Ha(n,"variance","batchNorm");let l,c;return null!=s&&(l=Ha(s,"scale","batchNorm")),null!=r&&(c=Ha(r,"offset","batchNorm")),ie(3===i.rank,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),ie(3===o.rank||1===o.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),ie(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`),null!=l&&ie(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),null!=c&&ie(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),pc(i,o,u,c,l,a)}}),gc=Ka({batchNorm4d_:function(e,t,n,r,s,a){const i=Ha(e,"x","batchNorm"),o=Ha(t,"mean","batchNorm"),u=Ha(n,"variance","batchNorm");let l,c;return null!=s&&(l=Ha(s,"scale","batchNorm")),null!=r&&(c=Ha(r,"offset","batchNorm")),ie(4===i.rank,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}
5057.`),ie(4===o.rank||1===o.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),ie(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`),null!=l&&ie(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`),null!=c&&ie(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),pc(i,o,u,c,l,a)}}),yc=Ka({bincount_:function(e,t,n){const r=Ha(e,"x","bincount"),s=Ha(t,"weights","bincount");ie("int32"===r.dtype,()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),ie(n>=0,()=>`size must be non-negative, but got ${n}.`),ie(s.size===r.size||0===s.size,()=>`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},i={size:n};return Da.runKernel(wt,a,i)}}),bc=Ka({bitwiseAnd_:function(e,t){const n=Ha(e,"x","bitwiseAnd"),r=Ha(t,"y","bitwiseAnd");if(!de(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports \'int32\' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const s={a:n,b:r};return Da.runKernel(vt,s)}}),xc=Ka({broadcastArgs_:function(e,t){const n=Ha(e,"s0","broadcastArgs","int32"),r=Ha(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const s={s0:n,s1:r};return Da.runKernel(It,s)}}),wc=Ka({broadcastTo_:function(e,t){let n=Ha(e,"broadcastTo","x");const r=n.shape;if(Ue(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=sc(n,e)}const s=n.shape,a=Array.from(t);for(let e=t.length-1;e>=0;e--)if(s[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===a.map((e,t)=>e>1?t:-1).filter(e=>e>=0).length)return So(n);const i={x:n},o={reps:a};return Da.runKernel(ss,i,o)}}),vc=Ka({ceil_:function(e){const t={x:Ha(e,"x","ceil","float32")};return Da.runKernel(Nt,t)}}),kc=Ka({clipByValue_:function(e,t,n){const r=Ha(e,"x","clipByValue");if(ie(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return Xo(r.shape,t,r.dtype);const s={x:r},a={clipValueMin:t,clipValueMax:n};return Da.runKernel(Tt,s,a)}}),Ic=Ka({concat1d_:function(e){return oc(e,0)}}),Sc=Ka({concat2d_:function(e,t){return oc(e,t)}}),Nc=Ka({concat3d_:function(e,t){return oc(e,t)}}),Tc=Ka({concat4d_:function(e,t){return oc(e,t)}}),Ec=Ka({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=Ha(e,"x","conv2d","float32"),u=Ha(t,"filter","conv2d","float32");let l=o,c=!1;3===o.rank&&(c=!0,l=sc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===l.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`),ie(4===u.rank,()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`),rc("conv2d",r,i);const h="NHWC"===s?l.shape[3]:l.shape[1];ie(h===u.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${u.shape[2]}.`),ie(ec(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations \'${a}\'`),ie(tc(a),()=>"Error in conv2D: Dilated rates should be larger than 0."),ie(tc(n),()=>"Error in conv2D: Strides should be larger than 0.");const d={x:l,filter:u},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=Da.runKernel(At,d,p);return c?sc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Cc=Ka({conv1d_:function(e,t,n,r,s="NWC",a=1,i){const o=Ha(e,"x","conv1d"),u=Ha(t,"filter","conv1d");let l=o,c=!1;2===o.rank&&(c=!0,l=sc(o,[1,o.shape[0],o.shape[1]])),ie(3===l.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`),ie(3===u.rank,()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`),rc("conv1d",r,i),ie(l.shape[2]===u.shape[1],()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`),ie(ec(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation \'${a}\'`),ie(tc(a),()=>"Error in conv1D: Dilated rates should be larger than 0."),ie(tc(n),()=>"Error in conv1D: Stride should be larger than 0."),ie("NWC"===s,()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);const h=sc(u,[1,u.shape[0],u.shape[1],u.shape[2]]),d=sc(l,[l.shape[0],1,l.shape[1],l.shape[2]]),p=Ec(d,h,[1,n],r,"NHWC",[1,a],i);return sc(p,c?[p.shape[2],p.shape[3]]:[p.shape[0],p.shape[2],p.shape[3]])}}),$c=Ka({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",i){ie(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,u=t,l=!1;3===t.rank&&(l=!0,u=sc(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),ie(4===o.length,()=>
5057`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),ie(4===u.rank,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`),ie(4===n.rank,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const c="NHWC"===a?o[3]:o[1],h="NHWC"===a?u.shape[3]:u.shape[1];ie(c===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`),ie(h===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`),rc("conv2dDerInput",s,i);const d={dy:u,filter:n},p={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:o},f=Da.runKernel(_t,d,p);return l?sc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Ac=Ka({conv2dTranspose_:function(e,t,n,r,s,a){const i=Ha(e,"x","conv2dTranspose"),o=Ha(t,"filter","conv2dTranspose");return $c(n,i,o,r,s,"NHWC",a)}}),Rc=Ka({conv3d_:function(e,t,n,r,s="NDHWC",a=[1,1,1]){const i=Ha(e,"x","conv3d"),o=Ha(t,"filter","conv3d");let u=i,l=!1;4===i.rank&&(l=!0,u=sc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===u.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`),ie(5===o.rank,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),ie(u.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${o.shape[3]}.`),ie(ec(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations \'${a}\'`),ie("NDHWC"===s,()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`),ie(tc(a),()=>"Error in conv3D: Dilated rates should be larger than 0."),ie(tc(n),()=>"Error in conv3D: Strides should be larger than 0.");const c={x:u,filter:o},h={strides:n,pad:r,dataFormat:s,dilations:a},d=Da.runKernel(Mt,c,h);return l?sc(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),_c=Ka({conv3DBackpropInput_:function(e,t,n,r,s){ie(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,i=t,o=!1;4===t.rank&&(o=!0,i=sc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const u=a[4],l=i.shape[4];ie(5===a.length,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),ie(5===i.rank,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),ie(5===n.rank,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),ie(u===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`),ie(l===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`);const c={dy:i,filter:n},h={pad:s,strides:r,inputShape:a},d=Da.runKernel(Dt,c,h);return o?sc(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),Mc=Ka({conv3dTranspose_:function(e,t,n,r,s){const a=Ha(e,"x","conv3dTranspose"),i=Ha(t,"filter","conv3dTranspose");return _c(n,a,i,r,s)}}),Fc=Ka({cos_:function(e){const t={x:Ha(e,"x","cos","float32")};return Da.runKernel(Ot,t)}}),Dc=Ka({cosh_:function(e){const t={x:Ha(e,"x","cosh","float32")};return Da.runKernel(Lt,t)}}),Oc=Ka({cumprod_:function(e,t=0,n=!1,r=!1){const s={x:Ha(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:r};return Da.runKernel(zt,s,a)}}),Lc=Ka({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:Ha(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:r};return Da.runKernel(Pt,s,a)}}),zc=Ka({denseBincount_:function(e,t,n,r=!1){const s=Ha(e,"x","denseBincount"),a=Ha(t,"weights","denseBincount");ie("int32"===s.dtype,()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`),ie(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),ie(n>=0,()=>`size must be non-negative, but got ${n}.`),ie(a.size===s.size||0===a.size,()=>`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 i={x:s,weights:a},o={size:n,binaryOutput:r};return Da.runKernel(Vt,i,o)}}),Pc=Ka({depthToSpace_:function(e,t,n="NHWC"){const r=Ha(e,"x","depthToSpace","float32"),s="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];ie(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),ie(s*t>=0,()=>
vendor: 4,462 bytes, line 5057
5057`Negative dimension size caused by overflow when multiplying\\n    ${s} and ${t}  for depthToSpace with input shape\\n    ${r.shape}`),ie(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying\\n    ${a} and ${t} for depthToSpace with input shape\\n        ${r.shape}`),ie(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${r.shape}`);const o={x:r},u={blockSize:t,dataFormat:n};return Da.runKernel(Ut,o,u)}}),Bc=Ka({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=Ha(e,"x","depthwiseConv2d","float32"),u=Ha(t,"filter","depthwiseConv2d","float32");let l=o,c=!1;3===o.rank&&(c=!0,l=sc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===l.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),ie(4===u.rank,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`);const h="NHWC"===s?l.shape[3]:l.shape[1];ie(h===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${u.shape[2]}.`),rc("depthwiseConv2d",r,i);const d={x:l,filter:u},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=Da.runKernel(Wt,d,p);return c?sc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Vc=Ka({diag_:function(e){const t={x:Ha(e,"x","diag")};return Da.runKernel(jt,t)}}),Uc=Ka({dilation2d_:function(e,t,n,r,s=[1,1],a="NHWC"){const i=Ha(e,"x","dilation2d"),o=Ha(t,"filter","dilation2d");ie(3===i.rank||4===i.rank,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),ie(3===o.rank,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),ie("NHWC"===a,()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let u=i,l=!1;3===i.rank&&(u=sc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0),ie(u.shape[3]===o.shape[2],()=>`Error in dilation2d:  input and filter must have the same depth: ${u.shape[3]} vs ${o.shape[2]}`);const c={x:u,filter:o},h={strides:n,pad:r,dilations:s},d=Da.runKernel(qt,c,h);return l?sc(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),Wc=Ka({equal_:function(e,t){let n=Ha(e,"a","equal","string_or_numeric"),r=Ha(t,"b","equal","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(nn,s)}}),Gc=Ka({where_:function(e,t,n){const r=Ha(t,"a","where"),s=Ha(n,"b","where"),a=Ha(e,"condition","where","bool"),i=ru(ru(a.shape,r.shape),s.shape),o={condition:wc(a,i),t:wc(r,i),e:wc(s,i)};return Da.runKernel(Ar,o)}}),Hc=Ka({divNoNan_:function(e,t){let n=Ha(e,"a","div"),r=Ha(t,"b","div");[n,r]=Ta(n,r);const s=Co(n,r),a=_o(s),i=Wc(r,a);return Gc(i,a,s)}}),jc=Ka({dot_:function(e,t){const n=Ha(e,"t1","dot"),r=Ha(t,"t2","dot");ie(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const s=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];if(ie(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),1===n.rank&&1===r.rank){const e=sc(n,[1,-1]),t=sc(r,[-1,1]),s=Au(e,t);return sc(s,[])}if(1===n.rank&&2===r.rank){const e=sc(n,[1,-1]),t=sc(r,[r.shape[0],r.shape[1]]),s=Au(e,t);return sc(s,[s.size])}if(2===n.rank&&1===r.rank){const e=sc(r,[-1,1]),t=Au(n,e);return sc(t,[t.size])}{const e=sc(r,[r.shape[0],r.shape[1]]);return Au(n,e)}}}),qc=Ka({einsum_:function(e,...t){const n=t.map((e,t)=>Ha(e,`tensors${t}`,"einsum")),r={equation:e};return Da.runKernel(Zt,n,r)}}),Kc=Ka({elu_:function(e){const t={x:Ha(e,"x","elu","float32")};return Da.runKernel(Qt,t)}}),Xc=Ka({ensureShape_:function(e,t){const n=Ha(e,"x","ensureShape","string_or_numeric");if(!he(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}}),Yc=Ka({erf_:function(e){let t=Ha(e,"x","erf");ie("int32"===t.dtype||"float32"===t.dtype,()=>"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=Io(t,"float32"));const n={x:t};return Da.runKernel(tn,n)}});function Jc(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Zc(e,t,n){const r=e.length+t.length,s=[];let a=0,i=0;for(let o=0;o<r;o++)-1===n.indexOf(o)?s.push(e[a++]):s.push(t[i++]);return s}function Qc(e,t){const n=[],r=e.length;for(let s=0;s<r;s++)-1===t.indexOf(s)&&n.push(e[s]);return[n,t.map(t=>e[t])]}function eh(e,t){return Zc(e,t.map(e=>1),t)}function th(e,t,n){ie(Jc(t,n),()=>`${e}
5057 supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function nh(e,t){if(Jc(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach(e=>n.push(e)),n}function rh(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function sh(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const ah=Ka({max_:function(e,t=null,n=!1){const r={x:Ha(e,"x","max")},s={reductionIndices:t,keepDims:n};return Da.runKernel(zn,r,s)}}),ih=Ka({min_:function(e,t=null,n=!1){const r={x:Ha(e,"x","min")},s={axis:t,keepDims:n};return Da.runKernel(jn,r,s)}}),oh=Ka({sum_:function(e,t=null,n=!1){let r=Ha(e,"x","sum");"bool"===r.dtype&&(r=Io(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Da.runKernel(Pr,s,a)}});function uh(e,t,n=null){if(0===e.rank)return eu(e);if(1!==e.rank&&null===n)return uh(sc(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return oh(eu(e),n);if(t===1/0)return ah(eu(e),n);if(t===-1/0)return ih(eu(e),n);if("euclidean"===t||2===t)return Ao(oh(Jo(eu(e),Bo(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return ah(oh(eu(e),n[0]),n[1]-1);if(t===1/0)return ah(oh(eu(e),n[1]),n[0]);if(t===-1/0)return ih(oh(eu(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Ao(oh(Ro(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const lh=Ka({norm_:function(e,t="euclidean",n=null,r=!1){const s=uh(e=Ha(e,"x","norm"),t,n);let a=s.shape;if(r){const t=we(n,e.shape);a=eh(s.shape,t)}return sc(s,a)}}),ch=Ka({euclideanNorm_:function(e,t=null,n=!1){return lh(e,"euclidean",t,n)}}),hh=Ka({exp_:function(e){const t={x:Ha(e,"x","exp")};return Da.runKernel(rn,t)}}),dh=Ka({expandDims_:function(e,t=0){const n=Ha(e,"x","expandDims","string_or_numeric");ie(t<=n.rank,()=>"Axis must be <= rank of the tensor");const r={input:n},s={dim:t};return Da.runKernel(sn,r,s)}}),ph=Ka({expm1_:function(e){const t={x:Ha(e,"x","expm1")};return Da.runKernel(an,t)}}),fh=Ka({tile_:function(e,t){const n=Ha(e,"x","tile","string_or_numeric");ie(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const r={x:n},s={reps:t};return Da.runKernel(ss,r,s)}}),mh=Ka({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=ko([e,t],r),a=e<=t?e:t;for(let e=0;e<a;++e)s.set(1,e,e);const i=sc(s.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return fh(dh(i,0),[n[0],1,1]);if(2===n.length)return fh(dh(dh(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return fh(dh(dh(dh(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}}),gh=Ka({floor_:function(e){const t={x:Ha(e,"x","floor","float32")};return Da.runKernel(cn,t)}}),yh=Ka({gather_:function(e,t,n=0,r=0){const s={x:Ha(e,"x","gather"),indices:Ha(t,"indices","gather","int32")},a={axis:n,batchDims:r};return Da.runKernel(pn,s,a)}}),bh=Ka({greater_:function(e,t){let n=Ha(e,"a","greater","string_or_numeric"),r=Ha(t,"b","greater","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(mn,s)}}),xh=Ka({greaterEqual_:function(e,t){let n=Ha(e,"a","greaterEqual","string_or_numeric"),r=Ha(t,"b","greaterEqual","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(gn,s)}}),wh=Ka({isFinite_:function(e){const t={x:Ha(e,"x","isFinite")};return Da.runKernel(wn,t)}}),vh=Ka({isInf_:function(e){const t={x:Ha(e,"x","isInf")};return Da.runKernel(vn,t)}}),kh=Ka({isNaN_:function(e){const t={x:Ha(e,"x","isNaN")};return Da.runKernel(kn,t)}}),Ih=Ka({leakyRelu_:function(e,t=.2){const n={x:Ha(e,"x","leakyRelu")},r={alpha:t};return Da.runKernel(In,n,r)}}),Sh=Ka({less_:function(e,t){let n=Ha(e,"a","less","string_or_numeric"),r=Ha(t,"b","less","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Sn,s)}}),Nh=Ka({lessEqual_:function(e,t){let n=Ha(e,"a","lessEqual","string_or_numeric"),r=Ha(t,"b","lessEqual","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Nn,s)}});function Th(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return Da.runKernel(Tn,{},r)}const Eh=Ka({localResponseNormalization_:function(e,t=5,n=1,r=1,s=.5){const a=Ha(e,"x","localResponseNormalization");ie(4===a.rank||3===a.rank,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\\n               rank ${a.rank}.`),ie(pe(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=a,o=!1;3===a.rank&&(o=!0,i=sc(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={x:i},l={depthRadius:t,bias:n,alpha:r,beta:s},c=Da.runKernel(Dn,u,l);return o?sc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Ch=Ka({log_:function(e){const t={x:Ha(e,"x","log","float32")};return Da.runKernel(En,t)}}),$h=Ka({log1p_:function(e){const t={x:Ha(e,"x","log1p")};return Da.runKernel(Cn,t)}}),Ah=Ka({softplus_:function(e){const t={x:Ha(e,"x","softplus")};return Da.runKernel(Lr,t)}}),Rh=Ka({logSigmoid_:function(e){const t=Ha(e,"x","logSigmoid");return zo(e=>({value:Mu(Ah(Mu(e))),gradFunc:t=>$o(t,uc(Mu(e)))}))(t)}}),_h=Ka({logSoftmax_:function(e,t=-1){const n=Ha(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank}
5057 and axis was ${t}`);const r=zo((e,n)=>{const r=ah(e,t,!0),s=Zo(e,r),a=Zo(Io(s,"float32"),Ch(oh(hh(s),t,!0)));return n([a]),{value:a,gradFunc:(e,n)=>{const[r]=n,s=hh(r);return Zo(e,$o(oh(e,t,!0),s))}}});return r(n)}}),Mh=Ka({logSumExp_:function(e,t=null,n=!1){const r=Ha(e,"x","logSumExp"),s=we(t,r.shape),a=ah(r,s,!0),i=Zo(r,a),o=hh(i),u=oh(o,s),l=Ch(u),c=To(sc(a,l.shape),l);if(n){const e=eh(c.shape,s);return sc(c,e)}return c}}),Fh=Ka({logicalAnd_:function(e,t){const n=Ha(e,"a","logicalAnd","bool"),r=Ha(t,"b","logicalAnd","bool");ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel($n,s)}}),Dh=Ka({logicalNot_:function(e){const t={x:Ha(e,"x","logicalNot","bool")};return Da.runKernel(An,t)}}),Oh=Ka({logicalOr_:function(e,t){const n=Ha(e,"a","logicalOr","bool"),r=Ha(t,"b","logicalOr","bool");ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Rn,s)}}),Lh=Ka({logicalXor_:function(e,t){const n=Ha(e,"a","logicalXor","bool"),r=Ha(t,"b","logicalXor","bool");return ru(n.shape,r.shape),Fh(Oh(e,t),Dh(Fh(e,t)))}}),zh=2147483648,Ph=Ka({searchSorted_:function(e,t,n="left"){const r=Ha(e,"sortedSequence","searchSorted"),s=Ha(t,"values","searchSorted"),a=r.shape[r.shape.length-1],i=s.shape[s.shape.length-1],o=sc(r,[-1,a]),u=sc(s,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==u.shape[0])throw new Error("Leading dimension of \'sortedSequence\' and \'values\' must match.");if(le(u.shape)>=zh)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=zh)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const l={sortedSequence:o,values:u},c={side:n};return Da.runKernel($r,l,c)}});function Bh(e,t){return Ph(e,t,"left")}const Vh=Ka({maxPool_:function(e,t,n,r,s){const a=Ha(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=sc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),ie(ec(n,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations \'1\'`),rc("maxPool",r,s);const u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s},c=Da.runKernel(Bn,u,l);return o?sc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Uh=Ka({maxPool3d_:function(e,t=[1,1,1],n,r,s,a="NDHWC"){const i=Ha(e,"x","maxPool3d");let o=i,u=!1;4===i.rank&&(u=!0,o=sc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),ie("NDHWC"===a,()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),rc("maxPool3d",r,s);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},h=Da.runKernel(Un,l,c);return u?sc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),Wh=Ka({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const a={x:Ha(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},o=Da.runKernel(Gn,a,i);return{result:o[0],indexes:o[1]}}}),Gh=Ka({mean_:function(e,t=null,n=!1){const r={x:Ha(e,"x","mean")},s={axis:t,keepDims:n};return Da.runKernel(Hn,r,s)}});function Hh(e,t="float32"){if(Ue(e),"complex64"===t){const t=Hh(e,"float32"),n=Hh(e,"float32");return Xa(t,n)}const n=Be(le(e),t);return Da.makeTensor(n,e,t)}function jh(e,t="float32"){if(Ue(e),"complex64"===t){const t=jh(e,"float32"),n=Hh(e,"float32");return Xa(t,n)}const n=Pe(le(e),t);return Da.makeTensor(n,e,t)}function qh(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=Ha(e,"x","meshgrid",e instanceof pa?e.dtype:"float32");if(void 0===t)return[r];let s=Ha(t,"y","meshgrid",t instanceof pa?t.dtype:"float32");const a=le(r.shape),i=le(s.shape);return"xy"===n?(r=sc(r,[1,-1]),s=sc(s,[-1,1]),[Au(jh([i,1],r.dtype),r),Au(s,jh([1,a],s.dtype))]):(r=sc(r,[-1,1]),s=sc(s,[1,-1]),[Au(r,jh([1,i],r.dtype)),Au(jh([a,1],s.dtype),s)])}const Kh=Ka({minimum_:function(e,t){let n=Ha(e,"a","minimum"),r=Ha(t,"b","minimum");[n,r]=Ta(n,r),"bool"===n.dtype&&(n=Io(n,"int32"),r=Io(r,"int32")),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(qn,s)}}),Xh=Ka({mirrorPad_:function(e,t,n){ie("reflect"===n||"symmetric"===n,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const r=Ha(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");ie(t.length===r.rank,()=>`Padding doesn\'t match input. Must be ${r.rank}. Got ${t.length}.`);const s="reflect"===n?1:0;for(let e=0;e<r.rank;e++)ie(2===t[e].length,()=>"Invalid number of paddings. Must be length of 2 each."),ie(t[e][0]>=0&&t[e][0]<=r.shape[e]-s&&t[e][1]>=0&&t[e][1]<=r.shape[e]-s,()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-s} or less than 0 for input of shape ${r.shape}`);const a={paddings:t,mode:n},i={x:r};return Da.runKernel(Kn,i,a)}}),Yh=Ka({mod_:function(e,t){let n=Ha(e,"a","mod"),r=Ha(t,"b","mod");[n,r]=Ta(n,r);const s={a:n,b:r};return Da.runKernel(Xn,s)}}),Jh=Ka({moments_:function(e,t=null,n=!1){const r=we(t,(e=Ha(e,"x","moments")).shape),s=Gh(e,r,n);let a=s.shape;n||(a=eh(s.shape,r));const i=Ro(Zo(Io(e,"float32"),sc(s,a)));return{mean:s,variance:Gh(i,r,n)}}}),Zh=Ka({multiRNNCell_:function(e,t,n,r){const s=Ha(t,"data","multiRNNCell"),a=ja(n,"c","multiRNNCell"),i=ja(r,"h","multiRNNCell");let o=s;const u=[];for(let t=0;t<e.length;t++){const n=e[t](o,a[t],i[t]);u.push(n[0]),u.push(n[1]),o=n[1]}const l=[],c=[];for(let e=0;e<u.length;e+=2)l.push(u[e]),c.push(u[e+1]);return[l,c]}}),Qh=Ka({multinomial_:function(e,t,n,r=!1){const s=Ha(e,"logits","multinomial"),a=s.size,i=s.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?sc(s,[1,-1]):s},u={numSamples:t,seed:n,normalized:r},l=Da.runKernel(Yn,o,u);return 1===i?sc(l,[l.size]):l}}
5057),ed=Ka({notEqual_:function(e,t){let n=Ha(e,"a","notEqual","string_or_numeric"),r=Ha(t,"b","notEqual","string_or_numeric");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Qn,s)}}),td=Ka({onesLike_:function(e){const t={x:Ha(e,"x","onesLike")};return Da.runKernel(rr,t)}}),nd=Ka({outerProduct_:function(e,t){const n=Ha(e,"v1","outerProduct"),r=Ha(t,"v2","outerProduct");ie(1===n.rank&&1===r.rank,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const s=sc(n,[-1,1]),a=sc(r,[1,-1]);return Au(s,a)}}),rd=Ka({pad_:function(e,t,n=0){const r=Ha(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},a={x:r};return Da.runKernel(ir,a,s)}}),sd=Ka({pad1d_:function(e,t,n=0){return ie(2===t.length,()=>"Invalid number of paddings. Must be length of 2."),rd(e,[t],n)}}),ad=Ka({pad2d_:function(e,t,n=0){return ie(2===t.length&&2===t[0].length&&2===t[1].length,()=>"Invalid number of paddings. Must be length of 2 each."),rd(e,t,n)}}),id=Ka({pad3d_:function(e,t,n=0){return ie(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,()=>"Invalid number of paddings. Must be length of 2 each."),rd(e,t,n)}}),od=Ka({pad4d_:function(e,t,n=0){return ie(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,()=>"Invalid number of paddings. Must be length of 2 each."),rd(e,t,n)}}),ud=Ka({spaceToBatchND_:function(e,t,n){const r=Ha(e,"x","spaceToBatchND");ie(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),ie(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),ie(r.shape.reduce((e,r,s)=>s>0&&s<=t.length?e&&(r+n[s-1][0]+n[s-1][1])%t[s-1]===0:e,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const s={x:r},a={blockShape:t,paddings:n};return Da.runKernel(Br,s,a)}}),ld=Ka({pool_:function(e,t,n,r,s,a,i){null==s&&(s=[1,1]),null==a&&(a=1),0===r&&(r="valid");const o=Ha(e,"x","maxPool");let u=o,l=!1;3===o.rank&&(l=!0,u=sc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(ec(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations \'${s}\'`);const c=Gl(u.shape,t,a,s,r),h=[c.dilationHeight,c.dilationWidth];let d;d="same"===r?function(e,t){const n=e.map((e,n)=>e+(e-1)*(t[n]-1)).map(e=>e-1),r=n.map(e=>Math.floor(e/2)),s=n.map((e,t)=>e-r[t]);return n.map((e,t)=>[r[t],s[t]])}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const p=1===h[0]&&1===h[1],[f,m]=function(e,t,n){const r=n.map(e=>e[0]),s=n.map(e=>e[1]),a=e.concat(r,s),i=t.map((e,t)=>(e-a[t]%e)%e),o=s.map((e,t)=>e+i[t]);return[t.map((e,t)=>[r[t],o[t]]),t.map((e,t)=>[0,i[t]])]}([c.inHeight,c.inWidth],h,d),g=p?r:"valid",y=p?u:ud(u,h,f),b=("avg"===n?()=>ac(y,t,a,g,i):()=>Vh(y,t,a,g,i))(),x=p?b:dc(b,h,m);return l?sc(x,[x.shape[1],x.shape[2],x.shape[3]]):x}}),cd=Ka({prelu_:function(e,t){const n={x:Ha(e,"x","prelu"),alpha:Ha(t,"alpha","prelu")};return Da.runKernel(lr,n)}}),hd=Ka({prod_:function(e,t=null,n=!1){let r=Ha(e,"x","prod");"bool"===r.dtype&&(r=Io(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Da.runKernel(cr,s,a)}}),dd=Ka({raggedGather_:function(e,t,n,r){const s={paramsNestedSplits:e.map((e,t)=>Ha(e,`tensors${t}`,"raggedGather","int32")),paramsDenseValues:Ha(t,"paramsDenseValues","raggedGather"),indices:Ha(n,"indices","raggedGather","int32")},a={outputRaggedRank:r},i=Da.runKernel(hr,s,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),pd=Ka({raggedRange_:function(e,t,n){const r=Ha(e,"starts","raggedRange"),s={starts:r,limits:Ha(t,"limits","raggedRange",r.dtype),deltas:Ha(n,"deltas","raggedRange",r.dtype)},a=Da.runKernel(dr,s);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}}),fd=Ka({raggedTensorToTensor_:function(e,t,n,r,s){const a=Ha(e,"shape","raggedTensorToTensor","int32"),i=Ha(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:Ha(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:r.map((e,t)=>Ha(e,`tensors${t}`,"raggedTensorToTensor","int32"))},u={rowPartitionTypes:s};return Da.runKernel(pr,o,u)}}),md=Ka({rand_:function(e,t,n){Ue(e);const r=le(e);let s=null;if(null==n||"float32"===n)s=new Float32Array(r);else if("int32"===n)s=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);s=new Uint8Array(r)}for(let e=0;e<r;e++)s[e]=t();
vendor: 5,808 bytes, line 5057
5057return Da.makeTensor(s,e,n)}});var gd=n(391);class yd{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const a=s||Math.random();this.random=gd.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,s,a;do{r=2*this.random()-1,s=2*this.random()-1,a=r*r+s*s}while(a>=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*i,t=this.mean+this.stdDev*s*i,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class bd{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=gd.alea(s.toString()),this.randn=new yd(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,a;for(;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class xd{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=gd.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const wd=Ka({randomGamma_:function(e,t,n=1,r="float32",s){if(Ue(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const a=new bd(t,n,r,s),i=ko(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),vd=Ka({randomNormal_:function(e,t=0,n=1,r,s){if(Ue(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const a=new yd(t,n,r,!1,s),i=ko(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),kd=Ka({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return vd(e,0,1,t,n)}}),Id=Ka({randomUniform_:function(e,t=0,n=1,r="float32",s){Ue(e);const a=ko(e,r),i=new xd(t,n,null,s);for(let e=0;e<a.values.length;e++)a.values[e]=i.nextValue();return a.toTensor()}}),Sd=Ka({randomUniformInt_:function(e,t,n,r){return Id(e,t,n,"int32",r)}});function Nd(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const s={start:e,stop:t,step:n,dtype:r};return Da.runKernel(fr,{},s)}const Td=Ka({reciprocal_:function(e){const t={x:Ha(e,"x","reciprocal")};return Da.runKernel(gr,t)}}),Ed=Ka({relu_:function(e){const t={x:Ha(e,"x","relu")};return Da.runKernel(yr,t)}}),Cd=Ka({relu6_:function(e){const t={x:Ha(e,"x","relu6")};return Da.runKernel(Ir,t)}}),$d=Ka({reverse_:function(e,t){const n={x:Ha(e,"x","reverse")},r={dims:t};return Da.runKernel(Sr,n,r)}}),Ad=Ka({reverse1d_:function(e){const t=Ha(e,"x","reverse");return ie(1===t.rank,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),$d(t,0)}}),Rd=Ka({reverse2d_:function(e,t){const n=Ha(e,"x","reverse");return ie(2===n.rank,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),$d(n,t)}}),_d=Ka({reverse3d_:function(e,t){const n=Ha(e,"x","reverse");return ie(3===n.rank,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),$d(n,t)}}),Md=Ka({reverse4d_:function(e,t){const n=Ha(e,"x","reverse");return ie(4===n.rank,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),$d(n,t)}}),Fd=Ka({round_:function(e){const t={x:Ha(e,"x","round")};return Da.runKernel(Nr,t)}}),Dd=Ka({rsqrt_:function(e){const t={x:Ha(e,"x","rsqrt","float32")};return Da.runKernel(Tr,t)}}),Od=Ka({selu_:function(e){const t={x:Ha(e,"x","selu")};return Da.runKernel(Rr,t)}}),Ld=Ka({separableConv2d_:function(e,t,n,r,s,a=[1,1],i="NHWC"){const o=Ha(e,"x","separableConv2d"),u=Ha(t,"depthwiseFilter","separableConv2d"),l=Ha(n,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(3===o.rank&&(h=!0,c=sc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");ie(4===c.rank,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),ie(4===u.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`),ie(4===l.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`),ie(1===l.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${l.shape[0]}.`),ie(1===l.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);const d=u.shape[2],p=u.shape[3];ie(l.shape[2]===d*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*p}, but got ${l.shape[2]}.`);const f=Bc(c,u,r,s,i,a),m=Ec(f,l,1,"valid",i);return h?sc(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),zd=async function(e,t){const n=Ha(e,"x","setdiff1d"),r=Ha(t,"y","setdiff1d");ie(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),ie(1===n.rank,()=>`x should be 1D tensor, but got x (${n.shape}).`),ie(1===r.rank,()=>`y should be 1D tensor, but got y (${r.shape}).`);
5057const s=await n.data(),a=await r.data(),i=new Set(a);let o=0;for(let e=0;e<s.length;e++)i.has(s[e])||o++;const u=new la([o],n.dtype),l=new la([o],"int32");for(let e=0,t=0;e<s.length;e++)i.has(s[e])||(u.values[t]=s[e],l.values[t]=e,t++);return[u.toTensor(),l.toTensor()]},Pd=Ka({sign_:function(e){const t={x:Ha(e,"x","sign")};return Da.runKernel(Dr,t)}}),Bd=Ka({sin_:function(e){const t={x:Ha(e,"x","sin","float32")};return Da.runKernel(Mr,t)}}),Vd=Ka({sinh_:function(e){const t={x:Ha(e,"x","sinh")};return Da.runKernel(Fr,t)}}),Ud=Ka({slice1d_:function(e,t,n){const r=Ha(e,"x","slice1d");return ie(1===r.rank,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),lc(r,[t],[n])}}),Wd=Ka({slice2d_:function(e,t,n){const r=Ha(e,"x","slice2d");return ie(2===r.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),lc(r,t,n)}}),Gd=Ka({slice3d_:function(e,t,n){const r=Ha(e,"x","slice3d");return ie(3===r.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),lc(r,t,n)}}),Hd=Ka({slice4d_:function(e,t,n){const r=Ha(e,"x","slice4d");return ie(4===r.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),lc(r,t,n)}}),jd=Ka({softmax_:function(e,t=-1){const n=Ha(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},s={dim:t};return Da.runKernel(Ur,r,s)}}),qd=Ka({fft_:function(e){ie("complex64"===e.dtype,()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return Da.runKernel(on,t)}}),Kd=Ka({ifft_:function(e){ie("complex64"===e.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return Da.runKernel(bn,t)}}),Xd=Ka({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=sc(e,[n,t]);r=Kd(s)}else{const s=[n,2*(t-1)],a=sc(Fu(e),[n,t]),i=sc(_u(e),[n,t]),o=$d(lc(a,[0,1],[n,t-2]),1),u=$o($d(lc(i,[0,1],[n,t-2]),1),Bo(-1)),l=oc([a,o],1),c=oc([i,u],1),h=sc(Xa(l,c),[s[0],s[1]]);r=Kd(h)}if(r=Fu(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=sc(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),Yd=Ka({split_:function(e,t,n=0){const r={x:Ha(e,"x","split")},s={numOrSizeSplits:t,axis:n};return Da.runKernel(Vr,r,s)}}),Jd=Ka({rfft_:function(e,t){ie("float32"===e.dtype,()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let s;if(null!=t&&t<n){const r=e.shape.map(e=>0),a=e.shape.map(e=>e);a[e.shape.length-1]=t,s=lc(e,r,a),n=t}else if(null!=t&&t>n){const r=e.shape.map(e=>e);r[e.shape.length-1]=t-n,s=oc([e,Hh(r)],e.shape.length-1),n=t}else s=e;const a=_o(s),i=sc(Xa(s,a),[r,n]),o=qd(i),u=Math.floor(n/2)+1,l=Fu(o),c=_u(o),h=Yd(l,[u,n-u],l.shape.length-1),d=Yd(c,[u,n-u],c.shape.length-1),p=s.shape.slice();return p[s.shape.length-1]=u,sc(Xa(h[0],d[0]),p)}}),Zd=Ka({squaredDifference_:function(e,t){let n=Ha(e,"a","squaredDifference"),r=Ha(t,"b","squaredDifference");[n,r]=Ta(n,r),ru(n.shape,r.shape);const s={a:n,b:r};return Da.runKernel(Kr,s,{})}}),Qd=Ka({squeeze_:function(e,t){const n=Ha(e,"x","squeeze","string_or_numeric");return sc(n,ve(n.shape,t).newShape)}}),ep=Ka({stack_:function(e,t=0){const n=ja(e,"tensors","stack","string_or_numeric");ie(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&ie(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");const r=n,s={axis:t};return Da.runKernel(ar,r,s)}}),tp=Ka({step_:function(e,t=0){const n={x:Ha(e,"x","step")},r={alpha:t};return Da.runKernel(ps,n,r)}}),np=Ka({stridedSlice_:function(e,t,n,r,s=0,a=0,i=0,o=0,u=0){const l={x:Ha(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};return Da.runKernel(Jr,l,c)}}),rp=Ka({tan_:function(e){const t={x:Ha(e,"x","tan","float32")};return Da.runKernel(ns,t)}});function sp(e,t){ue(e);const n=Ua(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ya(e,null,n,t)}function ap(e,t,n){if(ue(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have tw
5057o numbers");const r=Ua(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ya(e,t,r,n)}function ip(e,t,n){if(ue(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Ua(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ya(e,t,r,n)}function op(e,t,n){if(ue(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Ua(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ya(e,t,r,n)}function up(e,t,n){if(ue(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Ua(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Ya(e,t=t||r,r,n)}const lp=Ka({tensorScatterUpdate_:function(e,t,n){const r=Ha(e,"tensor","tensorScatterupdate"),s=Ha(t,"indices","tensorScatterupdate","int32"),a=Ha(n,"updates","tensorScatterupdate");if(Ku(a,s,r.shape),r.dtype!==a.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${r.dtype} and ${a.dtype}.`);const i={tensor:r,indices:s,updates:a};return Da.runKernel(Cr,i,{})}}),cp=Ka({topk_:function(e,t=1,n=!0){const r=Ha(e,"x","topk");
5057if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const s=r.shape[r.shape.length-1];if(t<0)throw new Error(`\'k\' passed to topk() must be >= 0 but got ${t}`);if(t>s)throw new Error(`\'k\' passed to topk() must be <= the last dimension (${s}) but got ${t}`);const a={x:r},i={k:t,sorted:n},[o,u]=Da.runKernel(as,a,i);return{values:o,indices:u}}}),hp=Ka({truncatedNormal_:function(e,t=0,n=1,r,s){if(Ue(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const a=new yd(t,n,r,!0,s),i=ko(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),dp=Ka({unique_:function(e,t=0){const n=Ha(e,"x","unique","string_or_numeric");ie(n.rank>0,()=>"The input tensor must be at least 1D");const r={x:n},s={axis:t},[a,i]=Da.runKernel(us,r,s);return{values:a,indices:i}}}),pp=Ka({unsortedSegmentSum_:function(e,t,n){const r=Ha(e,"x","unsortedSegmentSum"),s=Ha(t,"segmentIds","unsortedSegmentSum","int32");ie(pe(n),()=>"numSegments must be of dtype int");const a={x:r,segmentIds:s},i={numSegments:n};return Da.runKernel(cs,a,i)}}),fp=Ka({unstack_:function(e,t=0){const n=Ha(e,"x","unstack","string_or_numeric");ie(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);const r={value:n},s={axis:t};return Da.runKernel(ls,r,s)}});function mp(e,t){return Ph(e,t,"right")}function gp(e,t=!0,n,r){return Da.makeVariable(e,t,n,r)}function yp(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=ko(e,"int32"),s=ko([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const a=r.indexToLoc(n[t]),i=t*e.length;s.values.set(a,i)}return s.toTensor()}const bp=async function(e){const t=Ha(e,"condition","whereAsync","bool"),n=await t.data(),r=yp(t.shape,n);
5057return e!==t&&t.dispose(),r},xp=async function(e,t,n){const r=Ha(e,"tensor","boolMask"),s=Ha(t,"mask","boolMask","bool"),a=null==n?0:n,i=s.rank,o=r.shape;ie(i>0,()=>"mask cannot be scalar"),oe(o.slice(a,a+i),s.shape,"mask\'s shape must match the first K dimensions of tensor\'s shape,");let u=1;for(let e=a;e<a+i;e++)u*=o[e];const l=o.slice(0,a).concat([u],o.slice(a+i)),c=sc(r,l),h=sc(s,[-1]),d=await bp(h),p=Qd(d,[1]),f=yh(c,p,a);return e!==r&&r.dispose(),t!==s&&s.dispose(),p.dispose(),c.dispose(),h.dispose(),d.dispose(),f},wp=Ka({movingAverage_:function(e,t,n,r,s=!0){const a=Ha(e,"v","movingAverage"),i=Ha(t,"x","movingAverage"),o=Ha(n,"decay","movingAverage");Ea(a,i),ie(de(a.shape,i.shape),()=>"Shape mismatch in v and x");const u=Bo(1),l=Zo(u,o);let c=$o(Zo(i,a),l);if(s){ie(null!=r,()=>"When using zeroDebias: true, step is required.");const e=Ha(r,"step","movingAverage");c=Co(c,Zo(u,Jo(o,e)))}return To(a,c)}}),vp=Ka({scatterND_:function(e,t,n){Ue(n);const r=Ha(e,"indices","scatterND","int32"),s=Ha(t,"updates","scatterND");Ku(s,r,n);const a={indices:r,updates:s},i={shape:n};return Da.runKernel(Er,a,i)}}),kp=Ka({sparseToDense_:function(e,t,n,r=0){Ue(n);const s=Ha(e,"sparseIndices","sparseToDense","int32"),a=Ha(t,"sparseValues","sparseToDense","string_or_numeric"),i=Ha(r,"defaultValue","sparseToDense",a.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const s=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(s,a,n,i);const o={sparseIndices:s,sparseValues:a,defaultValue:i},u={outputShape:n};return Da.runKernel(qr,o,u)}}),Ip=Ka({gatherND_:function(e,t){const n=Ha(t,"indices","gatherND","int32"),r={params:Ha(e,"x","gatherND","string_or_numeric"),indices:n};return Da.runKernel(fn,r)}}),Sp=Ka({dropout_:function(e,t,n,r){const s=Ha(e,"x","dropout");if(ie("float32"===s.dtype,()=>`x has to be a floating point tensor since it\'s going to be scaled, but got a ${s.dtype} tensor instead.`),ie(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return e instanceof pa?s.clone():s;const a=function(e,t){if(null==t)return e.shape.slice();if(de(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(s,n),i=1-t,o=Co(gh(To(Id(a,0,1,"float32",r),i)),i);return $o(s,o)}});function Np(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Tp(e,t,n){const r=1-e%2,s=new Float32Array(e);for(let a=0;a<e;++a){const i=2*Math.PI*a/(e+r-1);s[a]=t-n*Math.cos(i)}return sp(s,"float32")}const Ep=async function(e,t,n=1){const r=Ha(e,"predictions","inTopK"),s=Ha(t,"targets","inTopK");ie(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),ie(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}`),oe(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];ie(n>0&&n<=a,()=>`\'k\' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);const i=await r.data(),o=await s.data(),[u,l]=[i.length/a,a],c=ke("bool",u);for(let e=0;e<u;e++){const t=e*l,r=i.subarray(t,t+l),s=[];for(let e=0;e<r.length;e++)s.push({value:r[e],index:e});s.sort((e,t)=>t.value-e.value),c[e]=0;for(let t=0;t<n;t++)if(s[t].index===o[e]){c[e]=1;break}}return e!==r&&r.dispose(),t!==s&&s.dispose(),Ja(c,s.shape,"bool")},Cp=Ka({conv2DBackpropFilter_:function(e,t,n,r,s,a="NHWC",i){let o=e;3===e.rank&&(o=sc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=sc(t,[1,t.shape[0],t.shape[1],t.shape[2]])),ie(4===o.rank,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),ie(4===u.rank,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`),ie(4===n.length,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const l="NHWC"===a?o.shape[3]:o.shape[1],c="NHWC"===a?u.shape[3]:u.shape[1];ie(l===n[2],()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`),ie(c===n[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`),rc("conv2dDerFilter",s,i);const h={x:o,dy:u},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:n};return Da.runKernel(Rt,h,d)}});function $p(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return $o(e,tp(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Ap(e,t){let n=t;const r=nu(e.shape,t.shape);return r.length>0&&(n=oh(n,r)),sc(n,e.shape)}function Rp(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Ed(e);if("elu"===t)return Kc(e);if("relu6"===t)return Cd(e);if("prelu"===t)return cd(e,n);if("leakyrelu"===t)return Ih(e,r);if("sigmoid"===t)return uc(e);throw new Error(`Unknown fused activation ${t}.`)}const _p=(e,t)=>!(e>0)||"linear"===t,Mp=Ka({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(u=u||"linear",!1===_p(Da.state.gradientDepth,u)){ie("NHWC"===s,()=>`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 h=Ec(e,t,n,r,s,a,i);return null!=o&&(h=To(h,o)),Rp(h,u,l,c)}const h=Ha(e,"x","conv2d","float32"),d=Ha(t,"filter","conv2d","float32");let p=h,f=!1;3===h.rank&&(f=!0,p=sc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===p.rank,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),ie(4===d.rank,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),rc("fused conv2d",r,i);const m="NHWC"===s?p.shape[3]:p.shape[1];ie(d.shape[2]===m,()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${d.shape[2]}.`),ie(ec(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations \'${a}\'`);const g=jl(p.shape,d.shape,n,a,r,i);let y,b;if(null!=o&&(y=Ha(o,"bias","fused conv2d"),[y]=Ta(y,h),"NHWC"===s?ru(g.outShape,y.shape):(ie(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),ie(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`))),null!=l){const e=l.shape;if(ie(e.length<=1||3===e.length,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}
5057.`),1===e.length)ie(1===e[0]||e[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`);else if(3===e.length)try{ru(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=Ha(l,"prelu weights","fused conv2d")}const x=(e,t)=>{ie("NHWC"===s,()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`);const[i,o,l,c]=t,h=$p(e,l,u);ie(Ql(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations \'${a}\'`);const d=[$c(o.shape,h,i,n,r),Cp(o,h,i.shape,n,r)];if(null!=c){const e=Ap(c,h);d.push(e)}return d},w={x:p,filter:d,bias:y,preluActivationWeights:b},v={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:c};if(null==o){const e=zo((e,t,n)=>{let r=Da.runKernel(ys,w,v);return n([t,e,r]),f&&(r=sc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}});return e(p,d)}{const e=zo((e,t,n,r)=>{let s=Da.runKernel(ys,w,v);return r([t,e,s,n]),f&&(s=sc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}});return e(p,d,y)}}}),Fp=Ka({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,a=[1,1],i){let o=e;3===e.rank&&(o=sc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=sc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:o,dy:u},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,filterShape:n};return Da.runKernel(Gt,l,c)}}),Dp=Ka({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,a=[1,1],i){let o=t,u=!1;3===t.rank&&(u=!0,o=sc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:o,filter:n},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,inputShape:e},h=Da.runKernel(Ht,l,c);return u?sc(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),Op=Ka({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(!1===_p(Da.state.gradientDepth,u)){let h=Bc(e,t,n,r,s,a,i);return null!=o&&(h=To(h,o)),Rp(h,u,l,c)}const h=Ha(e,"x","depthwiseConv2d","float32"),d=Ha(t,"filter","depthwiseConv2d","float32");let p=h,f=!1;3===h.rank&&(f=!0,p=sc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===p.rank,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),ie(4===d.rank,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),ie(p.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),null==a&&(a=[1,1]),ie(ec(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations \'${a}\'`),rc("fused depthwiseConv2d",r,i);const m=jl(p.shape,d.shape,n,a,r,i,!0);let g,y;null!=o&&(g=Ha(o,"bias","fused conv2d"),[g]=Ta(g,h),ru(m.outShape,g.shape)),null!=l&&(y=Ha(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{ie(Ql(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations \'${a}\'`);const[s,o,l,c]=t,h=$p(e,l,u),d=Dp(o.shape,h,s,n,r,a,i),p=Fp(o,h,s.shape,n,r,a,i);return null!=c?[d,p,Ap(g,h)]:[d,p]},x={x:p,filter:d,bias:g,preluActivationWeights:y},w={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:c};if(null==o){const e=zo((e,t,n)=>{let r=Da.runKernel(bs,x,w);return n([t,e,r]),f&&(r=sc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}});return e(p,d)}{const e=zo((e,t,n,r)=>{let s=Da.runKernel(bs,x,w);return r([t,e,s,n]),f&&(s=sc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}});return e(p,d,g)}}}),Lp=Ka({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===_p(Da.state.gradientDepth,a)){let u=Au(e,t,n,r);return null!=s&&(u=To(u,s)),Rp(u,a,i,o)}let u=Ha(e,"a","fused matMul"),l=Ha(t,"b","fused matMul");[u,l]=Ta(u,l);const c=n?u.shape[u.rank-2]:u.shape[u.rank-1],h=r?l.shape[l.rank-1]:l.shape[l.rank-2],d=n?u.shape[u.rank-1]:u.shape[u.rank-2],p=r?l.shape[l.rank-2]:l.shape[l.rank-1],f=u.shape.slice(0,-2),m=l.shape.slice(0,-2),g=le(f),y=le(m);ie(c===h,()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`);
5057const b=ru(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([d,p]),x=sc(u,n?[g,c,d]:[g,d,c]),w=sc(l,r?[y,p,h]:[y,h,p]);let v,k;null!=s&&(v=Ha(s,"bias","fused matMul"),[v]=Ta(v,u),ru(b,v.shape)),null!=i&&(k=Ha(i,"prelu weights","fused matMul"));const I=(e,t)=>{const[i,o,u,l]=t,c=$p(sc(e,u.shape),u,a);let h,d;return n||r?!n&&r?(h=Au(c,o,!1,!1),d=Au(c,i,!0,!1)):n&&!r?(h=Au(o,c,!1,!0),d=Au(i,c,!1,!1)):(h=Au(o,c,!0,!0),d=Au(c,i,!0,!0)):(h=Au(c,o,!1,!0),d=Au(i,c,!0,!1)),null!=s?[h,d,Ap(l,c)]:[h,d]},S={a:x,b:w,bias:v,preluActivationWeights:k},N={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:o};if(null==s){const e=zo((e,t,n)=>{const r=Da.runKernel(gs,S,N);return n([e,t,r]),{value:sc(r,b),gradFunc:I}});return e(x,w)}{const e=zo((e,t,n,r)=>{const s=Da.runKernel(gs,S,N);return r([e,t,s,n]),{value:sc(s,b),gradFunc:I}});return e(x,w,v)}}}),zp=Ka({hammingWindow_:function(e){return Tp(e,.54,.46)}}),Pp=Ka({hannWindow_:function(e){return Tp(e,.5,.5)}}),Bp=Ka({frame_:function(e,t,n,r=!1,s=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(lc(e,a,t)),a+=n;if(r)for(;a<e.size;){const r=a+t-e.size,o=oc([lc(e,a,t-r),Xo([r],s)]);i.push(o),a+=n}return 0===i.length?ap([],[0,t]):sc(oc(i),[i.length,t])}}),Vp=Ka({stft_:function(e,t,n,r,s=Pp){null==r&&(r=Np(t));const a=Bp(e,t,n),i=$o(a,s(t));return Jd(i,r)}}),Up=Ka({cropAndResize_:function(e,t,n,r,s="bilinear",a=0){const i=Ha(e,"image","cropAndResize"),o=Ha(t,"boxes","cropAndResize","float32"),u=Ha(n,"boxInd","cropAndResize","int32"),l=o.shape[0];ie(4===i.rank,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),ie(2===o.rank&&4===o.shape[1],()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${o.shape}.`),ie(1===u.rank&&u.shape[0]===l,()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${o.shape}.`),ie(2===r.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),ie(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),ie("bilinear"===s||"nearest"===s,()=>`method must be bilinear or nearest, but was ${s}`);const c={image:i,boxes:o,boxInd:u},h={method:s,extrapolationValue:a,cropSize:r};return Da.runKernel(Bt,c,h)}}),Wp=Ka({flipLeftRight_:function(e){const t=Ha(e,"image","flipLeftRight","float32");ie(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t};return Da.runKernel(ln,n,{})}}),Gp=Ka({grayscaleToRGB_:function(e){const t=Ha(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];ie(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),ie(1===r,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);const s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,fh(t,s)}}),Hp=Ka({rgbToGrayscale_:function(e){const t=Ha(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];ie(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),ie(3===r,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const s=t.dtype,a=Io(t,"float32"),i=sp([.2989,.587,.114]);let o;switch(t.rank){case 2:o=qc("ij,j->i",a,i);break;case 3:o=qc("ijk,k->ij",a,i);break;case 4:o=qc("ijkl,l->ijk",a,i);break;case 5:o=qc("ijklm,m->ijkl",a,i);break;case 6:o=qc("ijklmn,n->ijklm",a,i);break;default:throw new Error("Not a valid tensor rank.")}return o=dh(o,-1),Io(o,s)}}),jp=Ka({rotateWithOffset_:function(e,t,n=0,r=.5){const s=Ha(e,"image","rotateWithOffset","float32");ie(4===s.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);const a={image:s},i={radians:t,fillValue:n,center:r};return Da.runKernel(ms,a,i)}});function qp(e,t,n,r,s,a){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),ie(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was \'${r}\'`),ie(2===e.rank,()=>`boxes must be a 2D tensor, but was of rank \'${e.rank}\'`),ie(4===e.shape[1],()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),ie(1===t.rank,()=>
vendor: 4,663 bytes, line 5057
5057"scores must be a 1D tensor"),ie(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),ie(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was \'${a}\'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const Kp=Ka({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=Ha(e,"boxes","nonMaxSuppression","float32"),i=Ha(t,"scores","nonMaxSuppression","float32"),o=qp(a,i,n,r,s),u={maxOutputSize:n=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:s=o.scoreThreshold};return Da.runKernel(er,{boxes:a,scores:i},u)}});function Xp(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,a=0,i=!1;for(;r<s;){a=r+(s-r>>>1);const o=n(t,e[a]);o>0?r=a+1:(s=a,i=!o)}return i?r:-r-1}(e,t,n||Yp)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function Yp(e,t){return e>t?1:e<t?-1:0}function Jp(e,t,n,r,s){return ef(e,t,n,r,s,0)}function Zp(e,t,n,r,s,a){return ef(e,t,n,r,s,0,!1,a,!0)}function Qp(e,t,n,r,s,a){return ef(e,t,n,r,s,a,!0)}function ef(e,t,n,r,s,a,i=!1,o=!1,u=!1){const l=[];for(let e=0;e<t.length;e++)t[e]>s&&l.push({score:t[e],boxIndex:e,suppressBeginIndex:0});l.sort(rf);const c=a>0?-.5/a:0,h=[],d=[];for(;h.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:a,suppressBeginIndex:i}=t;if(n<s)break;let o=!1;for(let n=h.length-1;n>=i;--n){const i=tf(e,a,h[n]);if(i>=r){o=!0;break}if(t.score=t.score*nf(r,c,i),t.score<=s)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),d.push(t.score)):t.score>s&&Xp(l,t,rf))}const p=h.length,f=n-p;o&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=d),u&&(m.validOutputs=p),m}function tf(e,t,n){const r=e.subarray(4*t,4*t+4),s=e.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),o=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),d=Math.max(s[1],s[3]),p=(o-a)*(u-i),f=(h-l)*(d-c);if(p<=0||f<=0)return 0;const m=Math.max(a,l),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(u,d),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(p+f-x)}function nf(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function rf(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const sf=Ka({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=Ha(e,"boxes","nonMaxSuppression"),o=Ha(t,"scores","nonMaxSuppression"),u=qp(i,o,n,r,s,a),l={boxes:i,scores:o},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:s=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},h=Da.runKernel(nr,l,c);return{selectedIndices:h[0],selectedScores:h[1]}}}),af=Ka({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=Ha(e,"boxes","nonMaxSuppression"),o=Ha(t,"scores","nonMaxSuppression"),u=qp(i,o,n,r,s,null),l={boxes:i,scores:o},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:a},h=Da.runKernel(tr,l,c);return{selectedIndices:h[0],validOutputs:h[1]}}}),of=Ka({resizeBilinear_:function(e,t,n=!1,r=!1){const s=Ha(e,"images","resizeBilinear");ie(3===s.rank||4===s.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),ie(2===t.length,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),ie(!1===r||!1===n,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;3===s.rank&&(i=!0,a=sc(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},l=Da.runKernel(vr,o,u);return i?sc(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),uf=Ka({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=Ha(e,"images","resizeNearestNeighbor");ie(3===s.rank||4===s.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),ie(2===t.length,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),ie("float32"===s.dtype||"int32"===s.dtype,()=>"`images` must have `int32` or `float32` as dtype"),ie(!1===r||!1===n,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;3===s.rank&&(i=!0,a=sc(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},l=Da.runKernel(xr,o,u);return i?sc(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),lf=Ka({threshold_:function(e,t="binary",n=!1,r=.5){const s=Ha(e,"image","threshold"),a=s.shape[0]*s.shape[1];let i,o,u,l,c=$o(sp([r]),255);if(ie(3===s.rank,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}
5057.`),ie(3===s.shape[2]||1===s.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`),ie("int32"===s.dtype||"float32"===s.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),ie("otsu"===t||"binary"===t,()=>`Method must be binary or otsu, but was ${t}`),3===s.shape[2]){[i,o,u]=Yd(s,[1,1,1],-1);const e=$o(i,.2989),t=$o(o,.587),n=$o(u,.114);l=To(To(e,t),n)}else l=e;"otsu"===t&&(c=function(e,t){let n,r,s,a,i,o,u=sp([-1]),l=sp([0]),c=sp([0]);for(let h=0;h<e.size-1;h++){n=lc(e,0,h+1),r=lc(e,h+1),i=Co(oh(n),t),o=Co(oh(r),t);const d=oh($o(n,Nd(0,n.size)));s=Co(d,oh(n));const p=Xo(r.shape,n.size),f=To(Nd(0,r.size),p),m=$o(r,f);a=Co(oh(m),oh(r));const g=Zo(s,a),y=Zo(s,a),b=$o(i,o);c=$o($o(b,g),y);const x=bh(c,l);l=Gc(x,c,l),u=Gc(x,sp([h]),u)}return u}(yc(Io(Fd(l),"int32"),Ja([]),256),a));const h=n?Nh(l,c):bh(l,c);return Io($o(h,255),"int32")}}),cf=Ka({transform_:function(e,t,n="nearest",r="constant",s=0,a){const i=Ha(e,"image","transform","float32"),o=Ha(t,"transforms","transform","float32");ie(4===i.rank,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),ie(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),ie(null==a||2===a.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);const u={image:i,transforms:o},l={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return Da.runKernel(is,u,l)}}),hf=Ka({bandPart_:function(e,t,n){const r=Ha(e,"a","bandPart");ie(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const s=r.shape,[a,i]=r.shape.slice(-2);let o,u;"number"==typeof t?(ie(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),ie(t<=a,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`),o=Ha(t<0?a:t,"numLower","bandPart")):(ie("int32"===t.dtype,()=>"bandPart(): numLower\'s dtype must be an int32."),o=Gc(Sh(t,0),a,Kh(t,a))),"number"==typeof n?(ie(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),ie(n<=i,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`),u=Ha(n<0?i:n,"numUpper","bandPart")):(ie("int32"===n.dtype,()=>"bandPart(): numUpper\'s dtype must be an int32."),u=Gc(Sh(n,0),i,Kh(n,i)));const l=sc(Nd(0,a,1,"int32"),[-1,1]),c=Nd(0,i,1,"int32"),h=Zo(l,c),d=Fh(Nh(h,o),xh(h,Mu(u))),p=Hh([a,i],r.dtype);return sc(ep(fp(sc(r,[-1,a,i])).map(e=>Gc(d,e,p))),s)}}),df=Ka({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,ie(null!=e&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const n=e[0].shape[0];for(let t=1;t<e.length;++t)ie(e[t].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`)}else t=!0,e=Yd(e,e.shape[0],0).map(e=>Qd(e,[0]));ie(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let t=0;t<e.length;++t)n.push(Da.tidy(()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=$o(oh($o(n[r],e)),n[r]);e=Zo(e,t)}return Co(e,lh(e,"euclidean"))}));return t?ep(n,0):n}});function pf(e,t=!1){return Da.tidy(()=>{ie(2===e.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let s=mh(n),a=So(e);const i=ap([[1]],[1,1]);let o=So(i);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=a,u=o,l=s;[o,a,s]=Da.tidy(()=>{const t=lc(a,[e,e],[n-e,1]),u=lh(t),l=lc(a,[e,e],[1,1]),c=Gc(bh(l,0),ap([[-1]]),ap([[1]])),h=Zo(l,$o(c,u)),d=Co(t,h);o=1===d.shape[0]?So(i):oc([i,lc(d,[1,0],[d.shape[0]-1,d.shape[1]])],0);const p=Mu(Co(Au(c,h),u)),f=lc(a,[e,0],[n-e,r]),m=$o(p,o),g=Du(o);if(0===e)a=Zo(f,Au(m,Au(g,f)));else{const t=Zo(f,Au(m,Au(g,f)));a=oc([lc(a,[0,0],[e,r]),t],0)}const y=Du(m),b=lc(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=Zo(b,Au(Au(b,o),y));else{const t=Zo(b,Au(Au(b,o),y));s=oc([lc(s,[0,0],[n,e]),t],1)}return[o,a,s]}),li([t,u,l])}return!t&&n>r&&(s=lc(s,[0,0],[n,r]),a=lc(a,[0,0],[r,r])),[s,a]})}const ff=Ka({qr_:function(e,t=!1){if(ie(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),2===e.rank)return pf(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((e,t)=>
vendor: 5,927 bytes, line 5057
5057e*t),r=fp(sc(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];return r.forEach(e=>{const[n,r]=pf(e,t);s.push(n),a.push(r)}),[sc(ep(s,0),e.shape),sc(ep(a,0),e.shape)]}}});var mf;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(mf||(mf={}));const gf=Ka({computeWeightedLoss_:function(e,t,n=mf.SUM_BY_NONZERO_WEIGHTS){const r=Ha(e,"losses","computeWeightedLoss");let s=null;null!=t&&(s=Ha(t,"weights","computeWeightedLoss"));const a=null==s?r:$o(r,s);if(n===mf.NONE)return a;if(n===mf.SUM)return oh(a);if(n===mf.MEAN){if(null==s)return Gh(a);{const e=r.size/s.size,t=Co(oh(a),oh(s));return e>1?Co(t,Bo(e)):t}}if(n===mf.SUM_BY_NONZERO_WEIGHTS){if(null==s)return Co(oh(a),Bo(r.size));{const e=$o(s,jh(r.shape)),t=Io(oh(ed(e,Bo(0))),"float32");return Co(oh(a),t)}}throw Error(`Unknown reduction: ${n}`)}}),yf=Ka({absoluteDifference_:function(e,t,n,r=mf.SUM_BY_NONZERO_WEIGHTS){const s=Ha(e,"labels","absoluteDifference"),a=Ha(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=Ha(n,"weights","absoluteDifference")),oe(s.shape,a.shape,"Error in absoluteDifference: ");const o=eu(Zo(s,a));return gf(o,i,r)}}),bf=Ka({cosineDistance_:function(e,t,n,r,s=mf.SUM_BY_NONZERO_WEIGHTS){const a=Ha(e,"labels","cosineDistance"),i=Ha(t,"predictions","cosineDistance");let o=null;null!=r&&(o=Ha(r,"weights","cosineDistance")),oe(a.shape,i.shape,"Error in cosineDistance: ");const u=Bo(1),l=Zo(u,oh($o(a,i),n,!0));return gf(l,o,s)}}),xf=Ka({hingeLoss_:function(e,t,n,r=mf.SUM_BY_NONZERO_WEIGHTS){let s=Ha(e,"labels","hingeLoss");const a=Ha(t,"predictions","hingeLoss");let i=null;null!=n&&(i=Ha(n,"weights","hingeLoss")),oe(s.shape,a.shape,"Error in hingeLoss: ");const o=Bo(1);s=Zo($o(Bo(2),s),o);const u=Ed(Zo(o,$o(s,a)));return gf(u,i,r)}}),wf=Ka({huberLoss_:function(e,t,n,r=1,s=mf.SUM_BY_NONZERO_WEIGHTS){const a=Ha(e,"labels","huberLoss"),i=Ha(t,"predictions","huberLoss");let o=null;null!=n&&(o=Ha(n,"weights","huberLoss")),oe(a.shape,i.shape,"Error in huberLoss: ");const u=Bo(r),l=eu(Zo(i,a)),c=Kh(l,u),h=Zo(l,c),d=To($o(Bo(.5),Ro(c)),$o(u,h));return gf(d,o,s)}}),vf=Ka({logLoss_:function(e,t,n,r=1e-7,s=mf.SUM_BY_NONZERO_WEIGHTS){const a=Ha(e,"labels","logLoss"),i=Ha(t,"predictions","logLoss");let o=null;null!=n&&(o=Ha(n,"weights","logLoss")),oe(a.shape,i.shape,"Error in logLoss: ");const u=Bo(1),l=Bo(r),c=Mu($o(a,Ch(To(i,l)))),h=$o(Zo(u,a),Ch(To(Zo(u,i),l))),d=Zo(c,h);return gf(d,o,s)}}),kf=Ka({meanSquaredError_:function(e,t,n,r=mf.SUM_BY_NONZERO_WEIGHTS){const s=Ha(e,"labels","meanSquaredError"),a=Ha(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=Ha(n,"weights","meanSquaredError")),oe(s.shape,a.shape,"Error in meanSquaredError: ");const o=Zd(s,a);return gf(o,i,r)}}),If=Ka({sigmoidCrossEntropy_:function(e,t,n,r=0,s=mf.SUM_BY_NONZERO_WEIGHTS){let a=Ha(e,"multiClassLabels","sigmoidCrossEntropy");const i=Ha(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=Ha(n,"weights","sigmoidCrossEntropy")),oe(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Bo(r),t=Bo(1),n=Bo(.5);a=To($o(a,Zo(t,e)),$o(n,e))}const u=function(e,t){const n=Ha(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ha(t,"logits","sigmoidCrossEntropyWithLogits");oe(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=Ed(r),a=$o(r,n),i=$h(hh(Mu(eu(r))));return To(Zo(s,a),i)}(a,i);return gf(u,o,s)}}),Sf=Ka({softmaxCrossEntropy_:function(e,t,n,r=0,s=mf.SUM_BY_NONZERO_WEIGHTS){let a=Ha(e,"onehotLabels","softmaxCrossEntropy");const i=Ha(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=Ha(n,"weights","softmaxCrossEntropy")),oe(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Bo(r),t=Bo(1),n=Bo(a.shape[1]);a=To($o(a,Zo(t,e)),Co(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=zo((e,t,r)=>{const s=Mh(t,[n],!0),a=Zo(Io(t,"float32"),s);r([e,a]);const i=Mu($o(a,e));return{value:oh(i,[n]),gradFunc:(e,t)=>{const[r,s]=t,a=eh(e.shape,[n]);return[$o(sc(e,a),Zo(Io(r,"float32"),hh(s))),$o(sc(e,a),Zo(hh(s),Io(r,"float32")))]}}});return r(e,t)}(a,i);return gf(u,o,s)}}),Nf=Ka({sparseFillEmptyRows_:function(e,t,n,r){const s=Ha(e,"indices","sparseFillEmptyRows","int32"),a=Ha(t,"values","sparseFillEmptyRows"),i=Ha(n,"denseShape","sparseFillEmptyRows","int32"),o=Ha(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==s.rank)throw new Error(`Indices should be Tensor2D but received shape\\n        ${s.shape}`);if(1!==a.rank)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const u={indices:s,values:a,denseShape:i,defaultValue:o},l=Da.runKernel(Wr,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),Tf=Ka({sparseReshape_:function(e,t,n){const r=Ha(e,"inputIndices","sparseReshape","int32"),s=Ha(t,"inputShape","sparseReshape","int32"),a=Ha(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\\n        ${r.shape}`);if(1!==s.rank)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:r,inputShape:s,newShape:a},o=Da.runKernel(Gr,i);return{outputIndices:o[0],outputShape:o[1]}}}),Ef=Ka({sparseSegmentMean_:function(e,t,n){const r=Ha(e,"data","sparseSegmentMean"),s=Ha(t,"indices","sparseSegmentMean","int32"),a=Ha(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");
5057if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\\n          ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\\n          ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return Da.runKernel(Hr,i)}}),Cf=Ka({sparseSegmentSum_:function(e,t,n){const r=Ha(e,"data","sparseSegmentSum"),s=Ha(t,"indices","sparseSegmentSum","int32"),a=Ha(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\\n         ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\\n         ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return Da.runKernel(jr,i)}}),$f=Ka({stringNGrams_:function(e,t,n,r,s,a,i,o){const u=Ha(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=Ha(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:u,dataSplits:l},d=Da.runKernel(Zr,h,c);return{nGrams:d[0],nGramsSplits:d[1]}}}),Af=Ka({stringSplit_:function(e,t,n=!0){const r=Ha(e,"input","stringSplit","string"),s=Ha(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==s.rank)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);const a={skipEmpty:n},i={input:r,delimiter:s},o=Da.runKernel(Qr,i,a);return{indices:o[0],values:o[1],shape:o[2]}}}),Rf=Ka({stringToHashBucketFast_:function(e,t){const n=Ha(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const s={input:n};return Da.runKernel(es,s,r)}}),_f=Ka({staticRegexReplace_:function(e,t,n,r=!0){const s=Ha(e,"input","staticRegexReplace","string"),a={pattern:t,rewrite:n,replaceGlobal:r};return Da.runKernel(Yr,{x:s},a)}}),Mf={fft:qd,ifft:Kd,rfft:Jd,irfft:Xd},Ff={hammingWindow:zp,hannWindow:Pp,frame:Bp,stft:Vp},Df={flipLeftRight:Wp,grayscaleToRGB:Gp,resizeNearestNeighbor:uf,resizeBilinear:of,rgbToGrayscale:Hp,rotateWithOffset:jp,cropAndResize:Up,nonMaxSuppression:Kp,nonMaxSuppressionAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=Ha(e,"boxes","nonMaxSuppressionAsync"),i=Ha(t,"scores","nonMaxSuppressionAsync"),o=qp(a,i,n,r,s);n=o.maxOutputSize,r=o.iouThreshold,s=o.scoreThreshold;const u=await Promise.all([a.data(),i.data()]),l=u[0],c=u[1],{selectedIndices:h}=Jp(l,c,n,r,s);return a!==e&&a.dispose(),i!==t&&i.dispose(),sp(h,"int32")},nonMaxSuppressionWithScore:sf,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=Ha(e,"boxes","nonMaxSuppressionAsync"),o=Ha(t,"scores","nonMaxSuppressionAsync"),u=qp(i,o,n,r,s,a);n=u.maxOutputSize,r=u.iouThreshold,s=u.scoreThreshold,a=u.softNmsSigma;const l=await Promise.all([i.data(),o.data()]),c=l[0],h=l[1],{selectedIndices:d,selectedScores:p}=Qp(c,h,n,r,s,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:sp(d,"int32"),selectedScores:sp(p)}},nonMaxSuppressionPadded:af,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=Ha(e,"boxes","nonMaxSuppressionAsync"),o=Ha(t,"scores","nonMaxSuppressionAsync"),u=qp(i,o,n,r,s,null),l=u.maxOutputSize,c=u.iouThreshold,h=u.scoreThreshold,[d,p]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=Zp(d,p,l,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:sp(f,"int32"),validOutputs:Bo(m,"int32")}},threshold:lf,transform:cf},Of={bandPart:hf,gramSchmidt:df,qr:ff},Lf={absoluteDifference:yf,computeWeightedLoss:gf,cosineDistance:bf,hingeLoss:xf,huberLoss:wf,logLoss:vf,meanSquaredError:kf,sigmoidCrossEntropy:If,softmaxCrossEntropy:Sf},zf={sparseFillEmptyRows:Nf,sparseReshape:Tf,sparseSegmentMean:Ef,sparseSegmentSum:Cf},Pf={stringNGrams:$f,stringSplit:Af,stringToHashBucketFast:Rf,staticRegexReplace:_f},Bf=Al,Vf="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function Uf(){return new Promise(e=>Vf(()=>e()))}function Wf(e,t){const n=e[0].length;e.forEach((e,t)=>{ie(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),ie(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,s)=>{for(let a=0;a<n;
vendor: 4,409 bytes, line 5057
5057a++)ie(a===t||e[a]===r[a],()=>`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`)})}function Gf(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var Hf;function jf(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length<e+n.length;)r.push(-1);else r=t.slice();if(null==n)return r;if(e+n.length!==r.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${r.length}`);for(let s=1;s<n.length;++s){const a=n[s],i=r[r.length-n.length+s],o=r[i];if(a>=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${s+e}] = ${a} but shape[${s+e}] = ${o}`)}else r[i]=a}return r}function qf(e){const t={FIRST_DIM_SIZE:Hf.FIRST_DIM_SIZE,VALUE_ROWIDS:Hf.VALUE_ROWIDS,ROW_LENGTHS:Hf.ROW_LENGTHS,ROW_SPLITS:Hf.ROW_SPLITS,ROW_LIMITS:Hf.ROW_LIMITS,ROW_STARTS:Hf.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function Kf(e){return 0===e.length?0:e[0]===Hf.FIRST_DIM_SIZE?e.length-1:e.length}function Xf(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let s=0;s<Math.min(n,r-1);++s){const n=e[s],r=t[s+1];if(n>=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${s-e.length}] = ${n} but ragged tensor input.flatValues.shape[${s-e.length}] = ${r}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(Hf||(Hf={}));const Yf=30;function Jf(e){return e<=Yf?e:Fe(e,Math.floor(Math.sqrt(e)))}function Zf(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function Qf(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)s=s.concat([e[r+1]/t[r],t[r]]);s=s.concat(e.slice(n+1))}return s}function em(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],s=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?s.push(r):n.push(r);r.push(...n),r.push(0),r.push(...s)}return r}function tm(e,t,n,r=!0){const s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?s.push(t[n-1]*e[n]):s.push(e[n]/t[n-1]):s.push(e[n]);return s}function nm(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function rm(e,t,n){const r=e.slice(0,1);for(let s=0;s<n;++s)r.push(e[s+1]-t[s][0]-t[s][1]);return r}const sm=1.7580993408473768,am=1.0507009873554805,im=.3275911,om=.254829592,um=-.284496736,lm=1.421413741,cm=-1.453152027,hm=1.061405429;function dm(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function pm(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function fm(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function mm(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function gm(e,t){return{real:e[2*t],imag:e[2*t+1]}}function ym(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function bm(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let s=0;s<Math.ceil(e/2);s++){const a=(t?2:-2)*Math.PI*(s/e);n[s]=Math.cos(a),r[s]=Math.sin(a)}return{real:n,imag:r}}function xm(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}const wm="->",vm=/->/g,km=",",Im="...";function Sm(e,t){const n=((e=e.replace(/\\s/g,"")).length-e.replace(vm,"").length)/wm.length;if(n<1)throw new Error("Equations without an arrow are not supported.");
5057if(n>1)throw new Error(`Equation must contain exactly one arrow ("${wm}").`);const[r,s]=e.split(wm);ie(-1===r.indexOf(Im),()=>`The ellipsis notation ("${Im}") is not supported yet.`);const a=r.split(km),i=a.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let e=0;e<s.length;++e){const t=s[e];if(!a.some(e=>-1!==e.indexOf(t)))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===o.indexOf(t)&&o.push(t)}for(let e=0;e<r.length;++e){const t=r[e];-1===o.indexOf(t)&&t!==km&&o.push(t)}const u=new Array(a.length);for(let e=0;e<i;++e){if(new Set(a[e].split("")).size!==a[e].length)throw new Error(`Found duplicate axes in input component ${a[e]}. Support for duplicate axes in input is not implemented yet.`);u[e]=[];for(let t=0;t<a[e].length;++t)u[e].push(o.indexOf(a[e][t]))}const l=o.length,c=[];for(let e=s.length;e<l;++e)c.push(e);return{allDims:o,summedDims:c,idDims:u}}function Nm(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const r=[];for(let t=0;t<e;++t)-1===n[t]&&r.push(t);return n=n.filter(e=>-1!==e),{permutationIndices:n,expandDims:r}}function Tm(e,t,n){const r=new Array(e);for(let e=0;e<n.length;++e){const s=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===r[t[e][n]]?r[t[e][n]]=s[n]:ie(r[t[e][n]]===s[n],()=>`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(s)}, but got dimension ${s[n]}`)}}function Em(e,t){const n=e,r=[];let s=0;0===e.length&&n.push(-1),s=e.length+1;for(let e=0;e<s;++e)r.push([]);const a=[];for(let e=0;e<n.length;++e){const s=$m(t,n[e]);for(const t of s)-1===a.indexOf(t)&&(r[e].push(t),a.push(t))}return{path:n,steps:r}}function Cm(e){return e.every((e,t)=>e===t)}function $m(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}function Am(e,t,n=0){let r=[];if("number"==typeof t)ie(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{const s=t.reduce((e,t)=>(-1===t&&(e+=1),e),0);ie(s<=1,()=>"There should be only one negative value in split array.");const a=t.indexOf(-1);if(-1!==a){const r=t.reduce((e,t)=>t>0?e+t:e);t[a]=e.shape[n]-r}ie(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function Rm(e){return`Received SparseTensor with denseShape[0] = 0 but\\n  indices.shape[0] = ${e}`}function _m(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Mm(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Fm(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Dm(e,t){return`size ${e} must be non-negative, not ${t}`}function Om(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function Lm(e,t){return`Input to reshape is a SparseTensor with ${le(e)}\\n  dense values, but the requested shape requires a multiple of ${le(t)}. inputShape=${e} outputShape= ${t}`}function zm(e,t){return`Input to reshape is a tensor with ${le(e)} dense values, but the requested shape has ${le(t)}. inputShape=${e} outputShape=${t}`}function Pm(){return"segment ids must be >= 0"}function Bm(){return"segment ids are not increasing"}function Vm(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Um(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Wm(e,t){let n,r=!1;for(e<=Yf?(n=e,r=!0):n=Fe(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=Fe(e,n+1);return n}function Gm(e,t,n){const r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function Hm(e,t,n,r){const s=t.shape.length,a=e.shape.length;if(0!==r&&(r<-s||r>s))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) (\\n    ${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const i=e.shape[n],o=[];let u=1,l=1,c=1;for(let t=0;t<r;++t)o.push(e.shape[t]),u*=e.shape[t];for(let t=r;t<n;t++)o.push(e.shape[t]),l*=e.shape[t];for(let e=r;e<s;e++)o.push(t.shape[e]);for(let t=n+1;t<a;t++)o.push(e.shape[t]),c*=e.shape[t];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:i,outputShape:o}}function jm(e){try{return e.map(e=>Zs(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function qm(e){return e.map(e=>Js(e))}!function(){for(const e of lu)Ho(e)}();
vendor: 16,808 bytes, line 5057
5057const Km={kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,tp(Io(n,"float32"),-1))}}},Xm={kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ro(Io(n,"float32")),r=Ao(Zo(Bo(1),t));return Mu(Co(e,r))}}}},Ym={kernelName:nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ao(Zo(Ro(Io(n,"float32")),1));return Co(e,t)}}}},Jm={kernelName:rt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{let t=e;const r=nu(n.shape,s);return r.length>0&&(t=oh(t,r)),sc(t,n.shape)},b:()=>{let t=e;const n=nu(r.shape,s);return n.length>0&&(t=oh(t,n)),sc(t,r.shape)}}}},Zm={kernelName:st,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((t,r)=>{n[r]=()=>e.clone()}),n}},Qm={kernelName:ot,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_o(n)}}},eg={kernelName:ut,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_o(n)}}},tg={kernelName:lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Ao(Zo(Bo(1),Ro(Io(n,"float32")))))}}},ng={kernelName:ct,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ao(To(Bo(1),Ro(Io(n,"float32"))));return Co(e,t)}}}},rg={kernelName:pt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{const t=To(Ro(n),Ro(r));let a=$o(e,Co(r,t));const i=nu(n.shape,s);return i.length>0&&(a=oh(a,i)),sc(a,n.shape)},b:()=>{const t=To(Ro(n),Ro(r));let a=Mu($o(e,Co(n,t)));const i=nu(r.shape,s);return i.length>0&&(a=oh(a,i)),sc(a,r.shape)}}}},sg={kernelName:ht,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,To(Ro(Io(n,"float32")),1))}}},ag={kernelName:dt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Zo(Bo(1),Ro(Io(n,"float32"))))}}},ig=Ka({avgPool3dGrad_:function(e,t,n,r,s,a){const i=Ha(e,"dy","avgPool3dGrad"),o=Ha(t,"input","avgPool3dGrad");let u=i,l=o,c=!1;4===o.rank&&(c=!0,u=sc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=sc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),ie(5===u.rank,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),ie(5===l.rank,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),rc("avgPool3dGrad",s,a);const h={dy:u,input:l},d={filterSize:n,strides:r,pad:s,dimRoundingMode:a},p=Da.runKernel(yt,h,d);return c?sc(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),og={kernelName:gt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>ig(e,r,s,a,i,o)}}},ug=Ka({avgPoolGrad_:function(e,t,n,r,s){const a=Ha(e,"dy","avgPoolGrad"),i=Ha(t,"input","avgPoolGrad");ie(i.rank===a.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`);let o=i,u=a,l=!1;3===i.rank&&(l=!0,o=sc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=sc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===u.rank,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`),ie(4===o.rank,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);const c={dy:u,input:o},h={filterSize:n,strides:r,pad:s},d=Da.runKernel(mt,c,h);return l?sc(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),lg={kernelName:ft,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i}=n;return{x:()=>ug(e,r,s,a,i)}}},cg={kernelName:bt,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,s]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>Au(e,s,!1,!1),b:()=>Au(e,r,!0,!1)}:a&&!i?{a:()=>Au(s,e,!1,!0),b:()=>Au(r,e,!1,!1)}:{a:()=>Au(s,e,!0,!0),b:()=>Au(e,r,!0,!0)}:{a:()=>Au(e,s,!1,!0),b:()=>Au(r,e,!0,!1)}}},hg={kernelName:xt,gradFunc:(e,t,n)=>{const{blockShape:r,crops:s}=n;return{x:()=>ud(e,r,s)}}},dg={kernelName:kt,gradFunc:(e,t,n)=>{const r=n,s=r.inputShape,a=r.shape,i=Array.from(a);for(let e=s.length-1;e>=0;e--)if(s[e]===a[e])i[e]=1;else if(1!==s[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e<i.length;e++)i[e]>1&&o.push(e);return{x:()=>oh(e,o,!0)}}},pg={kernelName:St,gradFunc:e=>({x:()=>e.clone()})},fg={kernelName:Nt,gradFunc:e=>({x:()=>_o(e)})},mg={kernelName:Tt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:s,clipValueMax:a}=n;return{x:()=>Gc(Fh(xh(r,s),Nh(r,a)),e,_o(e))}}},gg={kernelName:Ct,inputsToSave:["x"],gradFunc:Km.gradFunc},yg={kernelName:$t,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map(e=>e.shape),{axis:s}=n,a=we(s,t[0].shape)[0],i=r.map(e=>e[a]);return Yd(e,i,a).map(e=>()=>e)}},bg={kernelName:At,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{dilations:a,strides:i,pad:o,dataFormat:u}=n;return ie(Ql(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations \'${a}\'`),{x:()=>$c(r.shape,e,s,i,o,u),filter:()=>Cp(r,e,s.shape,i,o,u)}}},xg={kernelName:_t,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:u}=n;return{dy:()=>Ec(e,s,a,i,o,1,u),filter:()=>Cp(e,r,s.shape,a,i,o,u)}}},wg=Ka({conv3DBackpropFilter_:function(e,t,n,r,s){let a=e;4===e.rank&&(a=sc(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=sc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),ie(5===a.rank,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),ie(5===i.rank,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),ie(5===n.length,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),ie(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),ie(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);const o={x:a,dy:i},u={strides:r,pad:s,filterShape:n};return Da.runKernel(Ft,o,u)}}),vg={kernelName:Mt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a}=n;ie(Ql(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations \'${r}\'`);const[i,o]=t;return{x:()=>_c(i.shape,e,o,s,a),filter:()=>wg(i,e,o.shape,s,a)}}},kg={kernelName:Ot,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(Mu(Bd(Io(n,"float32"))),e)}}},Ig={kernelName:Lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(Vd(Io(n,"float32")),e)}}},Sg={kernelName:Pt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s,exclusive:a,reverse:i}=n;return{x:()=>{const t=nh([s],r.rank);let n=Lc(e,s,a,!i);return null!=t&&(n=Du(n,t)),n}}}},Ng={kernelName:Wt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a,dimRoundingMode:i}=n,o=null==r?[1,1]:r;ie(Ql(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations \'${o}\'`);const[u,l]=t;return ie(4===u.rank,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`),ie(4===l.rank,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`),ie(u.shape[3]===l.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),ie(ec(s,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${s} and dilations \'${o}\'.`),rc("depthwiseConv2d",a,i),{x:()=>Dp(u.shape,e,l,s,a,o,i),filter:()=>Fp(u,e,l.shape,s,a,o,i)}}},Tg={kernelName:qt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,a={x:r,filter:s,dy:e},i={x:r,filter:s,dy:e};return{x:()=>Da.runKernel(Kt,a,n),filter:()=>Da.runKernel(Xt,i,n)}}},Eg={kernelName:Qt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r={dy:e,y:n};return{x:()=>Da.runKernel(en,r)}}},Cg={kernelName:tn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=$o(hh(Mu(Ro(n))),2/Math.sqrt(Math.PI));return{x:()=>$o(e,r)}}},$g={kernelName:rn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,n)}}},Ag={kernelName:sn,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>sc(e,n.shape)}}},Rg={kernelName:an,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,hh(n))}}},_g={kernelName:cn,gradFunc:e=>({x:()=>_o(e)})},Mg={kernelName:hn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{const t=Co(e,Io(r,"float32")),a=nu(n.shape,s);return a.length>0?sc(oh(t,a),n.shape):t},b:()=>{let t=$o(e,Io(n,"float32"));const a=nu(r.shape,s);a.length>0&&(t=sc(oh(t,a),r.shape));const i=Ro(r);return Mu(Co(t,Io(i,"float32")))}}}},Fg={kernelName:dn,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[s,a,i,o]=t,u=null==o?Bo(1):o,l=nu(a.shape,s.shape),c=[];if(1===a.rank){for(let e=0;e<s.shape.length-1;++e)c.push(s.shape[e]);c.push(1)}const h=Zo(s,a),d=$o(e,u),p=Dd(To(i,Bo(r))),f=$o($o($o(p,p),p),Bo(-.5));return{x:()=>1===a.rank?sc($o($o(e,fh(sc(p,[1,1,1,a.shape[0]]),c)),u),s.shape):sc($o($o(e,p),u),s.shape),mean:()=>{let e=$o($o(p,Bo(-1)),d);return 1===a.rank&&(e=oh(e,l)),sc(e,a.shape)},variance:()=>{let e=$o($o(f,h),d);return 1===a.rank&&(e=oh(e,l)),sc(e,a.shape)},scale:()=>{const t=$o(h,p);let n=$o(e,t);return 1===a.rank&&(n=oh(n,l)),sc(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=oh(t,l)),sc(t,a.shape)}}}},Dg={kernelName:pn,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,s]=t,{axis:a,batchDims:i}=n,o=we(a,r.shape)[0],u=(e,t,n)=>()=>{const r=e.shape,s=t.size,i=r.slice(0,o),u=i.length,l=r.slice(a,r.length).slice(1),c=l.length,h=Og(0,u),d=Og(u+1,u+1+c),p=Lg([i,[s],l]),f=sc(n,p),m=sc(t,[s]),g=Lg([[u],h,d]),y=Du(f,g);let b=pp(y,m,e.shape[o]);const x=rh(g);return b=Du(b,x),b};if(1===i){const t=r.shape[0],n=r.split(t,0);return{x:()=>{const t=ep(n.map((t,n)=>u(t,s.slice(n,1),e.slice(n,1))()));return t.reshape(r.shape)},indices:()=>s}}return{x:u(r,s,e),indices:()=>s}}};function Og(e,t){const n=[];for(let r=e;r<t;++r)n.push(r);return n}function Lg(e){const t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}const zg={kernelName:gn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>_o(n),b:()=>_o(r)}}},Pg={kernelName:yn,gradFunc:e=>({x:()=>Io(e,"float32")})},Bg={kernelName:wn,gradFunc:e=>({x:()=>_o(e)})},Vg={kernelName:vn,gradFunc:e=>({x:()=>_o(e)})},Ug={kernelName:kn,gradFunc:e=>({x:()=>_o(e)})},Wg={kernelName:In,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{alpha:s}=n,a=bh(r,0);return{x:()=>Gc(a,e,$o(e,s))}}},Gg={kernelName:Cn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,To(n,1))}}},Hg={kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Io(n,"float32"))}}},jg={kernelName:Mn,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n;return{logits:()=>{const t=hh(r);return Zo(e,$o(oh(e,s,!0),t))}}}},qg=Ka({localResponseNormalizationBackprop_:function(e,t,n,r=5,s=1,a=1,i=.5){const o={x:e,y:t,dy:n},u={depthRadius:r,bias:s,alpha:a,beta:i};return Da.runKernel(On,o,u)}}),Kg={kernelName:Dn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{depthRadius:a,bias:i,alpha:o,beta:u}=n;return{x:()=>qg(r,s,e,a,i,o,u)}}};function Xg(e,t,n,r){return t.rank<n.rank&&(t=sc(t,eh(t.shape,r))),e.rank<n.rank&&(e=sc(e,eh(e.shape,r))),{x:()=>$o(e,Io(Wc(n,t),e.dtype))}}const Yg={kernelName:zn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:s}=r,a=t[0],i=Xg(e,t[1],a,we(s,a.shape));return{x:()=>i.x()}}},Jg={kernelName:Pn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>$o(e,Io(xh(n,r),"float32")),b:()=>$o(e,Io(Sh(n,r),"float32"))}}},Zg=Ka({maxPool3dGrad_:function(e,t,n,r,s,a,i){const o=Ha(e,"dy","maxPool3dGrad"),u=Ha(t,"input","maxPool3dGrad"),l=Ha(n,"output","maxPool3dGrad");let c=o,h=u,d=l,p=!1;4===u.rank&&(p=!0,c=sc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=sc(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]]),d=sc(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),ie(5===c.rank,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),ie(5===h.rank,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),ie(5===d.rank,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),rc("maxPool3dGrad",a,i);const f={dy:c,input:h,output:d},m={filterSize:r,strides:s,pad:a,dimRoundingMode:i},g=Da.runKernel(Wn,f,m);return p?sc(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),Qg={kernelName:Un,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=n;return{x:()=>Zg(e,r,s,a,i,o,u)}}},ey=Ka({maxPoolGrad_:function(e,t,n,r,s,a,i){const o=Ha(e,"dy","maxPoolGrad"),u=Ha(t,"input","maxPoolGrad"),l=Ha(n,"output","maxPoolGrad");ie(u.rank===o.rank,()=>`Rank of input (${u.rank}) does not match rank of dy (${o.rank})`),ie(4===o.rank,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),ie(4===u.rank,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${u.rank}.`),rc("maxPoolGrad",a,i);const c={dy:o,input:u,output:l},h={filterSize:r,strides:s,pad:a,dimRoundingMode:i};return Da.runKernel(Vn,c,h)}}),ty={kernelName:Bn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>ey(e,r,s,a,i,o)}}},ny={kernelName:Kn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map(e=>e[0]);return{x:()=>lc(e,a,r.shape)}}},ry={kernelName:ir,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map(e=>e[0]);return{x:()=>lc(e,a,r.shape)}}},sy={kernelName:ur,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,s]=t,a=n,i=r,o=ru(a.shape,i.shape);return{a:()=>{const t=Io(i,"float32");let n=$o(e,$o(t,Jo(a,Zo(t,Bo(1)))));const r=nu(a.shape,o);return r.length>0&&(n=oh(n,r)),sc(n,a.shape)},b:()=>{const t=bh(a,0),n=Gc(t,Ch(a),_o(a));let r=$o(e,$o(s,n));const u=nu(i.shape,o);return u.length>0&&(r=oh(r,u)),sc(r,i.shape)}}}};const ay={kernelName:Rr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=bh(n,Bo(0)),r=Bo(sm),s=Bo(am),a=$o(e,s),i=$o($o(e,r),hh(Io(n,"float32")));return Gc(t,a,i)}}}},iy={kernelName:Br,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:s}=n;return{x:()=>dc(e,r,s)}}},oy={kernelName:Vr,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>oc(e,r)}}},uy=[Km,Xm,Ym,Jm,Zm,Qm,eg,tg,ng,rg,sg,ag,og,lg,cg,hg,dg,pg,fg,mg,gg,yg,xg,bg,vg,kg,Ig,Sg,Ng,Tg,{kernelName:Jt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{const t=Co(e,Io(r,"float32")),a=nu(n.shape,s);return a.length>0?sc(oh(t,a),n.shape):t},b:()=>{let t=$o(e,Io(n,"float32"));const a=nu(r.shape,s);a.length>0&&(t=sc(oh(t,a),r.shape));const i=Ro(r);return Mu(Co(t,Io(i,"float32")))}}}},Eg,Cg,$g,Ag,Rg,Mg,_g,Fg,Dg,zg,Pg,Bg,Vg,Ug,Wg,Gg,Hg,jg,Kg,Yg,Yg,Jg,Qg,ty,{kernelName:Hn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n,a=we(s,r.shape),i=le(Qc(r.shape,a)[1]);return{x:()=>{const t=r.shape.slice();a.forEach(e=>{t[e]=1});const n=sc(e,t);return Co($o(n,jh(r.shape,"float32")),i)}}}},{kernelName:jn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:s}=r,[a,i]=t,o=Xg(e,i,a,we(s,a.shape));return{x:()=>o.x()}}},{kernelName:qn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>$o(e,Io(Nh(n,r),"float32")),b:()=>$o(e,Io(bh(n,r),"float32"))}}},ny,{kernelName:Xn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{const t=nu(n.shape,s);return t.length>0?sc(oh(e,t),n.shape):e},b:()=>{const t=$o(e,Mu(gh(Co(n,r)))),a=nu(r.shape,s);return a.length>0?sc(oh(t,a),r.shape):t}}}},{kernelName:Jn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{const t=$o(e,Io(r,"float32")),a=nu(n.shape,s);return a.length>0?sc(oh(t,a),n.shape):t},b:()=>{const t=$o(e,Io(n,"float32")),a=nu(r.shape,s);return a.length>0?sc(oh(t,a),r.shape):t}}}},{kernelName:Zn,gradFunc:e=>({x:()=>Mu(e)})},{kernelName:sr,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Hh(n.shape,"float32")}}},{kernelName:rr,gradFunc:e=>({x:()=>_o(e)})},{kernelName:ar,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:r}=n;return fp(e,r).map(e=>()=>e)}},ry,ry,sy,{kernelName:lr,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,s=bh(n,0);return{x:()=>Gc(s,e,$o(e,r)),alpha:()=>{let t=Gc(s,_o(e),$o(e,n));const a=nu(r.shape,e.shape);return a.length>0&&(t=oh(t,a)),sc(t,r.shape)}}}},{kernelName:cr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n;let a=[];return a=null==s?r.shape.map((e,t)=>t):"number"==typeof s?[s]:s,{x:()=>function(e,t,n){const r=e.shape.length,s=r-n.length,a=nh(n,r);let i=e;null!=a&&(i=Du(e,a));const o=i.shape.slice(),u=o.splice(r-n.length,n.length).reduce((e,t)=>
vendor: 1,419 bytes, line 5057
5057e*t,1);o.push(u);let l=function(e,t,n){const r=e.shape.slice();r[n]=1;const s=sc(t,r),a=Oc(e,n,!0,!1),i=Oc(e,n,!0,!0),o=$o(a,i);return $o(s,o)}(i.reshape(o),t,s);if(l=l.reshape(i.shape),null!=a){const e=rh(a);l=Du(l,e)}return l}(r,e,a)}}},{kernelName:gr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Mu(Ro(n)))}}},{kernelName:Ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=$o(Nh(n,6),tp(n));return{x:()=>$o(e,Io(r,"float32"))}}},{kernelName:yr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,Io(tp(n),"float32"))}}},{kernelName:br,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>sc(e,n.shape)}}},{kernelName:vr,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>Da.runKernel(kr,s,n)}}},{kernelName:xr,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>Da.runKernel(wr,s,n)}}},{kernelName:Sr,gradFunc:(e,t,n)=>{const{dims:r}=n,s=we(r,e.shape);return{x:()=>$d(e,s)}}},{kernelName:Nr,gradFunc:e=>({x:()=>_o(e)})},{kernelName:Tr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mu(Co(e,$o(Jo(n,1.5),2)))}}},{kernelName:Ar,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Io(_o(n),"float32"),t:()=>$o(e,Io(n,e.dtype)),e:()=>$o(e,Io(Dh(n),e.dtype))}}},ay,{kernelName:Or,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,$o(n,Zo(Bo(1),n)))}}}
vendor: 4,211 bytes, line 5057
5057,{kernelName:Dr,gradFunc:e=>({x:()=>_o(e)})},{kernelName:Mr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(Fc(Io(n,"float32")),e)}}},{kernelName:Fr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(Dc(Io(n,"float32")),e)}}},{kernelName:_r,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:s,size:a}=n,i=r.shape,[o,u]=dl(r,s,a),l=[];for(let t=0;t<e.rank;t++)l.push([o[t],i[t]-o[t]-u[t]]);return{x:()=>rd(e,l)}}},{kernelName:Ur,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:s}=n,a=$o(e,r);return{logits:()=>Zo(a,$o(oh(a,[s],!0),r))}}},{kernelName:Lr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,uc(n))}}},iy,iy,oy,oy,{kernelName:zr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,$o(Ao(Io(n,"float32")),2))}}},{kernelName:Kr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Bo(2);return{a:()=>$o(e,$o(s,Zo(n,r))),b:()=>$o(e,$o(s,Zo(r,n)))}}},{kernelName:Xr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(e,$o(Io(n,"float32"),2))}}},{kernelName:ps,gradFunc:e=>({x:()=>_o(e)})},{kernelName:ts,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=ru(n.shape,r.shape);return{a:()=>{let t=e;const r=nu(n.shape,s);return r.length>0&&(t=oh(t,r)),sc(t,n.shape)},b:()=>{let t=e;const n=nu(r.shape,s);return n.length>0&&(t=oh(t,n)),sc(Mu(t),r.shape)}}}},{kernelName:Pr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,s=r.shape.slice(),{axis:a}=n;we(a,r.shape).forEach(e=>{s[e]=1});const i=sc(e,s),o=$o(i,jh(r.shape,"float32"));return{x:()=>o}}},{kernelName:ns,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Ro(Fc(n)))}}},{kernelName:rs,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>$o(Zo(Bo(1),Ro(n)),e)}}},{kernelName:ss,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:s}=n;return{x:()=>{let t=_o(r);if(1===r.rank)for(let n=0;n<s[0];++n)t=To(t,lc(e,[n*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)t=To(t,lc(e,[n*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)for(let i=0;i<s[2];++i)t=To(t,lc(e,[n*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)for(let i=0;i<s[2];++i)for(let o=0;o<s[3];++o)t=To(t,lc(e,[n*r.shape[0],a*r.shape[1],i*r.shape[2],o*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return t}}}},{kernelName:os,gradFunc:(e,t,n)=>{const r=n,{perm:s}=r,a=rh(s);return{x:()=>Du(e,a)}}},{kernelName:ls,gradFunc:(e,t,n)=>{const r=n,{axis:s}=r;return{value:()=>ep(e,s)}}},{kernelName:cs,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=su(t,_o(t)),r=yh(e,n);let s=xh(t,Bo(0,"int32"));const a=r.rank-s.rank;for(let e=0;e<a;++e)s=dh(s,e+1);s=Fh(s,jh(r.shape,"bool"));const i=_o(r);return Gc(s,r,i)}(e,n)}}},{kernelName:ds,gradFunc:e=>({x:()=>_o(e)})}];for(const e of uy)Es(e);fa().prototype.abs=function(){return this.throwIfDisposed(),eu(this)},fa().prototype.acos=function(){return this.throwIfDisposed(),Rl(this)},fa().prototype.acosh=function(){return this.throwIfDisposed(),_l(this)},fa().prototype.add=function(e){return this.throwIfDisposed(),To(this,e)},fa().prototype.all=function(e,t){return this.throwIfDisposed(),Fl(this,e,t)},fa().prototype.any=function(e,t){return this.throwIfDisposed(),Dl(this,e,t)},fa().prototype.argMax=function(e){return this.throwIfDisposed(),Ol(this,e)},fa().prototype.argMin=function(e){return this.throwIfDisposed(),Ll(this,e)},fa().prototype.asScalar=function(){return this.throwIfDisposed(),ie(1===this.size,()=>"The array must have only 1 element."),sc(this,[])},fa().prototype.asType=function(e){return this.throwIfDisposed(),Io(this,e)},fa().prototype.as1D=function(){return this.throwIfDisposed(),sc(this,[this.size])},fa().prototype.as2D=function(e,t){return this.throwIfDisposed(),sc(this,[e,t])},fa().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),sc(this,[e,t,n])},fa().prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),sc(this,[e,t,n,r])}
vendor: 28,930 bytes, line 5057
5057,fa().prototype.as5D=function(e,t,n,r,s){return this.throwIfDisposed(),sc(this,[e,t,n,r,s])},fa().prototype.asin=function(){return this.throwIfDisposed(),zl(this)},fa().prototype.asinh=function(){return this.throwIfDisposed(),Pl(this)},fa().prototype.atan=function(){return this.throwIfDisposed(),Bl(this)},fa().prototype.atan2=function(e){return this.throwIfDisposed(),Vl(this,e)},fa().prototype.atanh=function(){return this.throwIfDisposed(),Ul(this)},fa().prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),ac(this,e,t,n,r)},fa().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),dc(this,e,t)},fa().prototype.batchNorm=function(e,t,n,r,s){return this.throwIfDisposed(),pc(this,e,t,n,r,s)},fa().prototype.broadcastTo=function(e){return this.throwIfDisposed(),wc(this,e)},fa().prototype.cast=function(e){return this.throwIfDisposed(),Io(this,e)},fa().prototype.ceil=function(){return this.throwIfDisposed(),vc(this)},fa().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),kc(this,e,t)},fa().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof pa&&(e=[e]),oc([this,...e],t)},fa().prototype.conv1d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Cc(this,e,t,n,r,s,a)},fa().prototype.conv2dTranspose=function(e,t,n,r,s){return this.throwIfDisposed(),Ac(this,e,t,n,r,s)},fa().prototype.conv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Ec(this,e,t,n,r,s,a)},fa().prototype.cos=function(){return this.throwIfDisposed(),Fc(this)},fa().prototype.cosh=function(){return this.throwIfDisposed(),Dc(this)},fa().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Oc(this,e,t,n)},fa().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Lc(this,e,t,n)},fa().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Pc(this,e,t)},fa().prototype.depthwiseConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Bc(this,e,t,n,r,s,a)},fa().prototype.dilation2d=function(e,t,n,r,s){return this.throwIfDisposed(),Uc(this,e,t,n,r,s)},fa().prototype.divNoNan=function(e){return this.throwIfDisposed(),Hc(this,e)},fa().prototype.div=function(e){return this.throwIfDisposed(),Co(this,e)},fa().prototype.dot=function(e){return this.throwIfDisposed(),jc(this,e)},fa().prototype.elu=function(){return this.throwIfDisposed(),Kc(this)},fa().prototype.equal=function(e){return this.throwIfDisposed(),Wc(this,e)},fa().prototype.erf=function(){return this.throwIfDisposed(),Yc(this)},fa().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),ch(this,e,t)},fa().prototype.exp=function(){return this.throwIfDisposed(),hh(this)},fa().prototype.expandDims=function(e){return this.throwIfDisposed(),dh(this,e)},fa().prototype.expm1=function(){return this.throwIfDisposed(),ph(this)},fa().prototype.fft=function(){return this.throwIfDisposed(),qd(this)},fa().prototype.flatten=function(){return this.throwIfDisposed(),sc(this,[this.size])},fa().prototype.floor=function(){return this.throwIfDisposed(),gh(this)},fa().prototype.floorDiv=function(e){return this.throwIfDisposed(),Eo(this,e)},fa().prototype.gather=function(e,t,n){return this.throwIfDisposed(),yh(this,e,t,n)},fa().prototype.greaterEqual=function(e){return this.throwIfDisposed(),xh(this,e)},fa().prototype.greater=function(e){return this.throwIfDisposed(),bh(this,e)},fa().prototype.ifft=function(){return this.throwIfDisposed(),Kd(this)},fa().prototype.irfft=function(){return this.throwIfDisposed(),Xd(this)},fa().prototype.isFinite=function(){return this.throwIfDisposed(),wh(this)},fa().prototype.isInf=function(){return this.throwIfDisposed(),vh(this)},fa().prototype.isNaN=function(){return this.throwIfDisposed(),kh(this)},fa().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Ih(this,e)},fa().prototype.lessEqual=function(e){return this.throwIfDisposed(),Nh(this,e)},fa().prototype.less=function(e){return this.throwIfDisposed(),Sh(this,e)},fa().prototype.localResponseNormalization=function(e,t,n,r){return this.throwIfDisposed(),Eh(this,e,t,n,r)},fa().prototype.logSigmoid=function(){return this.throwIfDisposed(),Rh(this)},fa().prototype.logSoftmax=function(e){return this.throwIfDisposed(),_h(this,e)},fa().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Mh(this,e,t)},fa().prototype.log=function(){return this.throwIfDisposed(),Ch(this)},fa().prototype.log1p=function(){return this.throwIfDisposed(),$h(this)},fa().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Fh(this,e)},fa().prototype.logicalNot=function(){return this.throwIfDisposed(),Dh(this)},fa().prototype.logicalOr=function(e){return this.throwIfDisposed(),Oh(this,e)},fa().prototype.logicalXor=function(e){return this.throwIfDisposed(),Lh(this,e)},fa().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Au(this,e,t,n)},fa().prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),Vh(this,e,t,n,r)},fa().prototype.max=function(e,t){return this.throwIfDisposed(),ah(this,e,t)},fa().prototype.maximum=function(e){return this.throwIfDisposed(),su(this,e)},fa().prototype.mean=function(e,t){return this.throwIfDisposed(),Gh(this,e,t)},fa().prototype.min=function(e,t){return this.throwIfDisposed(),ih(this,e,t)},fa().prototype.minimum=function(e){return this.throwIfDisposed(),Kh(this,e)},fa().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Xh(this,e,t)},fa().prototype.mod=function(e){return this.throwIfDisposed(),Yh(this,e)},fa().prototype.mul=function(e){return this.throwIfDisposed(),$o(this,e)},fa().prototype.neg=function(){return this.throwIfDisposed(),Mu(this)},fa().prototype.norm=function(e,t,n){return this.throwIfDisposed(),lh(this,e,t,n)},fa().prototype.notEqual=function(e){return this.throwIfDisposed(),ed(this,e)},fa().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Ru(this,e,t,n)},fa().prototype.onesLike=function(){return this.throwIfDisposed(),td(this)},fa().prototype.pad=function(e,t){return this.throwIfDisposed(),rd(this,e,t)},fa().prototype.pool=function(e,t,n,r,s,a){return this.throwIfDisposed(),ld(this,e,t,n,r,s,a)},fa().prototype.pow=function(e){return this.throwIfDisposed(),Jo(this,e)},fa().prototype.prelu=function(e){return this.throwIfDisposed(),cd(this,e)},fa().prototype.prod=function(e,t){return this.throwIfDisposed(),hd(this,e,t)},fa().prototype.reciprocal=function(){return this.throwIfDisposed(),Td(this)},fa().prototype.relu=function(){return this.throwIfDisposed(),Ed(this)},fa().prototype.relu6=function(){return this.throwIfDisposed(),Cd(this)},fa().prototype.reshapeAs=function(e){return this.throwIfDisposed(),sc(this,e.shape)},fa().prototype.reshape=function(e){return this.throwIfDisposed(),sc(this,e)},fa().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),of(this,e,t,n)},fa().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),uf(this,e,t,n)},fa().prototype.reverse=function(e){return this.throwIfDisposed(),$d(this,e)},fa().prototype.rfft=function(){return this.throwIfDisposed(),Jd(this)},fa().prototype.round=function(){return this.throwIfDisposed(),Fd(this)},fa().prototype.rsqrt=function(){return this.throwIfDisposed(),Dd(this)},fa().prototype.selu=function(){return this.throwIfDisposed(),Od(this)},fa().prototype.separableConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Ld(this,e,t,n,r,s,a)},fa().prototype.sigmoid=function(){return this.throwIfDisposed(),uc(this)},fa().prototype.sign=function(){return this.throwIfDisposed(),Pd(this)},fa().prototype.sin=function(){return this.throwIfDisposed(),Bd(this)},fa().prototype.sinh=function(){return this.throwIfDisposed(),Vd(this)},fa().prototype.slice=function(e,t){return this.throwIfDisposed(),lc(this,e,t)},fa().prototype.softmax=function(e){return this.throwIfDisposed(),jd(this,e)},fa().prototype.softplus=function(){return this.throwIfDisposed(),Ah(this)},fa().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),ud(this,e,t)},fa().prototype.split=function(e,t){return this.throwIfDisposed(),Yd(this,e,t)},fa().prototype.sqrt=function(){return this.throwIfDisposed(),Ao(this)},fa().prototype.square=function(){return this.throwIfDisposed(),Ro(this)},fa().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Zd(this,e)},fa().prototype.squeeze=function(e){return this.throwIfDisposed(),Qd(this,e)},fa().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof pa?[this,e]:[this,...e];return ep(n,t)},fa().prototype.step=function(e){return this.throwIfDisposed(),tp(this,e)},fa().prototype.stridedSlice=function(e,t,n,r,s,a,i,o){return this.throwIfDisposed(),np(this,e,t,n,r,s,a,i,o)},fa().prototype.sub=function(e){return this.throwIfDisposed(),Zo(this,e)},fa().prototype.sum=function(e,t){return this.throwIfDisposed(),oh(this,e,t)},fa().prototype.tan=function(){return this.throwIfDisposed(),rp(this)},fa().prototype.tanh=function(){return this.throwIfDisposed(),cc(this)},fa().prototype.tile=function(e){return this.throwIfDisposed(),fh(this,e)},fa().prototype.toBool=function(){return this.throwIfDisposed(),Io(this,"bool")},fa().prototype.toFloat=function(){return this.throwIfDisposed(),Io(this,"float32")},fa().prototype.toInt=function(){return this.throwIfDisposed(),Io(this,"int32")},fa().prototype.topk=function(e,t){return this.throwIfDisposed(),cp(this,e,t)},fa().prototype.transpose=function(e){return this.throwIfDisposed(),Du(this,e)},fa().prototype.unique=function(e){return this.throwIfDisposed(),dp(this,e)},fa().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),pp(this,e,t)},fa().prototype.unstack=function(e){return this.throwIfDisposed(),fp(this,e)},fa().prototype.where=function(e,t){return this.throwIfDisposed(),Gc(e,this,t)},fa().prototype.zerosLike=function(){return this.throwIfDisposed(),_o(this)};class ly extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ly.prototype)}}class cy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,cy.prototype)}}class hy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,hy.prototype)}}class dy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,dy.prototype)}}class py extends Error{constructor(e){super(e),Object.setPrototypeOf(this,py.prototype)}}Error;class fy{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}function my(e,t){if(Array.isArray(e)){let n=[];for(let r=0;r<t;r++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function gy(e,t){if(!e)throw new py(t)}function yy(e,t){let n=0;for(const r of e)r===t&&n++;return n}function by(e){return 1===e.length?e[0]:e}function xy(e){return Array.isArray(e)?e:[e]}function wy(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function vy(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\\w|$)/g,(e,t)=>t.toUpperCase())}let ky={};function Iy(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Sy(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach(e=>Sy(e));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?Sy(t):e[n]=t.value)}}}function Ny(e,t={},n={},r="object",s=!1){if("string"==typeof e){const s=e;let a;if(s in n)a=n[s];else if(s in ky)a=ky[s];else if(a=t[s],null==a)throw new hy(`Unknown ${r}: ${e}. This may be due to one of the following reasons:\\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}{const a=e;if(null==a.className||null==a.config)throw new hy(`${r}: Improper config format: ${JSON.stringify(a)}.\\n\'className\' and \'config\' must set.`);const i=a.className;let o,u;if(i in n?[o,u]=n[i]:i in ky?[o,u]=ky.className:i in t&&([o,u]=t[i]),null==o)throw new hy(`Unknown ${r}: ${i}. This may be due to one of the following reasons:\\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=u){const e={};for(const t of Object.keys(ky))e[t]=ky[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},ky);for(const e of Object.keys(n))ky[e]=n[e];Sy(a.config);const r=u(o,a.config,n,s);return ky=Object.assign({},t),r}{const e=Object.assign({},ky);for(const e of Object.keys(n))ky[e]=n[e];const t=new o(a.config);return ky=Object.assign({},e),t}}}function Ty(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Ey(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Cy(e){if(null==e)throw new hy(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function $y(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new hy(`${n} is not a valid ${t}.  Valid values are ${e} or null/undefined.`)}function Ay(e,t,n=0,r=1/0){return gy(n>=0),gy(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(e=>typeof e===t)}function Ry(e,t){Array.isArray(e)?(ie(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((e,n)=>Ry(e,`element ${n+1} of ${t}`))):ie(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${_y(e)}.`)}function _y(e){return null===e?"null":Array.isArray(e)?"["+e.map(e=>_y(e)).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function My(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let Fy=0;function Dy(){return Fy++}const Oy={};function Ly(e=""){return e in Oy||(Oy[e]=0),Oy[e]+=1,e+Oy[e].toString()}const zy=["channelsFirst","channelsLast"],Py=["nearest","bilinear"],By=["valid","same","causal"],Vy=["max","avg"],Uy=["sum","mul","concat","ave"],Wy=new Map;function Gy(e){$y(zy,"DataFormat",e)}function Hy(e){$y(By,"PaddingMode",e)}function jy(e){$y(Vy,"PoolMode",e)}const qy=[];function Ky(e,t){qy.push(e);try{const e=t();return qy.pop(),e}catch(e){throw qy.pop(),e}}function Xy(e){if(!Zy(e))throw new Error("Not a valid tensor name: \'"+e+"\'");return(0===qy.length?"":qy.join("/")+"/")+e}function Yy(e){if(!Zy(e))throw new Error("Not a valid tensor name: \'"+e+"\'");Wy.has(e)||Wy.set(e,0);const t=Wy.get(e);if(Wy.set(e,Wy.get(e)+1),t>0){const n=`${e}_${t}`;return Wy.set(n,1),n}return e}const Jy=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\\._\\/]*$/);function Zy(e){return!!e.match(Jy)}function Qy(e){return e===parseInt(e.toString(),10)}function eb(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let r=1;for(let s=t;s<n;++s)r*=e[s];return r}function tb(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r<t&&(t=r)}return t}function nb(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r>t&&(t=r)}return t}function rb(e,t){if(t<e)throw new hy(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let r=e;r<t;++r)n.push(r);return n}let sb;function ab(){return null==sb&&(sb=xi().epsilon()),sb}function ib(e,t){return Io(e,t)}function ob(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),sc(e,n)}function ub(e,t,n){return ui(()=>{switch(e.rank){case 1:return Ud(e,t,n);case 2:return Wd(e,[t,0],[n,e.shape[1]]);case 3:return Gd(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Hd(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return lc(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return lc(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new hy(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function lb(e,t,n){return ui(()=>{switch(e.rank){case 1:return Ud(e,t,n);case 2:return Wd(e,[0,t],[e.shape[0],n]);case 3:return Gd(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Hd(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new hy(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function cb(e,t,n,r){return ui(()=>{switch(e.rank){case 1:return Ud(e,t,n);case 2:switch(r){case 1:return ub(e,t,n);case 2:return lb(e,t,n);default:throw new hy(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return ub(e,t,n);case 2:return Gd(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return lb(e,t,n);default:throw new hy(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return ub(e,t,n);case 2:return Hd(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Hd(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return lb(e,t,n);default:throw new hy(`The axis is not within the rank of the tensor ${r}`)}default:throw new hy(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function hb(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),oc(e,t)}function db(e,t){switch(e.rank){case 1:return Ic([e,t]);case 2:return Sc([e,t],0);case 3:return Nc([e,t],0);case 4:return Tc([e,t],0);default:throw new hy(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function pb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new hy(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return fh(e,t)}function fb(e,t=0,n=1,r,s){return vd(e,t,n,r,s)}function mb(e,t,n,r){if(e.rank<2||t.rank<2)throw new dy(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3&&e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new dy(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and  y shape = ${t.shape}`);if(2===e.rank&&2===t.rank)return Lp({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?bb(e.rank,r,"channelsLast"):null,activation:n});{const s=e.shape.slice(),a=s.pop();e=sc(e,[-1,a]);const i=t.shape.slice(),o=i.pop(),u=i.pop(),l=[...i,o],c=Array.from({length:t.rank},(e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n);t=sc(Du(t,c),[u,-1]);const h=[...s,...l];return sc(Lp({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?bb(e.rank,r,"channelsLast"):null,activation:n}),h)}}function gb(e,t,n){return ui(()=>(t=Array.isArray(t)?sp(t,"int32"):Io(t,"int32"),yh(e,t,n)))}function yb(e){return $o(e,e)}function bb(e,t,n){const r=t.shape;if(1!==t.rank&&t.rank!==e)throw new hy(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===r.length?sc(t,[1,r[0],1,1,1]):sc(t,[1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?sc(t,[1,1,1,1,r[0]]):sc(t,[1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?sc(t,[1,r[0],1,1]):sc(t,[1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?sc(t,[1,1,1,r[0]]):sc(t,[1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?sc(t,[1,r[0],1]):sc(t,[1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?sc(t,[1,1,r[0]]):sc(t,[1].concat(r))}else if(e<3)return t;throw new hy(`Unsupported input rank by biasAdd: ${t.rank}`)}function xb(e,t,n){return ui(()=>(null==n&&(n="channelsLast"),Gy(n),To(e,bb(e.rank,t,n))))}function wb(e,t,n,r){return ui(()=>Sp(e,t,n,r))}function vb(e,t,n=!1){return n?e():t()}const kb=["fanIn","fanOut","fanAvg"],Ib=["normal","uniform","truncatedNormal"];class Sb extends Wo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Nb extends Sb{apply(e,t){return Hh(e,t)}}Nb.className="Zeros",Ho(Nb);class Tb extends Sb{apply(e,t){return jh(e,t)}}Tb.className="Ones",Ho(Tb);class Eb extends Sb{constructor(e){if(super(),"object"!=typeof e)throw new hy(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new hy(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return ui(()=>$o(Bo(this.value),jh(e,t)))}getConfig(){return{value:this.value}}}Eb.className="Constant",Ho(Eb);class Cb extends Sb{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Id(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Cb.className="RandomUniform",Ho(Cb);class $b extends Sb{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new dy(`randomNormal does not support dType ${t}.`);return fb(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}$b.className="RandomNormal",Ho($b);class Ab extends Sb{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new dy(`truncatedNormal does not support dType ${t}.`);return hp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Ab.className="TruncatedNormal",Ho(Ab);class Rb extends Sb{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return ui(()=>{if(2!==e.length||e[0]!==e[1])throw new hy("Identity matrix initializer can only be used for 2D square matrices.");return $o(this.gain,mh(e[0]))})}getConfig(){return{gain:this.gain}}}Rb.className="Identity",Ho(Rb);class _b extends Sb{constructor(e){if(super(),e.scale<0)throw new hy(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,$y(kb,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){$y(Ib,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,r;if(Gy(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=eb(e,2);n=e[1]*t,r=e[0]*t}else if("channelsLast"===t){const t=eb(e,0,e.length-2);n=e[e.length-2]*t,r=e[e.length-1]*t}}else{const t=eb(e);n=Math.sqrt(t),r=Math.sqrt(t)}return[n,r]}(e),r=n[0],s=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,s):a/=Math.max(1,(r+s)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new dy(`${this.getClassName()} does not support dType ${t}.`);return hp(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return Id(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}_b.className="VarianceScaling",Ho(_b);class Mb extends _b{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _b.className}}Mb.className="GlorotUniform",Ho(Mb);class Fb extends _b{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _b.className}}Fb.className="GlorotNormal",Ho(Fb);class Db extends _b{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _b.className}}Db.className="HeNormal",Ho(Db);class Ob extends _b{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _b.className}}Ob.className="HeUniform",Ho(Ob);class Lb extends _b{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _b.className}}Lb.className="LeCunNormal",Ho(Lb);class zb extends _b{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _b.className}}zb.className="LeCunUniform",Ho(zb);class Pb extends Sb{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return ui(()=>{if(e.length<2)throw new dy("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=le(e.slice(0,-1)),r=e[e.length-1],s=n*r;s>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${s}) elements: Slowness may result.`);const a=fb([Math.max(r,n),Math.min(r,n)],0,1,t,this.seed),i=Of.qr(a,!1);let o=i[0];const u=i[1].flatten().stridedSlice([0],[Math.min(r,n)*Math.min(r,n)],[Math.min(r,n)+1]);return o=$o(o,u.sign()),n<r&&(o=o.transpose()),$o(Bo(this.gain),o.reshape(e))})}getConfig(){return{gain:this.gain,seed:this.seed}}}Pb.className="Orthogonal",Ho(Pb);const Bb={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Vb(e,t={}){return Ny(e,Go.getMap().classNameMap,t,"initializer")}function Ub(e){return Iy(e)}function Wb(e){if("string"==typeof e){const t=e in Bb?Bb[e]:e;if("GlorotNormal"===t)return new Fb;if("GlorotUniform"===t)return new Mb;if("HeNormal"===t)return new Db;if("HeUniform"===t)return new Ob;if("LeCunNormal"===t)return new Lb;if("LeCunUniform"===t)return new zb;{const e={};return e.className=t,e.config={},Vb(e)}}return e instanceof Sb?e:Vb(e)}function Gb(e){return Array.isArray(e)&&Array.isArray(e[0])}function Hb(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function jb(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new hy(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function qb(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new hy(`Expected exactly 1 Shape; got ${e.length}`)}return e}function Kb(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce((e,t)=>e*t);return t}const Xb="Variable";class Yb{constructor(e,t="float32",n=Xb,r=!0,s=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Dy(),n=null==n?Xb:n,this.originalName=Xy(n),this.name=Yy(this.originalName),this.trainable_=r,this.constraint=s,this.val=gp(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function Jb(e){return e.map(e=>e.read())}function Zb(e){e.forEach(e=>{e[0].write(e[1])})}class Qb{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class ex{constructor(e,t,n,r,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=s,this.outputTensorIndex=i,this.id=Dy(),null!=a&&(this.originalName=Xy(a),this.name=Yy(this.originalName)),this.rank=t.length}}let tx=0;class nx{constructor(e,t){this.callArgs=t,this.id=tx++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inbou
vendor: 4,708 bytes, line 5057
5057ndLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let rx=0;class sx extends Wo{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=rx++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=wy(e)+"_"+Ly(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new cy(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new hy(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return by(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return by(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ly(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \\`getInputAt(nodeIndex)\\` instead.`);if(0===this.inboundNodes.length)throw new ly(`Layer ${this.name} is not connected, no input to return.`);return by(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new ly(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ly(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \\`getOutputAt(nodeIndex)\\` instead.`);return by(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=xy(e);if(null==this.inputSpec||0===this.inputSpec.length)return;const n=xy(this.inputSpec);if(t.length!==n.length)throw new hy(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let e=0;e<t.length;e++){const r=t[e],s=n[e];if(null==s)continue;const a=r.rank;if(null!=s.ndim&&a!==s.ndim)throw new hy(`Input ${e} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(null!=s.maxNDim&&a>s.maxNDim)throw new hy(`Input ${e} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(null!=s.minNDim&&a<s.minNDim)throw new hy(`Input ${e} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(null!=s.dtype&&r.dtype!==s.dtype)throw new hy(`Input ${e} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${r.dtype}.`);if(s.axes){const t=r.shape;for(const n in s.axes){const r=Number(n),a=s.axes[n],i=r>=0?t[r]:t[t.length+r];if(null!=a&&-1===[a,null].indexOf(i))throw new hy(`Input ${e} is incompatible with layer ${this.name}: expected axis ${r} of input shape to have value ${a} but got shape ${t}.`)}}if(null!=s.shape)for(let t=0;t<s.shape.length;++t){const n=s.shape[t],a=r.shape[t];if(null!=n&&null!=a&&n!==a)throw new hy(`Input ${e} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${r.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}
5057apply(e,t){t=t||{},this.assertNotDisposed();const n=xy(e),r=function(e){let t=!0;for(const n of xy(e))if(!(n instanceof ex)){t=!1;break}return t}(e),s=function(e){let t=!0;for(const n of xy(e))if(n instanceof ex){t=!1;break}return t}(e);if(r===s)throw new hy("Arguments to apply() must be all SymbolicTensors or all Tensors");return Ky(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of xy(e))t.push(n.shape);this.build(by(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let r=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,r);const s=xy(r),a=[];for(let e of s)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(r=by(a),null!=this.activityRegularizer)throw new dy("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}{const n=function(e){e=xy(e);const t=[];for(const n of e)t.push(n.shape);return by(t)}(e),r=this.computeOutputShape(n);let s;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),s=null!=r&&r.length>0&&Array.isArray(r[0])?r.map((n,r)=>new ex(a,n,this,xy(e),t,this.name,r)):new ex(a,r,this,xy(e),t,this.name),this.addInboundNode(e,s,null,null,n,r,t),this._refCount++,null!=this.activityRegularizer)throw new dy("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}})}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,r)=>{null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new ly(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new ly(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new cy(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Kb(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Jb(e?this.trainableWeights:this.weights)}setWeights(e){ui(()=>{const t=this.weights;if(t.length!==e.length)throw new hy(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],r=Jb(t);for(let s=0;s<r.length;++s){const a=r[s],i=t[s],o=e[s];if(!de(a.shape,o.shape))throw new hy(`Layer weight shape ${a.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}Zb(n)})}addWeight(e,t,n,r,s,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new hy(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=null!=o?o():Wb("zeros"));const u=r.apply(t,n),l=new Yb(u,n,e,a,i);return u.dispose(),null!=s&&this.addLoss(()=>s.apply(l.read())),null==a&&(a=!0),a?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=xy(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
vendor: 7,458 bytes, line 5057
5057t.forEach(e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)})}return null}return t}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;const r=this.computeMask(e,n),s=xy(t),a=xy(r);if(s.length!==a.length)throw new Error(`${this.name} outputs ${s.length} tensors but ${s.length} masks for those tensors`);for(let e=0;e<s.length;e++)s[e].kerasMask=a[e]}addInboundNode(e,t,n,r,s,a,i=null){const o=xy(e);t=xy(t),n=xy(n),r=xy(r),s=Hb(s),a=Hb(a);const u=[],l=[],c=[];for(const e of o)u.push(e.sourceLayer),l.push(e.nodeIndex),c.push(e.tensorIndex);new nx({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:s,outputShapes:a},i);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer \'${this.name}\' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0===--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function ax(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const r=ax(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of r)-1===t.indexOf(e)&&t.push(e)}return t}}}class ix extends sx{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:Ly("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new hy("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new hy("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new hy("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const r=new ex(this.dtype,this.batchInputShape,this,[],{},this.name);r.nodeIndex=0,r.tensorIndex=0,new nx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[r],outputTensors:[r],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new hy(`Cannot pass any input to an InputLayer\'s apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}function ox(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new hy("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new ix({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}ix.className="InputLayer",Ho(ix);class ux{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof ux)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new hy(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return Io(t,e.dtype)}catch(n){throw new hy(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key \'${e.name}\' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof ex){if(null==this.id2Value[e.id])throw new hy(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new hy(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ex){if(null==this.id2Value[e.id])throw new hy(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new hy(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&li(this.id2Mask)}}const lx=new fy,cx=new fy;function hx(e,t,n,r){const s=null!=n&&n.training,a=Array.isArray(e),i=a?e:[e],o=i.map(e=>e.name),u=[],l=t.names();for(const e of o)-1!==l.indexOf(e)?u.push(t.getValue(e)):u.push(null);null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let h,d=lx.get(c);if(null==d){const e=function(e,t){ie(null!=e&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],r={};if(1===e.length){const s=px(e[0],t);n=s.sorted,r=s.recipientMap}else{const s=new Set;for(const a of e){const{sorted:e,recipientMap:i}=px(a,t);for(const t of e)s.has(t.name)||(n.push(t),s.add(t.name));for(const e in i)null==r[e]&&(r[e]=new Set),i[e].forEach(t=>r[e].add(t))}}return{sorted:n,recipientCounts:dx(r)}}(i,t);d=e.sorted,h=e.recipientCounts,lx.put(c,d),cx.put(c,h)}h={},s||Object.assign(h,cx.get(c));const p=new ux(t);for(let e=0;e<d.length;++e){if(null!=r){const e=ii().numTensors;e>r.maxNumTensors&&(r.maxNumTensors=e),e<r.minNumTensors&&(r.minNumTensors=e)}const a=d[e],i=a.sourceLayer;if(i instanceof ix)continue;const l=[],c=[],f=[];let m=!1;for(const e of a.inputs){const n=p.getValue(e),r=p.getMask(e);l.push(n),c.push(r),null!=r&&(m=!0),s||(h[e.name]--,0!==h[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||f.push(n))}m&&((n=n||{}).mask=c[0]);const g=xy(i.apply(l,n));let y=null;i.supportsMasking&&(y=i.computeMask(l,c));const b=fx(a),x=Array.isArray(b)?b:[b];for(let e=0;e<x.length;++e){p.hasKey(x[e])||p.add(x[e],g[e],Array.isArray(y)?y[0]:y);const t=o.indexOf(x[e].name);-1!==t&&(u[t]=g[e])}s||li(f)}return p.disposeMasks(),a?u:u[0]}function dx(e){const t={};for(const n in e)t[n]=e[n].size;return t}function px(e,t){const n=new Set,r=[],s={};for(const e of t.names())n.add(e);const a=[],i=[];for(a.push(e);a.length>0;){const e=a[a.length-1];if(n.has(e.name)){a.pop();continue}const t=i[i.length-1]===a.length-1;if(0===e.inputs.length||t)a.pop(),r.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==s[t.name]&&(s[t.name]=new Set),s[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:r,recipientMap:s}}function fx(e){let t;
5057if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const r of e.sourceLayer.inboundNodes[t].outputTensors)if(r.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}function mx(e,t){return ui(()=>Ao(oh($o(e,e),t,!0)))}Xe().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,function(e){null!=lx&&lx.setMaxEntries(e),null!=cx&&cx.setMaxEntries(e)});class gx extends Wo{getConfig(){return{}}}class yx extends gx{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return ui(()=>{const t=mx(e,this.axis),n=kc(t,0,this.maxValue);return $o(e,Co(n,To(ab(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}yx.className="MaxNorm",Ho(yx);class bx extends gx{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return ui(()=>Co(e,To(ab(),mx(e,this.axis))))}getConfig(){return{axis:this.axis}}}bx.className="UnitNorm",Ho(bx);class xx extends gx{apply(e){return Ed(e)}}xx.className="NonNeg",Ho(xx);class wx extends gx{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return ui(()=>{const t=mx(e,this.axis),n=To($o(this.rate,kc(t,this.minValue,this.maxValue)),$o(1-this.rate,t));return $o(e,Co(n,To(ab(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}wx.className="MinMaxNorm",Ho(wx);const vx={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function kx(e){return Iy(e)}function Ix(e,t={}){return Ny(e,Go.getMap().classNameMap,t,"constraint")}function Sx(e){return null==e?null:"string"==typeof e?Ix({className:e in vx?vx[e]:e,config:{}}):e instanceof gx?e:Ix(e)}function Nx(e){return new yx(e)}function Tx(e){return new bx(e)}function Ex(){return new xx}function Cx(e){return new wx(e)}function $x(){return new Nb}function Ax(){return new Tb}function Rx(e){return new Eb(e)}function _x(e){return new Cb(e)}function Mx(e){return new $b(e)}function Fx(e){return new Ab(e)}function Dx(e){return new Rb(e)}function Ox(e){return new _b(e)}function Lx(e){return new Mb(e)}function zx(e){return new Fb(e)}function Px(e){return new Db(e)}function Bx(e){return new Ob(e)}function Vx(e){return new Lb(e)}function Ux(e){return new zb(e)}function Wx(e){return new Pb(e)}async function Gx(e){if(null==e)return;const t=[],n=[],r=[];for(const s in e){const a=e[s];if("number"!=typeof a){const e=a;t.push(e.data()),n.push(s),r.push(e)}}if(t.length>0){const s=await Promise.all(t);for(let t=0;t<s.length;++t)e[n[t]]=s[t][0];li(r)}}function Hx(e){if(null!=e)for(const t in e){const n=e[t];"number"!=typeof n&&n.dispose()}}var jx;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(jx||(jx={}));class qx{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class Kx{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class Xx extends qx{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const r=t[e];if("number"==typeof r)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+r*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const s=ui(()=>To(this.totals[e],$o(r,n)));
5057this.totals[e]=s,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:ui(()=>{const n=$o(Co(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),ci(t[e])}))}}class Yx extends qx{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const r in this.history){const s=this.history[r];for(let a=0;a<s.length;++a)if("number"!=typeof s[a]){const i=s[a];e.push(i.data()),t.push(r),n.push(a)}}const r=await Promise.all(e);for(let e=0;e<r.length;++e)this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=r[e][0]}}class Jx extends qx{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Uf,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");Re(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let r,s=null!=n?n():Xs();return(...a)=>{const i=null!=n?n():Xs();return i-s<t||(s=i,r=e(...a)),r}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const r=[];null!=this.yield&&(await Gx(n),r.push(this.yield(e,t,n))),r.push(this.nextFrameFunc()),await Promise.all(r)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await Gx(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await Gx(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await Gx(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await Gx(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):Re(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await Gx(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await Gx(e),await this.trainEnd(e))}}function Zx(e,t){return null==e&&(e={}),e instanceof qx?[e]:Array.isArray(e)&&e[0]instanceof qx?e:xy(e).map(e=>new Jx(e,t))}class Qx{constructor(){}static registerCallbackConstructor(e,t){ie(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Qx.checkForDuplicate(t),null==Qx.constructors[e]&&(Qx.constructors[e]=[]),Qx.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Qx.constructors)Qx.constructors[+t].forEach(t=>{if(t===e)throw new hy("Duplicate callback constructor.")})}static clear(){Qx.constructors={}}static createCallbacks(e){const t=[];for(const n in Qx.constructors){const r=+n;e>=r&&t.push(...Qx.constructors[r])}return t.map(e=>new e)}}function ew(e,t,n,r,s,a,i,o,u){const l=new Yx,c=[new Xx,...Qx.createCallbacks(t)];null!=e&&c.push(...e),c.push(l);const h=new Kx(c);return h.setParams({epochs:n,initialEpoch:r,samples:s,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:u}),{callbackList:h,history:l}}function tw(e,t={},n=!1){return Ny(e,Go.getMap().classNameMap,t,"layer",n)}function nw(e,t){return ui(()=>{"float32"!==e.dtype&&(e=Io(e,"float32"));const n=oh(yb(e),t,!0),r=Xo(n.shape,ab()),s=Ao(su(n,r));return Co(e,s)})}function rw(e,t){return ui(()=>Gh(yb(Zo(t,e)),-1))}function sw(e,t){return ui(()=>Gh(eu(Zo(t,e)),-1))}function aw(e,t){return ui(()=>{const n=Zo(e,t),r=kc(eu(e),ab(),Number.MAX_VALUE),s=eu(Co(n,r));return $o(100,Gh(s,-1))})}function iw(e,t,n=!1){return ui(()=>{if(n)t=jd(t);else{const e=oh(t,t.shape.length-1,!0);t=Co(t,e)}return t=kc(t,ab(),1-ab()),Mu(oh($o(Io(e,"float32"),Ch(t)),t.shape.length-1))})}function ow(e,t,n=!1){return ui(()=>{const r=Io(gh(function(e){const t=[eb(e.shape)];return sc(e,t)}(e)),"int32"),s=(t=kc(t,ab(),1-ab())).shape;return iw(sc(Ru(r,s[s.length-1]),s),t,n)})}function uw(e,t){return ui(()=>{let n;return n=kc(t,ab(),1-ab()),n=Ch(Co(n,Zo(1,n))),Gh(function(e,t){if(!de(e.shape,t.shape))throw new hy(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return ui(()=>{const n=Ed(t),r=Mu(eu(t));return To(Zo(n,$o(t,e)),$h(hh(r)))})}
5057(e,n),-1)})}function lw(e,t){return ui(()=>{const n=nw(e,-1),r=nw(t,-1),s=$o(n,r);return Mu(oh(s,-1))})}Qx.constructors={};const cw={meanSquaredError:rw,meanAbsoluteError:sw,meanAbsolutePercentageError:aw,meanSquaredLogarithmicError:function(e,t){return ui(()=>{const n=kc(t,ab(),Number.MAX_VALUE),r=Ch(To(1,n)),s=kc(e,ab(),Number.MAX_VALUE),a=Ch(To(1,s));return Gh(yb(Zo(r,a)),-1)})},squaredHinge:function(e,t){return ui(()=>{const n=su(0,Zo(1,$o(e,t)));return Gh(yb(n),-1)})},hinge:function(e,t){return ui(()=>{const n=su(0,Zo(1,$o(e,t)));return Gh(n,-1)})},categoricalHinge:function(e,t){return ui(()=>{const n=oh($o(e,t),-1),r=ah($o(Zo(1,e),t),-1);return su(0,To(1,Zo(r,n)))})},logcosh:function(e,t){return ui(()=>{const n=Math.log(2),r=Zo(t,e),s=Zo(To(r,Ah($o(-2,r))),n);return Gh(s,-1)})},categoricalCrossentropy:iw,sparseCategoricalCrossentropy:ow,binaryCrossentropy:uw,kullbackLeiblerDivergence:function(e,t){return ui(()=>{const n=kc(e,ab(),1),r=kc(t,ab(),1);return oh($o(e,Ch(Co(n,r))),-1)})},poisson:function(e,t){return ui(()=>{const n=Ch(To(ab(),t));return Gh(Zo(t,$o(e,n)),-1)})},cosineProximity:lw};function hw(e){if("string"==typeof e){if(e in cw)return cw[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new hy(t)}return e}function dw(e,t){return ui(()=>{const n=$o(.5,td(t)),r=ib(bh(t,n),e.dtype);return Gh(Wc(e,r),-1)})}function pw(e,t){return ui(()=>ib(Wc(Ol(e,-1),Ol(t,-1)),"float32"))}function fw(e,t){return ui(()=>Io(oh(Fh(Wc(e,1),Wc(t,1))),"float32"))}function mw(e,t){return ui(()=>{const n=fw(e,t),r=function(e,t){return ui(()=>Io(oh(Fh(Wc(e,0),Wc(t,1))),"float32"))}(e,t),s=To(n,r);return Io(Gc(bh(s,0),Co(n,s),0),"float32")})}function gw(e,t){return uw(e,t)}function yw(e,t){return e.rank===t.rank&&(e=Qd(e,[e.rank-1])),(t=Ol(t,-1)).dtype!==e.dtype&&(t=Io(t,e.dtype)),Io(Wc(e,t),"float32")}
vendor: 4,897 bytes, line 5057
5057const bw=iw,xw=ow,ww={binaryAccuracy:dw,categoricalAccuracy:pw,precision:mw,categoricalCrossentropy:bw,sparseCategoricalCrossentropy:xw,mse:rw,MSE:rw,mae:sw,MAE:sw,mape:aw,MAPE:aw,cosine:lw};function vw(e){if("string"==typeof e&&e in ww)return ww[e];if("string"!=typeof e&&null!=e)return e;throw new hy(`Unknown metric ${e}`)}function kw(e){if(gy(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(cw))if(cw[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(ww))if(ww[n]===e){t=n;break}return void 0!==t?t:e.name}}function Iw(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Sw(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Sw(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Sw(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Sw(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Nw(e,t,n=console.log){let r="";for(let n=0;n<e.length;++n)n>0&&(r=r.slice(0,r.length-1)+" "),r+=e[n],r=r.slice(0,t[n]),r+=" ".repeat(t[n]-r.length);n(r)}function Tw(e,t,n){let r,s;try{s=e.inboundNodes.map(e=>JSON.stringify(e.inputShapes)).join(",")}catch(e){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}Nw([`${e.name} (${e.getClassName()})`,s,r,e.countParams().toString()],t,n)}function Ew(e,t,n,r){let s,a;try{a=e.inboundNodes.map(e=>JSON.stringify(e.inputShapes)).join(",")}catch(e){a="multiple"}try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}const i=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;e<t.inboundLayers.length;++e){const n=t.inboundLayers[e].name,r=t.nodeIndices[e],s=t.tensorIndices[e];i.push(`${n}[${r}][${s}]`)}const o=e.name,u=e.getClassName(),l=0===i.length?"":i[0];Nw([`${o} (${u})`,a,s,e.countParams().toString(),l],t,r);for(let e=1;e<i.length;++e)Nw(["","","","",i[e]],t,r)}function Cw(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function $w(e,t){if(null===e)return null;if("string"==typeof e)return vy(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let s=0;s<r;++s){const r=e[s];Cw(t,s,r)?n.push(r):n.push($w(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n];if("name"===n&&"string"==typeof r)t[n]=r;else{const e=vy(n);t[e]=$w(r,e)}}return t}}function Aw(e,t){if(null==e)return null;if("string"==typeof e)return wy(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let s=0;s<r;++s){const r=e[s];Cw(t,s,r)?n.push(r):n.push(Aw(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n];t[wy(n)]="name"!==n&&"className"!==n||"string"!=typeof r?Aw(r,n):r}return t}}const Rw="4.22.0";class _w extends sx{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=Ly(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Ey(this.inputs).length!==this.inputs.length)throw new hy(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(e=>e.name)}`);Ey(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(e=>e.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(r)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;gy(0===n,"input layer has >1 nodes"),gy(0===r,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(r)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];
vendor: 5,034 bytes, line 5057
5057if(!(n instanceof ix))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map(e=>e.shape),this.internalOutputShapes=this.outputs.map(e=>e.shape);const t={},n={},r={},s={},a={},i=[],o=(e,t,n,r,s,u)=>{null!=r&&null!=s&&null!=u||(r=e.sourceLayer,s=e.nodeIndex,u=e.tensorIndex);const l=r.inboundNodes[s];if(-1!==n.indexOf(l))throw new cy(`The tensor ${e.name} at layer "${r.name}" is part of a cycle.`);if(-1!==t.indexOf(l))return;this.containerNodes.add(_w.nodeKey(r,s)),r.id in a||(a[r.id]=Object.keys(a).length),-1===n.indexOf(l)&&n.push(l);const c=l.inboundLayers.length;for(let e=0;e<c;e++){const r=l.inputTensors[e],s=l.inboundLayers[e],a=l.nodeIndices[e],i=l.tensorIndices[e];o(r,t,n,s,a,i)}for(t.push(l);n.indexOf(l)>=0;)n.splice(n.indexOf(l),1);i.push(l)},u=[],l=[];for(const e of this.outputs)o(e,u,l);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let a=t[e.id];const i=null==r[e.outboundLayer.id]?0:r[e.outboundLayer.id];a=Math.max(a,i),r[e.outboundLayer.id]=a,s[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let r=0;r<e.inboundLayers.length;r++){const s=e.inboundLayers[r],i=e.nodeIndices[r],o=s.inboundNodes[i],u=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(a+1,u),n[o.id]=o}}const h={};for(const e in t){const r=t[e];r in h||(h[r]=[]),h[r].push(n[e])}const d={};for(const e in r){const t=r[e];t in d||(d[t]=[]),d[t].push(s[e])}let p=Object.keys(d).map(e=>parseInt(e,10)).sort(Ty);this.layers=[];for(const e of p){const t=d[e];t.sort((e,t)=>{const n=a[e.id],r=a[t.id];return n<r?-1:n>r?1:0});for(const e of t)e instanceof _w&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=d,p=Object.keys(h).map(e=>parseInt(e,10)).sort(Ty);const f=this.inputs.slice(),m=[];for(const e of p)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new cy(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map(e=>e.name);for(const e of g){const t=g.filter(t=>t===e).length;if(1!==t)throw new cy(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new nx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(e=>null),outputMasks:this.outputs.map(e=>null),inputShapes:this.inputs.map(e=>e.shape),outputShapes:this.outputs.map(e=>e.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container \'${this.name}\' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0===--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(t=>t.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new hy("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let r=0;const s=(e=>{const t=Object.keys(e);if(0===t.length)return!1;const n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))})(e);s&&this.parseWeights(e);for(const e of this.layers)for(const[t,a]of e.weights.entries()){const e=s?`${a.name.split("/").slice(0,-1).join("/")+"/"}${t}`:a.originalName;if(null!=n[e])throw new hy(`Duplicate weight name: ${e}`);n[e]=a,r++}const a=[];for(const r in e){let s=r;if(null==n[r]){const e=r.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[r]]);else if(t)throw new hy(`Provided weight data has no target variable: ${r}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new hy(`${e.length} of ${r}
5057 weights are not set: ${e}`)}Zb(a)}parseWeights(e){for(const t in Object.keys(e)){const n=t.split("/"),r=["vars","layer_checkpoint_dependencies"],s=n.map(e=>e.startsWith("_")?e.slice(1):e).filter(e=>!r.includes(e)).join("/");s!==t&&(e[s]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Rw}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Aw(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return ui(()=>{e=xy(e);const n=new ux;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return hx(this.outputs,n,t)})}computeMask(e,t){return ui(()=>{let n;return e=xy(e),n=null==t?my(null,e.length):xy(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){const t=Hb(e);if(t.length!==this.inputLayers.length)throw new hy(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const r=this.inputLayers[e],s=t[e];n[r.name+"_0_0"]=s}const r=Object.keys(this.nodesByDepth).map(e=>parseInt(e,10)).sort(Ty);if(r.length>1)for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map(e=>e.id).indexOf(t.id))continue;const r=[];for(let t=0;t<e.inboundLayers.length;t++){const s=e.inboundLayers[t],a=e.nodeIndices[t],i=e.tensorIndices[t],o=n[`${s.name}_${a}_${i}`];r.push(o)}const s=Hb(t.computeOutputShape(by(r))),a=t.inboundNodes.indexOf(e);for(let e=0;e<s.length;e++)n[`${t.name}_${a}_${e}`]=s[e]}}const s=[],a=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],r=this.outputLayersTensorIndices[e],s=`${t.name}_${n}_${r}`;a.push(s)}for(let e=0;e<a.length;e++){const t=a[e];gy(t in n),s.push(n[t])}return by(s)}runInternalGraph(e,t){null==t&&(t=my(null,e.length));const n={};for(let r=0;r<this.inputs.length;++r){const s=this.inputs[r],a=e[r],i=t[r];n[s.id]=[a,i]}const r=Object.keys(this.nodesByDepth).map(e=>parseInt(e,10)).sort(Ty);for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,r=e.inputTensors,s=e.outputTensors,a=new Array;for(const e of r)e.id in n&&a.push(n[e.id]);if(a.length===r.length){let r,i,o,u,l={};if(null!=e.callArgs&&(l=e.callArgs),1===a.length){const[e,n]=a[0];null==l.mask&&(l.mask=n),o=xy(t.call(e,l)),u=xy(t.computeMask(e,n)),r=[e],i=[n]}else r=a.map(e=>e[0]),i=a.map(e=>e[1]),null==l.mask&&(l.mask=i),o=xy(t.call(r,l)),u=xy(t.computeMask(r,i));if(t.activityRegularizer)throw new dy("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<s.length;++e){const t=s[e],r=o[e],a=u[e];n[t.id]=[r,a]}}}}const s=[],a=[],i=[];for(const e of this.outputs){gy(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,r]=n[e.id];i.push(t.shape),s.push(t),a.push(r)}return[s,a,i]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof _w?1:0;for(let r=0;r<e.inboundNodes.length;r++){const s=_w.nodeKey(e,r);this.containerNodes.has(s)&&(t[s]=n,n+=1)}}return t}getLayer(e,t){if(null!=t)return this.findLayer(t);if(null==e)throw new hy("Provide either a layer name or layer index");if("number"==typeof e)return this.findLayer(e);for(const t of this.layers)if(t.name===e)return t;throw new hy(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new hy(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return ui(()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const r=_w.nodeKey(t,n);this.containerNodes.has(r)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const r=e.getClassName(),s=e.getConfig(),a=[];for(let n=0;n<e.inboundNodes.length;n++){const r=e.inboundNodes[n],s=_w.nodeKey(e,n);let i={};if(this.containerNodes.has(s)){if(r.callArgs)try{JSON.stringify(r.callArgs),i=r.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${r.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),i={}}
vendor: 4,341 bytes, line 5057
5057if(r.inboundLayers.length>0){const e=[];for(let n=0;n<r.inboundLayers.length;n++){const s=r.inboundLayers[n],a=r.nodeIndices[n],o=r.tensorIndices[n];let u=t[_w.nodeKey(s,a)];null==u&&(u=0),e.push([s.name,u,o,i])}a.push(e)}}}const i={};i.name=e.name,i.className=r,i.config=s,i.inboundNodes=a,n.push(i)}e.layers=n;const r=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],s=this.inputLayersNodeIndices[e],a=_w.nodeKey(n,s);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.inputLayersTensorIndices[e];r.push([n.name,i,o])}e.inputLayers=r;const s=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],r=this.outputLayersNodeIndices[e],a=_w.nodeKey(n,r);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.outputLayersTensorIndices[e];s.push([n.name,i,o])}return e.outputLayers=s,e}static fromConfig(e,t,n={},r=!1){const s={},a={};function i(e,t){e.name in a?a[e.name].push(t):a[e.name]=[t]}function o(e,t){const n=[];let r;for(const a of t){const o=a[0],u=a[1],l=a[2];if(r=null==a[3]?{}:a[3],!(o in s))return void i(e,t);const c=s[o];if(c.inboundNodes.length<=u)return void i(e,t);const h=c.inboundNodes[u];n.push(h.outputTensors[l])}n.length>0&&e.apply(by(n),r)}function u(e){const n=e.name,a=tw(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(r),s[n]=a,e.inboundNodes.forEach(e=>{if(!(e instanceof Array))throw new hy(`Corrupted configuration, expected array for nodeData: ${e}`);i(a,e)})}const l=t.name,c=t.layers;for(const e of c)u(e);for(;!Cy(a);)for(const e of c){const t=s[e.name];if(t.name in a){const e=a[t.name];delete a[t.name];for(const n of e)o(t,n)}}const h=[],d=[],p=t.inputLayers;for(const e of p){const t=e[0],n=e[1],r=e[2];gy(t in s);const a=s[t].inboundNodes[n].outputTensors;h.push(a[r])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],r=e[2];gy(t in s);const a=s[t].inboundNodes[n].outputTensors;d.push(a[r])}return new e({inputs:h,outputs:d,name:l})}get stateful(){if(this._stateful)throw new hy("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){ui(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function Mw(e,t){return function(e,t,n){const r=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map(e=>null);if(1===r)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach(t=>{t in e?n.push(e[t]):n.push(null)}),n}throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function Fw(e,t,n,r){if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=ui(()=>{if(1===e.shape.length)return So(e);if(2===e.shape.length){if(e.shape[1]>1)return Ol(e,1);if(1===e.shape[1])return sc(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),r=Array.from(await t.data());li(t);const s=[];return r.forEach(e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);s.push(n[e])}),sp(s,"float32")}return null}function Dw(e,t){return $o(e,t)}function Ow(e,t){let n,r;const s=t;n=s.xs,r=s.ys,ie(null!=n&&null!=r,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \\`{xs: xVal, ys: yVal}\\`, where the two values may be \\`tf.Tensor\\`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates ${t}`);
5057const a=Lw("input",e.inputNames,n),i=Lw("output",e.outputNames,r),o=a[0].shape[0];ie(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs.  (Expected input keys: ${JSON.stringify(e.inputNames)})`),ie(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let t=0;t<a.length;t++)ie(a[t].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[t]} has ${a[t].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`);for(let t=0;t<i.length;t++)ie(i[t].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`);return{xs:a,ys:i}}function Lw(e,t,n){if(n instanceof pa)return[n];if(Array.isArray(n))return ie(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{const r=[];for(const s of t){if(null==n[s])throw new hy(`The feature data generated by the dataset lacks the required ${e} key \'${s}\'.`);r.push(n[s])}return r}}function zw(e){return"function"==typeof e.iterator}function Pw(e){ie(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Bw(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(e=>ub(e,t,n-t)):ub(e,t,n-t)}function Vw(e,t){return ui(()=>null==e?null:Array.isArray(e)?e.map(e=>Vw(e,t)):gb(e,"int32"===t.dtype?t:Io(t,"int32")))}function Uw(e,t){const n=[];let r=0,s=null;for(;r<e;)s=r+t,s>=e&&(s=e),n.push([r,s]),r=s;return n}function Ww(e){const t=[];e instanceof pa&&(e=[e]);for(let n=0;n<e.length;++n){const r=e[n];if(1===r.rank)t.push(ob(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function Gw(e,t){if(null==e)return;const n=[];if(t instanceof pa)n.push(t.id);else if(Array.isArray(t))t.forEach(e=>n.push(e.id));else if(null!=t)for(const e in t){const r=t[e];n.push(r.id)}const r=[];if(e instanceof pa)-1===n.indexOf(e.id)&&r.push(e);else if(Array.isArray(e))e.forEach(e=>{-1===n.indexOf(e.id)&&r.push(e)});else if(null!=e)for(const t in e){const s=e[t];-1===n.indexOf(s.id)&&r.push(s)}r.forEach(e=>{e.isDisposed||e.dispose()})}function Hw(e){return Array.isArray(e)}function jw(e){return!function(e){return e instanceof pa}(e)&&!Hw(e)}function qw(e,t,n,r=!0,s=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(Hw(e)&&e.length>0)t=!0;else if(jw(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new hy(`Error when checking model ${s} expected no data, but got ${e}`)}return[]}if(null==e)return t.map(e=>null);let a;if(jw(e)){a=[];for(const n of t){if(null==e[n])throw new hy(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(Hw(e)){if(e.length!==t.length)throw new hy(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(t.length>1)throw new hy(`The model ${s} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Ww(a),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new hy(`Error when checking ${s}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${i.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!r)continue;const a=i.shape[t],o=n[e][t];if(null!=o&&o>=0&&a!==o)throw new hy(`${s} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${s} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function Kw(e,t,n,r=!0,s=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new hy(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new hy(`The model expects ${t.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new hy(`Error when checking ${s}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let a=0;a<n[e].length;++a){if(0===a&&!r)continue;const o=i.shape[a],u=n[e][a];if(null!=u&&u!==o)throw new hy(`Error when checking ${s}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}class Xw extends _w{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new hy("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");!function(e,t,n,r=console.log){const s=function(e){let t=!0;const n=[],r=[];for(const t in e.nodesByDepth)n.push(e.nodesByDepth[t]);for(const e of n){if(e.length>1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}r.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const s of n.inboundNodes)if(-1!==r.indexOf(s)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(s?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(e=>Math.floor(t*e))),!s){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}r("_".repeat(t)),Nw(a,n,r),r("=".repeat(t));const o=e.layers;for(let e=0;e<o.length;++e)s?Tw(o[e],n,r):Ew(o[e],n,i,r),r((e===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const u=function(e){let t;return t=null!=e.collectedTrainableWeights?Kb(e.collectedTrainableWeights):Kb(e.trainableWeights),t}(e),l=Kb(e.nonTrainableWeights);r(`Total params: ${u+l}`),r(`Trainable params: ${u}`),r(`Non-trainable params: ${l}`),r("_".repeat(t))}(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.o
vendor: 4,280 bytes, line 5057
5057ptimizer)this.optimizer_=function(e){const t={Adagrad:()=>Bf.adagrad(.01),Adadelta:()=>Bf.adadelta(1,.95,ab()),Adam:()=>Bf.adam(.001,.9,.999,ab()),Adamax:()=>Bf.adamax(.002,.9,.999,ab(),0),RMSProp:()=>Bf.rmsprop(.001,.9,0,ab()),SGD:()=>Bf.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new hy(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof qo))throw new hy("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new hy(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map(e=>hw(e))}else{const n=hw(e.loss);this.outputs.forEach(e=>{t.push(n)})}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new hy(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(hw(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Ky("loss",()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}});const r=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map(e=>[]);let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map(e=>n);{const e=[];for(const r of t){let t=n.hasOwnProperty(r)?n[r]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),s=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Ky("metric",()=>{for(let e=0;e<this.outputs.length;++e)-1===n.indexOf(e)&&(t=>{let n,r,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let s;1===t[t.length-1]||this.lossFunctions[e]===uw?-1!==["accuracy","acc"].indexOf(i)?r=dw:-1!==["crossentropy","ce"].indexOf(i)&&(r=gw):this.lossFunctions[e]===ow?-1!==["accuracy","acc"].indexOf(i)?r=yw:-1!==["crossentropy","ce"].indexOf(i)&&(r=xw):-1!==["accuracy","acc"].indexOf(i)?r=pw:-1!==["crossentropy","ce"].indexOf(i)&&(r=bw),-1!==["accuracy","acc"].indexOf(i)?s="acc":-1!==["crossentropy","ce"].indexOf(i)&&(s="ce"),a=r,n=""+s}else{const e=vw(i);a=e,n=""+kw(i)}let t;Ky(n,()=>{t=a}),s(e,n,t)}})(r[e])}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const r=null==n.batchSize?32:n.batchSize;Pw(r);const s=this.standardizeUserDataXY(e,t,!0,r);try{const e=s[0].concat(s[1]);this.makeTestFunction();const t=this.testFunction;return by(this.testLoop(t,e,r,n.verbose,n.steps))}finally{Gw(s[0],e),Gw(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const r=null!=(n=n||{}).batches,s=e.testFunction;let a=[];if(n.verbose>0)throw new dy("Verbose mode is not implemented yet.");ie(!r||n.batches>
50570&&Number.isInteger(n.batches),()=>`Test loop expects \\`batches\\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);const i="function"==typeof t.next?t:await t.iterator();let o=0,u=0;for(;!r||u<n.batches;){const t=await i.next();if(a=ui(()=>{if(t.value){const{xs:n,ys:r}=Ow(e,t.value),i=n.concat(r),l=ui(()=>s(i));if(li(i),0===u)for(let e=0;e<l.length;++e)a.push(Bo(0));const c=i[0].shape[0];for(let e=0;e<l.length;++e){const t=l[e],n=a[e];a[e]=ui(()=>To(a[e],$o(c,t))),u>0&&li(n)}li(l),o+=c,++u}return a}),t.done){r&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \\`batches\\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<a.length;++e){const t=a[e];a[e]=Co(a[e],o),li(t)}return by(a)}(this,e,t)}checkNumSamples(e,t,n,r="steps"){let s;if(null!=n){if(s=null,null!=t)throw new hy(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new hy(`Either the input data should have a defined shape, or ${r} shoud be specified.`);s=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return s}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new hy("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),r=n?t:[t],s=this.retrieveSymbolicTensors(r),a=new ux;if(e instanceof pa&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new hy(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)a.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new hy(`No value is provided for the model\'s input ${t.name}`);a.add(t,n)}const i=hx(s,a);return n?i:i[0]}retrieveSymbolicTensors(e){const t=my(null,e.length);let n=e.length;for(const r of this.layers){const s=Array.isArray(r.output)?r.output:[r.output],a=s.map(e=>e.name);for(let r=0;r<e.length;++r){const i=a.indexOf(e[r]);if(-1!==i&&(t[r]=s[i],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach((t,r)=>{null==t&&n.push(e[r])}),new hy(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return ui(()=>{const r=this.checkNumSamples(e);if(n)throw new dy("Verbose predictLoop() is not implemented yet.");const s=Uw(r,t),a=this.outputs.map(e=>[]);for(let t=0;t<s.length;++t)ui(()=>{const n=s[t][0],r=s[t][1],a=Bw(e,n,r),i=[];if(Array.isArray(a))for(let e=0;e<a.length;++e)i.push({key:this.inputs[e],value:a[e]});else i.push({key:this.inputs[0],value:a});const o=new ux(i);return hx(this.outputs,o)}).forEach((e,t)=>a[t].push(e));return by(a.map(e=>oc(e,0)))})}predict(e,t={}){const n=Ww(e);Kw(n,this.inputNames,this.feedInputShapes,!1);try{const e=null==t.batchSize?32:t.batchSize;return Pw(e),this.predictLoop(n,e)}finally{Gw(n,e)}}predictOnBatch(e){Kw(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(null==this.optimizer_)throw new cy("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const s=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===ow?s.push(t.slice(0,t.length-1).concat([1])):s.push(t)}if(function(e,t){const n=Ey(e.map(e=>e.shape[0]));n.sort();const r=Ey(t.map(e=>e.shape[0]));if(r.sort(),n.length>1)throw new hy(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(e=>e.shape))}`);if(r.length>1)throw new hy(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(e=>e.shape))}`);if(n.length>0&&r.length>0&&!de(n,r))throw new hy(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${r[0]} target sample(s).`)}(e=qw(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=qw(t,this.feedOutputNames,s,!1,"target")),function(e,t,n){const r=[rw,uw,iw];for(let s=0;s<e.length;++s){const a=e[s],i=t[s],o=n[s];if(null!=i){if(i===iw&&1===a.shape[a.shape.length-1])throw new hy(`You are passing a target array of shape ${a.shape} while using a loss \'categorical_crossentropy\'. \'categorical_crossentropy\'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==r.indexOf(i)){const e=a.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const r=e[n],s=t[n];if(null!=s&&r!==s)throw new hy(`A target Tensor with shape ${a.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>
vendor: 4,190 bytes, line 5057
50570&&e[0].shape[0]%r!==0)throw new hy(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,s=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,s,a);if(null!=n)throw new Error("sample weight is not supported yet.");let u=null;if(null!=r){const e=Mw(r,this.outputNames);u=[];for(let t=0;t<e.length;++t)u.push(await Fw(o[t],null,e[t]))}return[i,o,u]}testLoop(e,t,n,r=0,s){return ui(()=>{const a=this.checkNumSamples(t,n,s,"steps"),i=[];if(r>0)throw new dy("Verbose mode is not implemented yet.");if(null!=s)throw new dy("steps mode in testLoop() is not implemented yet");{const r=Uw(a,n),s=sp(rb(0,a));for(let n=0;n<r.length;++n){const a=r[n][0],o=r[n][1],u=ub(s,a,o-a),l=Vw(t,u),c=e(l);if(0===n)for(let e=0;e<c.length;++e)i.push(Bo(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=To(i[e],$o(o-a,t))}}for(let e=0;e<i.length;++e)i[e]=Co(i[e],a)}return i})}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const r=e[n];let s=r;yy(e,r)>1&&(s+=`_${yy(e.slice(0,n),r)}`),t.push(s)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),a=[],i=this.collectedTrainableWeights.map(e=>e.read());return[this.optimizer_.minimize(()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const i=new ux(e),o=hx(this.outputs,i,{training:!0});let u;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(r[e],o[e]);null!=s[e]&&(n=Dw(n,s[e]));const a=Gh(n);t.push(a),u=0===e?n:To(u,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],s=this.metricsTensors[e][1];n=Gh(t(r[s],o[s]))}ci(n),a.push(n)}return u=Gh(u),this.calculateLosses().forEach(e=>{u=To(u,e)}),u},!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>ui(()=>{const t=[];let n;const r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;e<this.inputs.length;++e)a.push({key:this.inputs[e],value:r[e]});const i=new ux(a),o=hx(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const r=this.lossFunctions[e],a=Gh(r(s[e],o[e]));n=0===e?a:To(n,a),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],r=this.metricsTensors[e][1],a=Gh(n(s[r],o[r]));t.push(a)}return t})}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let r,s,a,i,o,u,l,c,h;this.isTraining=!0;try{const d=null==n.batchSize?32:n.batchSize;Pw(d);const p=!1,f=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,p,d);r=f[0],s=f[1],h=f[2];let m,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new dy("validationData including sample weights is not supported yet."):new hy(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],u=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,u,null,null,e,d);l=t[0],c=t[1],m=l.concat(c)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(r[0].shape[0]*(1-n.validationSplit)),t=r[0].shape[0];l=Bw(r,e,t),a=r,r=Bw(r,0,e),c=Bw(s,e,t),i=s,s=Bw(s,0,e),m=l.concat(c)}else null!=n.validationSteps&&(g=!0);const y=r.concat(s).concat(h);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let w,v;g?(this.makeTestFunction(),w=this.testFunction,v=x.slice().concat(x.map(e=>"val_"+e))):(w=null,m=[],v=x.slice());const k=Zx(n.callbacks,n.yieldEvery);return await this.fitLoop(b,y,x,d,n.epochs,n.verbose,k,w,m,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,Gw(r,e),Gw(s,t),Gw(a,e),Gw(i,t),Gw(l,o),Gw(c,u),null!=h&&li(h)}}
vendor: 8,311 bytes, line 5057
5057async fitLoop(e,t,n,r,s,a,i,o,u,l,c,h,d,p){null==r&&(r=32),null==s&&(s=1),null==l&&(l=!0),null==h&&(h=0);let f=!1;if(null!=o&&null!=u&&(f=!0),null!=p&&(f=!0,null==d))throw new hy("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,r,d,"steps_per_epoch");let g;null!=m&&(g=rb(0,m)),null==a&&(a=1);const{callbackList:y,history:b}=ew(i,a,s,h,m,d,r,f,c);y.setModel(this),this.history=b,await y.onTrainBegin(),this.stopTraining_=!1;for(let a=h;a<s;++a){await y.onEpochBegin(a);const s={};if(null!=d)throw new dy("stepsPerEpoch mode is not implemented yet.");{if("batch"===l)throw new dy("batch shuffling is not implemneted yet");l&&Z(g);const a=sp(g),i=Uw(m,r);for(let l=0;l<i.length;++l){const c={};if(await y.onBatchBegin(l,c),ui(()=>{const h=i[l][0],d=i[l][1],p=ub(a,h,d-h);c.batch=l,c.size=d-h;const m=Vw(t,p),g=e(m);for(let e=0;e<n.length;++e){const t=n[e],r=g[e];c[t]=r,ci(r)}if(l===i.length-1&&f){const e=this.testLoop(o,u,r);for(let t=0;t<n.length;++t){const r=n[t],a=e[t];ci(a),s["val_"+r]=a}}}),await y.onBatchEnd(l,c),Hx(c),this.stopTraining_)break}a.dispose()}if(await y.onEpochEnd(a,s),this.stopTraining_)break}return await y.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return async function(e,t,n){const r=null!=n.batchesPerEpoch;if(ie(null!=e.optimizer,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),ie(null!=n,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),ie(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),ie(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),ie(null==n.validationSplit,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const s=null!=n.validationData;let a,i;if(s)if(zw(n.validationData))ie(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{const e=function(e){if(3===e.length)throw new dy("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);a=e.xs,i=e.ys}const o=e.makeTrainFunction(),u=e.getDedupedMetricsNames();let l;l=s?u.slice().concat(u.map(e=>"val_"+e)):u.slice();const c=Zx(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:d,history:p}=ew(c,h,n.epochs,null,null,function(e,t){let n=null;return null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}(t,n),null,s,l);d.setModel(e),e.history=p,await d.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){const l={};await d.onEpochBegin(f);let c=0,h=0;for(r||(m=await t.iterator());!r||c<n.batchesPerEpoch;){const t=await m.next();if(r&&t.done){console.warn(`You provided \\`batchesPerEpoch\\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${c} batches; interrupting training. Make sure that your dataset can generate at least \\`batchesPerEpoch * epochs\\` batches (in this case, `+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=t.value){const{xs:r,ys:s}=Ow(e,t.value),a={};a.batch=h,a.size=r[0].shape[0],await d.onBatchBegin(h,a);const i=[];if(null!=n.classWeight){const t=Mw(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await Fw(s[e],null,t[e]))}const l=r.concat(s).concat(i),p=o(l);li(l);for(let e=0;e<u.length;++e){const t=u[e],n=p[e];a[t]=n,ci(n)}await d.onBatchEnd(h,a),Hx(a),h++,c++}if(r?c>=n.batchesPerEpoch:t.done){if(s){let t;t=zw(n.validationData)?xy(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):xy(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)l[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await d.onEpochEnd(f,l),f++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),r=n[0],s=n[1],a=this.makeTrainFunction()(r.concat(s)),i=[];for(const e of a){const t=await e.data();i.push(t[0])}return li(a),Gw(n[0],e),Gw(n[1],t),by(i)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,r=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let e=0;e<r.length;++e)n&&!r[e].trainable||t.push({name:r[e].originalName,tensor:s[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ii().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ii().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=wy(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(e=>wy(e))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const r of t){if("string"!=typeof n[r])throw new Error("Serialization of non-string loss is not supported.");e[r]=wy(n[r])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[wy(kw(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>wy(kw(e)));{const e={};for(const t in this.metrics)e[t]=wy(kw(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=tw($w(e.optimizer_config));let n,r;if("string"==typeof e.loss)n=vy(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(e=>vy(e));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=vy(e.loss[t])}if(Array.isArray(e.metrics))r=e.metrics.map(e=>vy(e));else if(null!=e.metrics){r={};for(const t in e.metrics)r[t]=vy(e.metrics[t])}this.compile({loss:n,metrics:r,optimizer:t})}async save(e,t){if("string"==typeof e){const t=Ui(e);if(0===t.length)throw new hy(`Cannot find any save handlers for URL \'${e}\'`);if(t.length>1)throw new hy(`Found more than one (${t.length}) save handlers for URL \'${e}\'`);e=t[0]}if(null==e.save)throw new hy("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await ki(this.getNamedWeights(t)),r={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${Rw}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){r.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:s}=await ki(await this.optimizer.getWeights(),e);n.specs.push(...s),n.data=_i([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Iw(this.userDefinedMetadata,this.name,e),r.userDefinedMetadata=this.userDefinedMetadata}return r.weightData=n.data,r.weightSpecs=n.specs,e.save(r)}setUserDefinedMetadata(e){Iw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Xw.className="Model",Ho(Xw);class Yw extends Xw{}async function Jw(e,t){"modelTopology"in e||(e={modelTopology:e});let n=e.modelTopology;null!=n.model_config&&(n=n.model_config);const r=tw($w(n),t);
5057if(null!=e.weightsManifest){const t=await gu(e.weightsManifest,e.pathPrefix,r.weights.map(e=>e.originalName)),n={};for(const e of r.weights)n[e.originalName]=t[e.originalName];r.loadWeights(n),li(t)}return r}async function Zw(e,t){if(null==t&&(t={}),"string"==typeof e){const n=Wi(e,t);if(0===n.length)n.push(ku(e,t));else if(n.length>1)throw new hy(`Found more than one (${n.length}) load handlers for URL \'${e}\'`);e=n[0]}return async function(e,t,n){if(null==n&&(n={}),null==e.load)throw new hy("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const r=await e.load();let s=r.modelTopology;null!=s.model_config&&(s=s.model_config);const a=null==n.strict||n.strict,i=null!=r.weightData&&null!=r.weightSpecs&&a,o=tw($w(s),void 0,i),u=r.trainingConfig;if(null!=u&&o.loadTrainingConfig(u),null!=r.userDefinedMetadata&&o.setUserDefinedMetadata(r.userDefinedMetadata),null!=r.weightData){if(null==r.weightSpecs)throw new hy("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=Ii(e,t),r={},s=[];return t.forEach(e=>{"optimizer"===e.group?s.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name]}),{modelWeights:r,optimizerWeights:s}}(r.weightData,r.weightSpecs);o.loadWeights(e,a),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),li(e),li(t.map(e=>e.tensor))}return o}(e,0,t)}Yw.className="Functional",Ho(Yw);class Qw extends Xw{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Ly("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(e=>e<0))throw new hy(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Qw||e instanceof Xw;let n;if(t){if(n=e,1!==n.outputs.length)throw new hy("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new hy("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new hy("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=ox({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new hy(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new hy("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=ax(this.outputs[0])}this.inboundNodes=[],new nx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:my(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(e=>e.shape),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(qb(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");
5057this.model=new Xw({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new cy("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new cy("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new cy("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new cy("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},r=!1){let s,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new hy("Legacy serialization format not supported yet.");s=t}else ie(null!=t.layers,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the \'layers\' field."),s=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof Qw))throw new dy(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of s){const t=tw(e,void 0,r);r&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new hy("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new hy("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function ev(e){return new Xw(e)}function tv(e){return new Qw(e)}function nv(e){return ox(e)}function rv(e,t){Qx.registerCallbackConstructor(e,t)}Qw.className="Sequential",Ho(Qw);class sv extends Wo{getConfig(){return{}}}class av extends sv{apply(e,t=1){return function(e,t=1){if(1!==t)throw new dy(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Kc(e)}(e,t)}}av.className="elu",Ho(av);class iv extends sv{apply(e){return Od(e)}}iv.className="selu",Ho(iv);class ov extends sv{apply(e){return Ed(e)}}ov.className="relu",Ho(ov);class uv extends sv{apply(e){return ui(()=>Kh(6,Ed(e)))}}uv.className="relu6",Ho(uv);class lv extends sv{apply(e){return e}}lv.className="linear",Ho(lv);class cv extends sv{apply(e){return uc(e)}}cv.className="sigmoid",Ho(cv);class hv extends sv{apply(e){return function(e){return ui(()=>{const t=To(.5,$o(.2,e));return kc(t,0,1)})}(e)}}hv.className="hardSigmoid",Ho(hv);class dv extends sv{apply(e){return Ah(e)}}dv.className="softplus",Ho(dv);class pv extends sv{apply(e){return function(e){return ui(()=>Co(e,To(eu(e),1)))}(e)}}pv.className="softsign",Ho(pv);class fv extends sv{apply(e){return cc(e)}}fv.className="tanh",Ho(fv);class mv extends sv{apply(e,t=-1){return jd(e,t)}}mv.className="softmax",Ho(mv);class gv extends sv{apply(e,t=-1){return _h(e,t)}}gv.className="logSoftmax",Ho(gv);class yv extends sv{apply(e){return ui(()=>ui(()=>{const t=Math.sqrt(2),n=$o(.5,To(1,Yc(Co(e,t))));return $o(e,n)}))}}yv.className="gelu",Ho(yv);class bv extends sv{apply(e){return ui(()=>$o(.5,$o(e,To(1,cc($o(Ao(Co(2,Math.PI)),To(e,$o(.044715,Jo(e,3)))))))))}}bv.className="gelu_new",Ho(bv);class xv extends sv{apply(e){return ui(()=>$o(e,cc(Ah(e))))}}xv.className="mish",Ho(xv);class wv extends sv{apply(e,t=1){return ui(()=>$o(uc($o(e,t)),e))}}function vv(e){return e.getClassName()}function kv(e,t={}){return Ny(e,Go.getMap().classNameMap,t,"activation")}function Iv(e){if(null==e){return kv({className:"linear",config:{}})}if("string"==typeof e){const t={};return t.className=e,t.config={},kv(t)}return e instanceof sv?e:kv(e)}function Sv(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer\'s constructor is expected to be an object, but received: ${e}`)}wv.className="swish",Ho(wv);class Nv extends Wo{}
vendor: 25,292 bytes, line 5057
5057class Tv extends Nv{constructor(e){super(),Sv(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return ui(()=>{let t=Hh([1]);return this.hasL1&&(t=To(t,oh($o(this.l1,eu(e))))),this.hasL2&&(t=To(t,oh($o(this.l2,yb(e))))),sc(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Tv.className="L1L2",Ho(Tv);const Ev={l1l2:"L1L2"};function Cv(e){return Iy(e)}function $v(e,t={}){return Ny(e,Go.getMap().classNameMap,t,"regularizer")}function Av(e){return null==e?null:"string"==typeof e?$v({className:e in Ev?Ev[e]:e,config:{}}):e instanceof Nv?e:$v(e)}class Rv extends sx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=jb(e);let n=Ed(e);return null!=this.maxValue&&(n=kc(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Rv.className="ReLU",Ho(Rv);class _v extends sx{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=jb(e);return Ih(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}_v.className="LeakyReLU",Ho(_v);class Mv extends sx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Wb(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Av(e.alphaRegularizer),this.alphaConstraint=Sx(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new hy(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=qb(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new Qb({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=jb(e),cd(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Ub(this.alphaInitializer),alphaRegularizer:Cv(this.alphaRegularizer),alphaConstraint:kx(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Mv.className="PReLU",Ho(Mv);class Fv extends sx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new dy(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=jb(e);return Kc(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Fv.className="ELU",Ho(Fv);class Dv extends sx{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=jb(e);return $o(n,Io(bh(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Dv.className="ThresholdedReLU",Ho(Dv);class Ov extends sx{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new mv).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return ui(()=>{let n=jb(e);const r=t.mask;if(null!=r){const e=$o(Zo(jh(n.shape),Io(r,n.dtype)),Bo(-1e9));n=To(n,e)}return this.axis instanceof Array?this.axis.length>1?hh(Zo(n,Mh(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)})}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Lv(e,t,n){if("number"==typeof e)return my(e,t);if(e.length!==t)throw new hy(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let r=0;r<t;++r){const s=e[r];if(!Qy(s))throw new hy(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e}function zv(e,t,n,r,s=1){if(null==e)return e;let a;return a="same"===n?e:e-(t+(t-1)*(s-1))+1,Math.floor((a+r-1)/r)}function Pv(e,t,n,r){if(null==e)return null;if("valid"===r)e=e*t+nb([n-t,0]);else{if("same"!==r)throw new hy(`Unsupport padding mode: ${r}.`);e*=t}return e}function Bv(e,t){return ui(()=>(Gy(t),"channelsFirst"===t?Du(e,[0,2,3,1]):e))}function Vv(e,t){return ui(()=>(Gy(t),"channelsFirst"===t?Du(e,[0,2,3,4,1]):e))}function Uv(e,t,n,r=[1,1],s="valid",a,i,o=null){return ui(()=>{if(null==a&&(a="channelsLast"),Gy(a),3!==e.rank&&4!==e.rank)throw new hy(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new hy(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let u=Bv(e,a);if("causal"===s)throw new dy("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Mp({x:u,filter:t,strides:r,pad:"same"===s?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(u=Du(u,[0,3,1,2])),u})}Ov.className="Softmax",Ho(Ov);class Wv extends sx{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Wv.verifyArgs(t),this.rank=e,Ry(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new dy(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Lv(t.kernelSize,e,"kernelSize"),this.strides=Lv(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,Hy(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,Gy(this.dataFormat),this.activation=Iv(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=Wb(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Sx(t.biasConstraint),this.biasRegularizer=Av(t.biasRegularizer),this.activityRegularizer=Av(t.activityRegularizer),this.dilationRate=Lv(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new hy(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new hy(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new hy(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(gy("kernelSize"in e,"required key \'kernelSize\' not in config"),"number"!=typeof e.kernelSize&&!Ay(e.kernelSize,"number",1,3))throw new hy(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:vv(this.activation),useBias:this.useBias,biasInitializer:Ub(this.biasInitializer),biasRegularizer:Cv(this.biasRegularizer),activityRegularizer:Cv(this.activityRegularizer),biasConstraint:kx(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Gv extends Wv{constructor(e,t){super(e,t),this.kernel=null,Gv.verifyArgs(t),this.filters=t.filters,Ry(this.filters,"filters"),this.kernelInitializer=Wb(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Sx(t.kernelConstraint),this.kernelRegularizer=Av(t.kernelRegularizer)}build(e){e=qb(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new hy(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return ui(()=>{let t;e=jb(e);const n=null==this.bias?null:this.bias.read(),r=My(this.activation.getClassName());if(null!=r&&2===this.rank)t=Uv(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(1===this.rank)t=function(e,t,n,r=1,s="valid",a,i=1){return ui(()=>{if(null==a&&(a="channelsLast"),Gy(a),3!==e.shape.length)throw new hy(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new hy(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new hy(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===a&&(e=Du(e,[0,2,1])),"causal"===s)throw new dy("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Cc(e,t,r,"same"===s?"same":"valid","NWC",i);return null!=n&&(o=xb(o,n)),o})}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=Uv(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new dy("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,r=[1,1,1],s="valid",a,i){return ui(()=>{if(null==a&&(a="channelsLast"),Gy(a),4!==e.rank&&5!==e.rank)throw new hy(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new hy(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=Vv(e,a);if("causal"===s)throw new dy("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Rc(o,t,r,"same"===s?"same":"valid","NDHWC",i),null!=n&&(o=xb(o,n)),"channelsFirst"===a&&(o=Du(o,[0,4,1,2,3])),o})}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t})}computeOutputShape(e){e=qb(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const r=zv(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(r)}let r=[e[0]];return"channelsLast"===this.dataFormat?(r=r.concat(t),r.push(this.filters)):(r.push(this.filters),r=r.concat(t)),r}getConfig(){const e={filters:this.filters,kernelInitializer:Ub(this.kernelInitializer),kernelRegularizer:Cv(this.kernelRegularizer),kernelConstraint:kx(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new hy(`Convolution layer expected config.filters to be a \'number\' > 0 but got ${JSON.stringify(e.filters)}`)}}class Hv extends Gv{constructor(e){super(2,e),Hv.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Ay(e.kernelSize,"number",1,2))throw new hy(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Hv.className="Conv2D",Ho(Hv);class jv extends Gv{constructor(e){super(3,e),jv.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new hy(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}jv.className="Conv3D",Ho(jv);class qv extends Hv{constructor(e){if(super(e),this.inputSpec=[new Qb({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new hy(`Conv2DTranspose currently supports only padding modes \'same\' and \'valid\', but received padding mode ${this.padding}`)}build(e){if(4!==(e=qb(e)).length)throw new hy("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new hy("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Qb({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return ui(()=>{let t=jb(e);if(4!==t.shape.length)throw new hy(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a;"channelsFirst"===this.dataFormat?(s=2,a=3):(s=1,a=2);const i=n[s],o=n[a],u=this.kernelSize[0],l=this.kernelSize[1],c=this.strides[0],h=this.strides[1],d=[r,Pv(i,c,u,this.padding),Pv(o,h,l,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Du(t,[0,2,3,1]));let p=Ac(t,this.kernel.read(),d,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(p=Du(p,[0,3,1,2])),null!=this.bias&&(p=xb(p,this.bias.read(),this.dataFormat)),null!=this.activation&&(p=this.activation.apply(p)),p})}computeOutputShape(e){const t=(e=qb(e)).slice();let n,r,s;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3):(n=3,r=1,s=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],u=this.strides[1];return t[n]=this.filters,t[r]=Pv(t[r],o,a,this.padding),t[s]=Pv(t[s],u,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}qv.className="Conv2DTranspose",Ho(qv);class Kv extends jv{constructor(e){if(super(e),this.inputSpec=[new Qb({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new hy(`Conv3DTranspose currently supports only padding modes \'same\' and \'valid\', but received padding mode ${this.padding}`)}build(e){if(5!==(e=qb(e)).length)throw new hy("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new hy("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Qb({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return ui(()=>{let t=jb(e);if(5!==t.shape.length)throw new hy(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a,i;"channelsFirst"===this.dataFormat?(i=2,s=3,a=4):(i=1,s=2,a=3);const o=n[i],u=n[s],l=n[a],c=this.kernelSize[0],h=this.kernelSize[1],d=this.kernelSize[2],p=this.strides[0],f=this.strides[1],m=this.strides[2],g=[r,Pv(o,p,c,this.padding),Pv(u,f,h,this.padding),Pv(l,m,d,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Du(t,[0,2,3,4,1]));let y=Mc(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=Du(y,[0,4,1,2,3])),null!==this.bias&&(y=xb(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y})}computeOutputShape(e){const t=(e=qb(e)).slice();let n,r,s,a;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3,a=4):(n=4,r=1,s=2,a=3);const i=this.kernelSize[0],o=this.kernelSize[1],u=this.kernelSize[2],l=this.strides[0],c=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[r]=Pv(t[r],l,i,this.padding),t[s]=Pv(t[s],c,o,this.padding),t[a]=Pv(t[a],h,u,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Kv.className="Conv3DTranspose",Ho(Kv);class Xv extends Gv{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new hy("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new hy("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new hy(`SeparableConv${this.rank}D supports only padding modes: \'same\' and \'valid\', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=Wb(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Av(t.depthwiseRegularizer),this.depthwiseConstraint=Sx(t.depthwiseConstraint),this.pointwiseInitializer=Wb(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Av(t.pointwiseRegularizer),this.pointwiseConstraint=Sx(t.pointwiseConstraint)}build(e){if((e=qb(e)).length<this.rank+2)throw new hy(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new hy(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],r=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let e=0;e<this.rank;++e)s.push(1);s.push(n*this.depthMultiplier,this.filters);const a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new Qb({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return ui(()=>{let t;if(e=jb(e),1===this.rank)throw new dy("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=Du(e,[0,2,3,1])),t=Ld(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=xb(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=Du(t,[0,3,1,2])),t})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ub(this.depthwiseInitializer),e.pointwiseInitializer=Ub(this.pointwiseInitializer),e.depthwiseRegularizer=Cv(this.depthwiseRegularizer),e.pointwiseRegularizer=Cv(this.pointwiseRegularizer),e.depthwiseConstraint=kx(this.depthwiseConstraint),e.pointwiseConstraint=kx(this.pointwiseConstraint),e}}Xv.className="SeparableConv";class Yv extends Xv{constructor(e){super(2,e)}}Yv.className="SeparableConv2D",Ho(Yv);class Jv extends Gv{constructor(e){super(1,e),Jv.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Ay(e.kernelSize,"number",1,1))throw new hy(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Jv.className="Conv1D",Ho(Jv);class Zv extends sx{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return ui(()=>{if(e=jb(e),"channelsLast"===this.dataFormat){const t=cb(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return cb(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=cb(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return cb(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Zv.className="Cropping2D",Ho(Zv);class Qv extends sx{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Gy(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,$y(Py,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return ui(()=>{let t=jb(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=Du(t,[0,2,3,1]);const e=this.size[0]*n[2],r=this.size[1]*n[3],s="nearest"===this.interpolation?Df.resizeNearestNeighbor(t,[e,r]):Df.resizeBilinear(t,[e,r]);return Du(s,[0,3,1,2])}{const e=this.size[0]*n[1],r=this.size[1]*n[2];return"nearest"===this.interpolation?Df.resizeNearestNeighbor(t,[e,r]):Df.resizeBilinear(t,[e,r])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}Qv.className="UpSampling2D",Ho(Qv);class ek extends Wv{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Wb(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Sx(e.depthwiseConstraint),this.depthwiseRegularizer=Av(e.depthwiseRegularizer)}build(e){if((e=qb(e)).length<4)throw new hy(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new hy(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ui(()=>{let t=function(e,t,n=[1,1],r="valid",s,a){return ui(()=>{null==s&&(s="channelsLast"),Gy(s);let i=Bv(e,s);if(4!==e.rank)throw new hy(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new hy(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Bc(i,t,n,"same"===r?"same":"valid","NHWC",a),"channelsFirst"===s&&(i=Du(i,[0,3,1,2])),i})}(e=jb(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=xb(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t})}computeOutputShape(e){e=qb(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=zv(t,this.kernelSize[0],this.padding,this.strides[0]),a=zv(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,s,a]:[e[0],s,a,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ub(this.depthwiseInitializer),e.depthwiseRegularizer=Cv(this.depthwiseRegularizer),e.depthwiseConstraint=kx(this.depthwiseRegularizer),e}}function tk(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new hy("When input
5057s is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function s(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=s(t),constants:n=s(n)}}function nk(e,t,n,r=!1,s,a,i=!1,o=!1){return ui(()=>{const u=t.shape.length;if(u<3)throw new hy(`Input should be at least 3D, but is ${u}D.`);const l=[1,0].concat(rb(2,u));if(t=Du(t,l),null!=a)throw new dy("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=s&&((s=Io(Io(s,"bool"),"float32")).rank===u-1&&(s=dh(s,-1)),s=Du(s,l)),r&&(t=$d(t,0),null!=s&&(s=$d(s,0)));const c=[];let h,d=n;const p=t.shape[0],f=fp(t);let m,g;null!=s&&(m=fp(s));for(let t=0;t<p;++t){const n=f[t],r=ui(()=>e(n,d));if(null==s)h=r[0],d=r[1];else{const e=ui(()=>{const e=m[t],n=Zo(td(e),e);return{output:To($o(r[0],e),$o(d[0],n)),newStates:d.map((t,s)=>To($o(r[1][s],e),$o(t,n)))}});h=e.output,d=e.newStates}o&&c.push(h)}return o&&(g=ep(c,1)),[h,g,d]})}ek.className="DepthwiseConv2D",Ho(ek);class rk extends sx{constructor(e){let t;if(super(e),null==e.cell)throw new hy("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new hk({cells:e.cell}):e.cell,null==t.stateSize)throw new hy("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Qb({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return null==this.states_?rb(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(e=>null):this.states_}setStates(e){this.states_=e}computeOutputShape(e){Gb(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let r;if(r=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const r of t)n.push([e[0],r]);return[r].concat(n)}return r}computeMask(e,t){return ui(()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map(e=>null);return[e].concat(t)}return e})}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new dy("Constants support is not implemented in RNN yet.");Gb(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Qb({shape:[t,null,...n]});const r=[e[0]].concat(e.slice(2));let s;if(this.cell.build(r),s=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!de(this.stateSpec.map(e=>e.shape[e.shape.length-1]),s))throw new hy(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=s.map(e=>new Qb({shape:[null,e]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){ui(()=>{if(!this.stateful)throw new ly("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new hy("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \\n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(e=>Hh([n,e])):this.states_=[Hh([n,this.cell.stateSize])];else if(null==e)li(this.states_),null!=this.keptStates&&(li(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(e=>Hh([n,e])):this.states_[0]=Hh([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new hy(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):li(this.states_);for(let t=0;t<this.states_.length;++t){const r=e[t],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,a=[n,s];if(!de(r.shape,a))throw new hy(`State ${t} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${r.shape}`);this.states_[t]=r}}this.states_=this.states_.map(e=>ci(e.clone()))})}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=tk(e,n,r,this.numConstants);e=s.inputs,n=s.initialState,r=s.constants;let a=[],i=[];if(null!=n){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new Qb({shape:e.shape}));i=i.concat(this.stateSpec)}if(null!=r&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof ex){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return ui(()=>{const n=null==t?null:t.mask,r=null==t?null:t.training;let s=null==t?null:t.initialState;e=jb(e),null==s&&(s=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new hy(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:r},o=nk((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]},e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),u=o[0],l=o[1],c=o[2];this.stateful&&this.resetStates(c,r);const h=this.returnSequences?l:u;return this.returnState?[h].concat(c):h})}getInitialState(e){return ui(()=>{let t=Hh(e.shape);return t=oh(t,[1,2]),t=ob(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(e=>e>1?pb(t,[1,e]):t):this.cell.stateSize>1?[pb(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===rk.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const r=tw(t.cell,n);return new e(Object.assign(t,{cell:r}))}}rk.className="RNN",Ho(rk);class sk extends sx{}class ak extends sk{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ry(this.units,"units"),this.activation=Iv(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Wb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Wb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Wb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Av(e.kernelRegularizer),this.recurrentRegularizer=Av(e.recurrentRegularizer),this.biasRegularizer=Av(e.biasRegularizer),this.kernelConstraint=Sx(e.kernelConstraint),this.recurrentConstraint=Sx(e.recurrentConstraint),this.biasConstraint=Sx(e.biasConstraint),this.dropout=tb([1,nb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=tb([1,nb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=qb(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ui(()=>
vendor: 11,899 bytes, line 5057
5057{if(2!==e.length)throw new hy(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const r=null!=t.training&&t.training;let s;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=dk({ones:()=>td(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=dk({ones:()=>td(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;s=mb(null!=a?$o(e,a):e,this.kernel.read()),null!=this.bias&&(s=xb(s,this.bias.read())),null!=i&&(n=$o(n,i));let o=To(s,mb(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:vv(this.activation),useBias:this.useBias,kernelInitializer:Ub(this.kernelInitializer),recurrentInitializer:Ub(this.recurrentInitializer),biasInitializer:Ub(this.biasInitializer),kernelRegularizer:Cv(this.kernelRegularizer),recurrentRegularizer:Cv(this.recurrentRegularizer),biasRegularizer:Cv(this.biasRegularizer),activityRegularizer:Cv(this.activityRegularizer),kernelConstraint:kx(this.kernelConstraint),recurrentConstraint:kx(this.recurrentConstraint),biasConstraint:kx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}ak.className="SimpleRNNCell",Ho(ak);class ik extends rk{constructor(e){e.cell=new ak(e),super(e)}call(e,t){return ui(()=>{null!=this.cell.dropoutMask&&(li(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(li(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return new e(t)}}ik.className="SimpleRNN",Ho(ik);class ok extends sk{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new hy("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Ry(this.units,"units"),this.activation=Iv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Iv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Wb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Wb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Wb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Av(e.kernelRegularizer),this.recurrentRegularizer=Av(e.recurrentRegularizer),this.biasRegularizer=Av(e.biasRegularizer),this.kernelConstraint=Sx(e.kernelConstraint),this.recurrentConstraint=Sx(e.recurrentConstraint),this.biasConstraint=Sx(e.biasConstraint),this.dropout=tb([1,nb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=tb([1,nb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=qb(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ui(()=>{if(2!==e.length)throw new hy(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let r=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=dk({ones:()=>td(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=dk({ones:()=>td(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,u;0<this.dropout&&this.dropout<1&&(e=$o(e,s[0]));let l=mb(e,this.kernel.read());this.useBias&&(l=xb(l,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(r=$o(r,a[0]));const c=this.recurrentKernel.read(),[h,d]=Yd(c,[2*this.units,this.units],c.rank-1),p=mb(r,h),[f,m,g]=Yd(l,3,l.rank-1),[y,b]=Yd(p,2,p.rank-1);i=this.recurrentActivation.apply(To(f,y)),o=this.recurrentActivation.apply(To(m,b));const x=mb($o(o,r),d);u=this.activation.apply(To(g,x));const w=To($o(i,r),$o(To(1,Mu(i)),u));return[w,w]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:vv(this.activation),recurrentActivation:vv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ub(this.kernelInitializer),recurrentInitializer:Ub(this.recurrentInitializer),biasInitializer:Ub(this.biasInitializer),kernelRegularizer:Cv(this.kernelRegularizer),recurrentRegularizer:Cv(this.recurrentRegularizer),biasRegularizer:Cv(this.biasRegularizer),activityRegularizer:Cv(this.activityRegularizer),kernelConstraint:kx(this.kernelConstraint),recurrentConstraint:kx(this.recurrentConstraint),biasConstraint:kx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}ok.className="GRUCell",Ho(ok);class uk extends rk{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new ok(e),super(e)}call(e,t){return ui(()=>{null!=this.cell.dropoutMask&&(li(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(li(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}uk.className="GRU",Ho(uk);class lk extends sk{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ry(this.units,"units"),this.activation=Iv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Iv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Wb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Wb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Wb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Av(e.kernelRegularizer),this.recurrentRegularizer=Av(e.recurrentRegularizer),this.biasRegularizer=Av(e.biasRegularizer),this.kernelConstraint=Sx(e.kernelConstraint),this.recurrentConstraint=Sx(e.recurrentConstraint),this.biasConstraint=Sx(e.biasConstraint),this.dropout=tb([1,nb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=tb([1,nb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=qb(e))[e.length-1];let r;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;r=new((t=class extends Sb{apply(t,r){const s=e.apply([n]),a=(new Tb).apply([n]),i=e.apply([2*n]);return db(db(s,a),i)}}).className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return ui(()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new hy(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=dk({ones:()=>td(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=dk({ones:()=>td(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,u,l,c;0<this.dropout&&this.dropout<1&&(e=$o(e,a[0]));let h=mb(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(r=$o(r,i[0])),h=To(h,mb(r,this.recurrentKernel.read())),this.useBias&&(h=xb(h,this.bias.read()));const[d,p,f,m]=Yd(h,4,h.rank-1);o=this.recurrentActivation.apply(d),u=this.recurrentActivation.apply(p),l=To($o(u,s),$o(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=$o(c,this.activation.apply(l));return[g,g,l]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:vv(this.activation),recurrentActivation:vv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ub(this.kernelInitializer),recurrentInitializer:Ub(this.recurrentInitializer),biasInitializer:Ub(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Cv(this.kernelRegularizer),recurrentRegularizer:Cv(this.recurrentRegularizer),biasRegularizer:Cv(this.biasRegularizer),activityRegularizer:Cv(this.activityRegularizer),kernelConstraint:kx(this.kernelConstraint),recurrentConstraint:kx(this.recurrentConstraint),biasConstraint:kx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}lk.className="LSTMCell",Ho(lk);class ck extends rk{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new lk(e),super(e)}call(e,t){return ui(()=>{null!=this.cell.dropoutMask&&(li(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(li(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}ck.className="LSTM",Ho(ck);class hk extends sk{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return ui(()=>{let n=e.slice(1);const r=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?r.push(n.splice(0,e.stateSize.length)):r.push(n.splice(0,1));r.reverse();const s=[];let a;for(let i=0;i<this.cells.length;++i){const o=this.cells[i];n=r[i],a=0===i?[e[0]].concat(n):[a[0]].concat(n),a=o.call(a,t),s.push(a.slice(1))}n=[];for(const e of s.slice().reverse())n.push(...e);return[a[0]].concat(n)})}build(e){let t;
5057Gb(e)&&(e=e[0]),this.cells.forEach((n,r)=>{Ky(`RNNCell_${r}`,()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map(e=>({className:e.getClassName(),config:e.getConfig()}))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const r=[];for(const e of t.cells)r.push(tw(e,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Jb(e)}setWeights(e){const t=[];for(const n of this.cells){const r=n.weights.length,s=e.splice(r);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],s[e]])}Zb(t)}}function dk(e){const{ones:t,rate:n,training:r=!1,count:s=1,dropoutFunc:a}=e,i=()=>null!=a?a(t(),n):wb(t(),n),o=()=>vb(i,t,r);return!s||s<=1?ci(o().clone()):Array(s).fill(void 0).map(o).map(e=>ci(e.clone()))}hk.className="StackedRNNCells",Ho(hk);class pk extends rk{constructor(e){if(e.unroll)throw new dy("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new dy("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Qb({ndim:5})]}call(e,t){return ui(()=>{if(null!=this.cell.dropoutMask&&(li(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(li(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new hy("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return ui(()=>{const{stateSize:t}=this.cell,n=e.shape,r=this.computeSingleOutputShape(n),s=Hh([r[0],...r.slice(2)]);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){ui(()=>{if(!this.stateful)throw new ly("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)];if(null==n[0])throw new hy("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \\n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Hh(s)):this.states_=[Hh(s)];else if(null==e)li(this.states_),null!=this.keptStates&&(li(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Hh(s)):this.states_[0]=Hh(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new hy(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):li(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],r=s;if(!de(n.shape,r))throw new hy(`State ${t} is incompatible with layer ${this.name}: expected shape=${r}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map(e=>ci(e.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:r,padding:s,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,u=e[o?3:2],l=e[o?4:3],c=zv(u,r[0],s,a[0],i[0]),h=zv(l,r[1],s,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}pk.className="ConvRNN2D";class fk extends lk{constructor(e){const{filters:t,kernelSize:n,strides:r,padding:s,dataFormat:a,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Ry(this.filters,"filters"),this.kernelSize=Lv(n,2,"kernelSize"),this.kernelSize.forEach(e
5057=>Ry(e,"kernelSize")),this.strides=Lv(r||1,2,"strides"),this.strides.forEach(e=>Ry(e,"strides")),this.padding=s||"valid",Hy(this.padding),this.dataFormat=a||"channelsLast",Gy(this.dataFormat),this.dilationRate=Lv(i||1,2,"dilationRate"),this.dilationRate.forEach(e=>Ry(e,"dilationRate"))}build(e){var t;e=qb(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new hy(`The channel dimension of the input should be defined. Found ${e[n]}`);const r=e[n],s=this.kernelSize.concat([r,4*this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,r=this.filters;e=new((t=class extends Sb{apply(e,t){return hb([n.apply([r]),jh([r]),n.apply([2*r])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return ui(()=>{if(3!==e.length)throw new hy(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,r=e[0],s=e[1],a=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=dk({ones:()=>td(r),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?$o(t[n],e):e;let u=o(r,i,0),l=o(r,i,1),c=o(r,i,2),h=o(r,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=dk({ones:()=>td(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const d=this.recurrentDropoutMask;let p=o(s,d,0),f=o(s,d,1),m=o(s,d,2),g=o(s,d,3);const[y,b,x,w]=Yd(this.kernel.read(),4,3),[v,k,I,S]=this.useBias?Yd(this.bias.read(),4):[null,null,null,null];u=this.inputConv(u,y,v,this.padding),l=this.inputConv(l,b,k,this.padding),c=this.inputConv(c,x,I,this.padding),h=this.inputConv(h,w,S,this.padding);const[N,T,E,C]=Yd(this.recurrentKernel.read(),4,3);p=this.recurrentConv(p,N),f=this.recurrentConv(f,T),m=this.recurrentConv(m,E),g=this.recurrentConv(g,C);const $=this.recurrentActivation.apply(To(u,p)),A=this.recurrentActivation.apply(To(l,f)),R=To($o(A,a),$o($,this.activation.apply(To(c,m)))),_=$o(this.recurrentActivation.apply(To(h,g)),this.activation.apply(R));return[_,_,R]})}getConfig(){const e=super.getConfig(),{units:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),r)}inputConv(e,t,n,r){const s=Ec(e,t,this.strides,r||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?xb(s,n,this.dataFormat):s}recurrentConv(e,t){return Ec(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}fk.className="ConvLSTM2DCell",Ho(fk);class mk extends pk{constructor(e){const t=new fk(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}mk.className="ConvLSTM2D",Ho(mk);class gk extends sx{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,r=this.getNoiseShape(n);return vb(()=>wb(n,this.rate,r,this.seed),()=>n,e)}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}
vendor: 9,876 bytes, line 5057
5057gk.className="Dropout",Ho(gk);class yk extends gk{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}yk.className="SpatialDropout1D",Ho(yk);class bk extends sx{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Ry(this.units,"units"),this.activation=Iv(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=Wb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Wb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Sx(e.kernelConstraint),this.biasConstraint=Sx(e.biasConstraint),this.kernelRegularizer=Av(e.kernelRegularizer),this.biasRegularizer=Av(e.biasRegularizer),this.activityRegularizer=Av(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=qb(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=qb(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e),r=My(this.activation.getClassName());let s;return null!=r?s=mb(n,this.kernel.read(),r,this.bias?this.bias.read():null):(s=mb(n,this.kernel.read()),null!=this.bias&&(s=xb(s,this.bias.read())),null!=this.activation&&(s=this.activation.apply(s))),s})}getConfig(){const e={units:this.units,activation:vv(this.activation),useBias:this.useBias,kernelInitializer:Ub(this.kernelInitializer),biasInitializer:Ub(this.biasInitializer),kernelRegularizer:Cv(this.kernelRegularizer),biasRegularizer:Cv(this.biasRegularizer),activityRegularizer:Cv(this.activityRegularizer),kernelConstraint:kx(this.kernelConstraint),biasConstraint:kx(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}bk.className="Dense",Ho(bk);class xk extends sx{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=qb(e);for(const t of e.slice(1))if(null==t)throw new hy(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],eb(e,1)]}call(e,t){return ui(()=>{this.invokeCallHook(e,t);let n=jb(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=Du(n,e)}return function(e){if(e.rank<=1)throw new hy(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],eb(e.shape,1)];return sc(e,t)}(n)})}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}xk.className="Flatten",Ho(xk);class wk extends sx{constructor(e){super(e),this.supportsMasking=!0,this.activation=Iv(e.activation)}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e);return this.activation.apply(n)})}getConfig(){const e={activation:vv(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}wk.className="Activation",Ho(wk);class vk extends sx{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return ui(()=>{return e=jb(e),t=e,n=this.n,ui(()=>{if(2!==t.shape.length)throw new hy(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return pb(ob(t,1),[1,n,1])});var t,n})}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}vk.className="RepeatVector",Ho(vk);class kk extends sx{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",r=t.slice();let s=1,a=null;for(let e=0;e<r.length;++e){const t=r[e];if(this.isUnknown(t)){if(null!==a)throw new hy("Can only specifiy one unknown dimension.");a=e}else s*=t}const i=eb(e);if(null!==a){if(0===s||i%s!==0)throw new hy(n);r[a]=i/s}else if(i!==s)throw new hy(n);return r}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e),r=n.shape,s=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return sc(n,s)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}kk.className="Reshape",Ho(kk);class Ik extends sx{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \\`dims\\` to be an Array, but received ${e.dims} instead.`);const t=rb(1,e.dims.length+1);if(!de(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Qb({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=qb(e)).slice();return this.dims.forEach((n,r)=>{t[r+1]=e[n]}),t}call(e,t){return Du(jb(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Ik.className="Permute",Ho(Ik);class Sk extends sx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=jb(e);return Dl(ed(n,this.maskValue),-1)}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e),r=Dl(ed(n,this.maskValue),-1,!0);return $o(n,Io(r,n.dtype))})}}Sk.className="Masking",Ho(Sk);class Nk extends sx{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(xy(e.inputLength))}this.inputDim=e.inputDim,Ry(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Ry(this.outputDim,"outputDim"),this.embeddingsInitializer=Wb(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Av(e.embeddingsRegularizer),this.activityRegularizer=Av(e.activityRegularizer),this.embeddingsConstraint=Sx(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return ui(()=>this.maskZero?(e=jb(e),ed(e,_o(e))):null)}computeOutputShape(e){if(e=qb(e),null==this.inputLength)return[...e,this.outputDim];const t=xy(this.inputLength);if(t.length!==e.length-1)throw new hy(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r<t.length;++r){const s=t[r],a=e[r+1];if(null!=s&&null!=a&&s!==a)throw new hy(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==s&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return ui(()=>{this.invokeCallHook(e,t);let n=jb(e);"int32"!==n.dtype&&(n=ib(n,"int32"));const r=gb(this.embeddings.read(),sc(n,[n.size]));return sc(r,qb(this.computeOutputShape(n.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ub(this.embeddingsInitializer),embeddingsRegularizer:Cv(this.embeddingsRegularizer),activityRegularizer:Cv(this.activityRegularizer),embeddingsConstraint:kx(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Nk.className="Embedding",Ho(Nk);class Tk extends sx{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new dy}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let r=0;r<t.length;++r){const s=e[e.length-t.length+r],a=t[r];if(null==s||null==a||s<0||a<0)n.push(null);else if(1===s)n.push(a);else if(1===a)n.push(s);else{if(s!==a)throw new hy("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(s)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[qb(e)]),e.length<2)throw new hy(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=Ey(t),t.length>1)throw new hy(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const r=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,r)}const r=e.map(e=>e.length);-1===e.indexOf(null)&&1===Ey(r).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return ui(()=>
5057{if(this.reshapeRequired){const t=[],n=e.map(e=>e.rank);if(-1===n.indexOf(null)){const r=nb(n);for(let n of e){const e=n.rank;for(let t=0;t<r-e;++t)n=ob(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const r of e){const e=r.rank;if(null==e){const e=r.shape,s=e[0],a=e.slice(1).concat([s]);let i=sc(r,[s].concat(eb(e.slice(1))));i=Du(i,[1,0]),i=sc(i,a),t.push(i),n=!0}else if(e>1){const s=rb(1,e).concat([0]);t.push(Du(r,s)),n=!0}else t.push(r)}let r=this.mergeFunction(t);const s=r.rank;if(n)if(null==s){const e=r.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));r=sc(Du(sc(r,[-1,t]),[1,0]),n)}else if(s>1){const e=[s-1].concat(rb(0,s-1));r=Du(r,e)}return r}}return this.mergeFunction(e)})}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const r=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=Ey(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return ui(()=>{if(null==t)return null;if(!Array.isArray(t))throw new hy("`mask` should be an Array");if(!Array.isArray(e))throw new hy("`inputs` should be an Array");if(t.length!==e.length)throw new hy(`The Array \'inputs\' and \'mask\' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(e=>null==e))return null;let n=(t=t.map(e=>null==e?e:dh(e,0)))[0];for(let e=1;e<t.length-1;++e)n=Fh(n,t[e]);return n})}}class Ek extends Tk{constructor(e){super(e)}mergeFunction(e){return ui(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=To(t,e[n]);return t})}}Ek.className="Add",Ho(Ek);class Ck extends Tk{constructor(e){super(e)}mergeFunction(e){return ui(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=$o(t,e[n]);return t})}}Ck.className="Multiply",Ho(Ck);class $k extends Tk{constructor(e){super(e)}mergeFunction(e){return ui(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=To(t,e[n]);return $o(1/e.length,t)})}}$k.className="Average",Ho($k);class Ak extends Tk{constructor(e){super(e)}mergeFunction(e){return ui(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=su(t,e[n]);return t})}}Ak.className="Maximum",Ho(Ak);class Rk extends Tk{constructor(e){super(e)}mergeFunction(e){return ui(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Kh(t,e[n]);return t})}}Rk.className="Minimum",Ho(Rk);class _k extends Tk{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new hy("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const r=e[t].slice();r.splice(this.axis,1);let s=!1;for(const e of n)if(de(e,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new hy("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return ui(()=>hb(e,this.axis))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new hy("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[r]||null==e[r]){n[r]=null;break}n[r]+=e[r]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new hy("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new hy("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new hy(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return ui(()=>{let n=!0;if(t.forEach(e=>{null==e||(n=!1)}),n)return null;const r=[];for(let n=0;n<e.length;++n)null==t[n]?r.push(Io(td(e[n]),"bool")):t[n].rank<e[n].rank?r.push(dh(t[n],-1)):r.push(t[n]);const s=oc(r,this.axis);return Fl(s,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Mk(e,t){for(;e<0;)e+=t;return e}_k.className="Concatenate",Ho(_k);class Fk extends Tk{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new dy("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new hy(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(2!==e.length)throw new hy(`A \\`Dot\\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map((t,n)=>Mk(t,e[n].shape.length)):[Mk(this.axes,n.shape.length),Mk(this.axes,r.shape.length)],this.normalize&&(n=nw(n,t[0]),r=nw(r,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new dy("batchDot is not implemented for tensors of 4D or higher rank yet");if(ie(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),ie(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new dy("batchDot is not implemented for complex64-type Tensors yet.");const r=e.shape.length,s=t.shape.length;null==n&&(n=[r-1,s-2]);const a=n;return ui(()=>{let n,i;if(r>s){n=r-s;const e=[];for(let t=0;t<n;++t)e.push(1);t=sc(t,t.shape.concat(e))}else if(s>r){n=s-r;const t=[];for(let e=0;e<n;++e)t.push(1);e=sc(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=a[0]===a[1]?oh($o(e,t),a[0]):oh($o(Du(e,[1,0]),t),a[1]);else{const n=a[0]!==e.shape.length-1,r=a[1]===t.shape.length-1;i=Au(e,t,n,r)}if(n>0){let e;e=r>s?r+s-3:r-1;const t=[];for(let r=e;r<e+n;++r)t.push(r);i=Qd(i,t)}return 1===i.shape.length&&(i=dh(i,1)),i})}(n,r,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[Mk(this.axes,e.length),Mk(this.axes,t.length)],n}computeOutputShape(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new dy("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);const s=t.concat(n);return 1===s.length&&s.push(1),s}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Fk.className="Dot",Ho(Fk);class Dk extends sx{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e);return vb(()=>To(fb(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}}Dk.className="GaussianNoise",Ho(Dk);class Ok extends sx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ui(()=>{this.invokeCallHook(e,t);const n=jb(e);return this.rate>0&&this.rate<1?vb(()=>{const e=Math.sqrt(this.rate/(1-this.rate));return $o(n,fb(n.shape,1,e))},()=>n,t.training||!1):n})}}Ok.className="GaussianDropout",Ho(Ok);class Lk extends sx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||jb(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ui(()=>
vendor: 29,200 bytes, line 5057
5057{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),r=()=>{const t=jb(e),r=-1.7580993408473766;let s=xh(Id(n),this.rate);s=ib(s,"float32");const a=((1-this.rate)*(1+this.rate*r**2))**-.5,i=-a*r*this.rate,o=To($o(t,s),$o(To(s,-1),r));return To($o(o,a),i)};return vb(r,()=>jb(e),t.training||!1)}return e})}}function zk(e,t,n,r,s,a=.001){let i;if(2===e.rank)i=fc(e,t,n,r,s,a);else if(3===e.rank)i=mc(e,t,n,r,s,a);else{if(4!==e.rank)throw new dy(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=gc(e,t,n,r,s,a)}return i}Lk.className="AlphaDropout",Ho(Lk);class Pk extends sx{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Wb(e.betaInitializer||"zeros"),this.gammaInitializer=Wb(e.gammaInitializer||"ones"),this.movingMeanInitializer=Wb(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Wb(e.movingVarianceInitializer||"ones"),this.betaConstraint=Sx(e.betaConstraint),this.gammaConstraint=Sx(e.gammaConstraint),this.betaRegularizer=Av(e.betaRegularizer),this.gammaRegularizer=Av(e.gammaRegularizer)}build(e){e=qb(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new hy(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Qb({ndim:e.length,axes:{[t]:n}})];const r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return ui(()=>{const n=null!=t.training&&t.training,r=jb(e),s=r.shape,a=s.length,i=rb(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const u=my(1,a);u[o]=s[o];const l=i.slice();l.sort();const c=!de(l,rb(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=sc(this.movingMean.read(),u),t=sc(this.movingVariance.read(),u),n=this.center?sc(this.beta.read(),u):null,s=this.scale?sc(this.gamma.read(),u):null;return zk(r,e,t,n,s,this.epsilon)}return zk(r,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,d,p]=function(e,t,n,r,s=.001){return de(r.slice().sort(),rb(0,e.rank-1))?function(e,t,n,r,s=.001){return ui(()=>{const a=Jh(e,r),i=a.mean,o=a.variance;return[zk(e,i,o,n,t,s),i,o]})}(e,t,n,r,s):function(e,t,n,r,s=.001){return ui(()=>{const a=Jh(e,r),i=a.mean,o=a.variance,u=[];for(const t of rb(0,e.rank))-1!==r.indexOf(t)?u.push(1):u.push(e.shape[t]);const l=sc(i,u),c=sc(o,u),h=null==t?null:sc(t,u),d=null==n?null:sc(n,u);return[zk(e,l,c,d,h,s),i,o]})}(e,t,n,r,s)}(r,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{ui(()=>{const r=1-n,s=e.read(),a=$o(Zo(s,t),r);e.write(Zo(s,a))})};return(()=>{f(this.movingMean,d,this.momentum),f(this.movingVariance,p,this.momentum)})(),h})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ub(this.betaInitializer),gammaInitializer:Ub(this.gammaInitializer),movingMeanInitializer:Ub(this.movingMeanInitializer),movingVarianceInitializer:Ub(this.movingVarianceInitializer),betaRegularizer:Cv(this.betaRegularizer),gammaRegularizer:Cv(this.gammaRegularizer),betaConstraint:kx(this.betaConstraint),gammaConstraint:kx(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Pk.className="BatchNormalization",Ho(Pk);class Bk extends sx{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Wb(e.betaInitializer||"zeros"),this.gammaInitializer=Wb(e.gammaInitializer||"ones"),this.betaRegularizer=Av(e.betaRegularizer),this.gammaRegularizer=Av(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=qb(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==Ey(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map(t=>e[t]),r=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){const n=jb(e),r=n.shape,s=r.length;return ui(()=>{let{mean:e,variance:t}=Jh(n,this.axis,!0);const a=my(1,s);for(const e of this.axis)a[e]=r[e];const i=e=>null!=e&&e.shape.length!==s?sc(e,a):e;let o=this.scale?i(this.gamma.read()):null,u=this.center?i(this.beta.read()):null;const l=[],c=[];for(let e=0;e<s;++e)-1!==this.axis.indexOf(e)?(l.push(r[e]),c.push(1)):(l.push(1),c.push(r[e]));return e=fh(e,l),t=fh(t,l),null!=o&&(o=fh(o,c)),null!=u&&(u=fh(u,c)),zk(n,e,t,u,o,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ub(this.betaInitializer),gammaInitializer:Ub(this.gammaInitializer),betaRegularizer:Cv(this.betaRegularizer),gammaRegularizer:Cv(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}Bk.className="LayerNormalization",Ho(Bk);class Vk extends sx{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new hy(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new hy(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new hy(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Qb({ndim:4})]}computeOutputShape(e){let t,n;return e=qb(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return ui(()=>{return t=jb(e),n=this.padding,r=this.dataFormat,ui(()=>{if(4!==t.rank)throw new hy(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new hy("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r="channelsLast"),"channelsLast"!==r&&"channelsFirst"!==r)throw new hy(`Unknown data format: ${r}. Supported data formats are \'channelsLast\' and \'channelsFirst.`);let e;return e="channelsFirst"===r?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],rd(t,e)});var t,n,r})}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function Uk(e,t,n,r,s,a){return ui(()=>{let i;Gy(s),jy(a),Hy(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=Bv(e,s);const o="same"===r?"same":"valid";return i="max"===a?Vh(e,t,n,o):ac(e,t,n,o),"channelsFirst"===s&&(i=Du(i,[0,3,1,2])),i})}function Wk(e,t,n,r,s,a){return ui(()=>{let i;Gy(s),jy(a),Hy(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=Vv(e,s);const o="same"===r?"same":"valid";return i="max"===a?Uh(e,t,n,o):ic(e,t,n,o),"channelsFirst"===s&&(i=Du(i,[0,4,1,2,3])),i})}Vk.className="ZeroPadding2D",Ho(Vk);class Gk extends sx{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new hy(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Ry(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new hy(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Ry(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,Hy(this.padding),this.inputSpec=[new Qb({ndim:3})]}computeOutputShape(e){const t=zv((e=qb(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return ui(()=>{this.invokeCallHook(e,t),e=ob(jb(e),2);const n=this.poolingFunction(jb(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Qd(n,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Hk extends Gk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Uk(e,t,n,r,s,"max")}}Hk.className="MaxPooling1D",Ho(Hk);class jk extends Gk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Uk(e,t,n,r,s,"avg")}}jk.className="AveragePooling1D",Ho(jk);class qk extends sx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new hy(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Ry(this.poolSize,"poolSize"),Ry(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Gy(this.dataFormat),Hy(this.padding),this.inputSpec=[new Qb({ndim:4})]}computeOutputShape(e){e=qb(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=zv(t,this.poolSize[0],this.padding,this.strides[0]),n=zv(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return ui(()=>(this.invokeCallHook(e,t),this.poolingFunction(jb(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Kk extends qk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Uk(e,t,n,r,s,"max")}}Kk.className="MaxPooling2D",Ho(Kk);class Xk extends qk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Uk(e,t,n,r,s,"avg")}}Xk.className="AveragePooling2D",Ho(Xk);class Yk extends sx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new hy(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Ry(this.poolSize,"poolSize"),Ry(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Gy(this.dataFormat),Hy(this.padding),this.inputSpec=[new Qb({ndim:5})]}computeOutputShape(e){e=qb(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[4]:e[3];return t=zv(t,this.poolSize[0],this.padding,this.strides[0]),n=zv(n,this.poolSize[1],this.padding,this.strides[1]),r=zv(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return ui(()=>(this.invokeCallHook(e,t),this.poolingFunction(jb(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Jk extends Yk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Wk(e,t,n,r,s,"max")}}Jk.className="MaxPooling3D",Ho(Jk);class Zk extends Yk{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Gy(s),Hy(r),Wk(e,t,n,r,s,"avg")}}Zk.className="AveragePooling3D",Ho(Zk);class Qk extends sx{constructor(e){super(e),this.inputSpec=[new Qb({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new dy}}class eI extends Qk{constructor(e){super(e||{})}call(e,t){return ui(()=>{const t=jb(e);return Gh(t,1)})}}eI.className="GlobalAveragePooling1D",Ho(eI);class tI extends Qk{constructor(e){super(e||{})}call(e,t){return ui(()=>{const t=jb(e);return ah(t,1)})}}tI.className="GlobalMaxPooling1D",Ho(tI);class nI extends sx{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Gy(this.dataFormat),this.inputSpec=[new Qb({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new dy}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class rI extends nI{call(e,t){return ui(()=>{const t=jb(e);return"channelsLast"===this.dataFormat?Gh(t,[1,2]):Gh(t,[2,3])})}}rI.className="GlobalAveragePooling2D",Ho(rI);class sI extends nI{call(e,t){return ui(()=>{const t=jb(e);return"channelsLast"===this.dataFormat?ah(t,[1,2]):ah(t,[2,3])})}}sI.className="GlobalMaxPooling2D",Ho(sI);class aI extends sx{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const r=tw(t.layer,n);delete t.layer;const s={layer:r};return Object.assign(s,t),new e(s)}}class iI extends aI{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=qb(e)).length<3)throw new hy(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=qb(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return ui(()=>nk((e,n)=>[jb(this.layer.call(e,t)),[]],e=jb(e),[],!1,null,null,!1,!0)[1])}}iI.className="TimeDistributed",Ho(iI);class oI extends aI{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=tw(n),t.goBackwards=!0!==t.goBackwards;const r={};var s;if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=tw(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,s=this.mergeMode,$y(Uy,"BidirectionalMergeMode",s),e.weights)throw new dy("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,r,s=this.forwardLayer.computeOutputShape(e);return Array.isArray(s)&&Array.isArray(s[0])||(s=[s]),this.returnState?(r=s.slice(1),t=s[0]):t=s[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):by(n)}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=tk(e,n,r,this.numConstants);if(e=s.inputs,n=s.initialState,r=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==r)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new hy("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);const r=n.map(e=>new Qb({shape:e.shape}));this.forwardLayer.stateSpec=r.slice(0,e/2),this.backwardLayer.stateSpec=r.slice(e/2),i.push(...r)}if(null!=r)throw new dy("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof ex;for(const e of a)if(e instanceof ex!==o)throw new hy("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return ui(()=>{const n=t.initialState;let r,s,a,i;if(null==n)r=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(s.slice(1))),r=r[0],s=s[0]),this.returnSequences&&(s=$d(s,1)),"concat"===this.mergeMode?i=hb([r,s]):"sum"===this.mergeMode?i=To(r,s):"ave"===this.mergeMode?i=$o(.5,To(r,s)):"mul"===this.mergeMode?i=$o(r,s):null==this.mergeMode&&(i=[r,s]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Ky(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ky(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map(e=>null);return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=tw(t.layer);if(delete t.layer,null!=t.numConstants)throw new dy("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=n,new e(r)}}oI.className="Bidirectional",Ho(oI);class uI extends sx{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return ui(()=>("float32"!==(e=jb(e)).dtype&&(e=ib(e,"float32")),To($o(e,this.scale),this.offset)))}}uI.className="Rescaling",Ho(uI);const{resizeBilinear:lI,cropAndResize:cI}=Df;class hI extends sx{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,r,s,a,i,o){return ui(()=>{let u,l=!1;const c=[t/a,n/i,(r+t)/a,(s+n)/i],h=[];3===e.rank?(l=!0,u=ep([e])):u=e;for(let e=0;e<u.shape[0];e++)h.push(c);const d=Ja(h,[h.length,4]),p=Nd(0,h.length,1,"int32"),f=cI(u,d,p,[r,s],"nearest");return ib(l?jb(fp(f)):f,o)})}upsize(e,t,n,r){return ui(()=>ib(lI(e,[t,n]),r))}call(e,t){return ui(()=>{const t=jb(e),n=t.dtype,r=t.shape,s=r[r.length-3],a=r[r.length-2];let i=0;s!==this.height&&(i=Math.floor((s-this.height)/2));let o=0;return a!==this.width&&(o=Math.floor((a-this.width)/2),0===o&&(o=1)),i>=0&&o>=0?this.centerCrop(t,i,o,this.height,this.width,s,a,n):this.upsize(e,this.height,this.width,n)})}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=qb(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}hI.className="CenterCrop",Ho(hI);class dI extends sx{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=qb(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return ui(()=>{let n;if("int32"!==(e=jb(e)).dtype&&(e=ib(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new hy(`countWeights is not used when outputMode !== count.\\n              Received countWeights=${t.countWeights}`);n=jb(t.countWeights)}const r=ah(e),s=ih(e),a=bh(this.numTokens,r).bufferSync().get(0),i=xh(s,0).bufferSync().get(0);if(!a||!i)throw new hy(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,r){let s=jb(e);if("int32"!==s.dtype&&(s=ib(s,"int32")),"int"===t)return s;const a=s.shape;if(0===s.rank&&(s=dh(s,-1)),"oneHot"===t&&1!==s.shape[s.shape.length-1]&&(s=dh(s,-1)),s.rank>2)throw new hy(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${a} which would result in output rank ${s.rank}.`);const i=["multiHot","oneHot"].includes(t);let o;if(o=zc(s,void 0!==r&&"count"===t?r:[],n,i),"tfIdf"!==t)return o;if(r)return $o(o,r);throw new hy("When outputMode is \'tfIdf\', weights must be provided.")}(e,this.outputMode,this.numTokens,n)})}}dI.className="CategoryEncoding",Ho(dI);const pI=new Set(["bilinear","nearest"]);class fI extends sx{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!pI.has(e.interpolation))throw new hy(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){const t=(e=qb(e))[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return ui(()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return Df.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return Df.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...pI]} are supported`)})}}fI.className="Resizing",Ho(fI);class mI{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}mI.className="RandomSeed";class gI extends sx{constructor(e){super(e),this.randomGenerator=new mI(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}gI.className="BaseRandomLayer";const yI=new Set(["bilinear","nearest"]);class bI extends gI{constructor(e){super(e);const{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&2===this.factor.length)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new hy(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new hy(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new hy(`factor cannot have upper bound less than lower bound.\\n        Got upper bound: ${this.widthUpper}.\\n        Got lower bound: ${this.widthLower}\\n      `);if(n){if(!yI.has(n))throw new hy(`Invalid interpolation parameter: ${n} is not implemented`);this.interpolation=n}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=qb(e))[2];return[this.imgHeight,-1,t]}call(e,t){return ui(()=>{const t=jb(e);this.imgHeight=t.shape[t.shape.length-3];const n=t.shape[t.shape.length-2];this.widthFactor=Id([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*n;r=Math.round(r);const s=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return Df.resizeBilinear(e,s);case"nearest":return Df.resizeNearestNeighbor(e,s);default:throw new Error(`Interpolation is ${this.interpolation}\\n          but only ${[...yI]} are supported`)}})}}function xI(e){return new ix(e)}function wI(e){return new Fv(e)}function vI(e){return new Rv(e)}function kI(e){return new _v(e)}function II(e){return new Mv(e)}function SI(e){return new Ov(e)}function NI(e){return new Dv(e)}function TI(e){return new Jv(e)}function EI(e){return new Hv(e)}function CI(e){return new qv(e)}function $I(e){return new jv(e)}function AI(e){return new Kv(e)}function RI(e){return new Yv(e)}function _I(e){return new Zv(e)}function MI(e){return new Qv(e)}function FI(e){return new ek(e)}function DI(e){return new wk(e)}function OI(e){return new bk(e)}function LI(e){return new gk(e)}function zI(e){return new yk(e)}function PI(e){return new xk(e)}function BI(e){return new vk(e)}function VI(e){return new kk(e)}function UI(e){return new Ik(e)}function WI(e){return new Nk(e)}function GI(e){return new Ek(e)}function HI(e){return new $k(e)}function jI(e){return new _k(e)}function qI(e){return new Ak(e)}function KI(e){return new Rk(e)}function XI(e){return new Ck(e)}function YI(e){return new Fk(e)}function JI(e){return new Pk(e)}function ZI(e){return new Bk(e)}function QI(e){return new Vk(e)}function eS(e){return new jk(e)}function tS(e){return eS(e)}function nS(e){return eS(e)}function rS(e){return new Xk(e)}function sS(e){return rS(e)}function aS(e){return rS(e)}function iS(e){return new Zk(e)}function oS(e){return iS(e)}function uS(e){return iS(e)}function lS(e){return new eI(e)}function cS(e){return new rI(e)}function hS(e){return new tI(e)}function dS(e){return new sI(e)}function pS(e){return new Hk(e)}function fS(e){return new Kk(e)}function mS(e){return new Jk(e)}function gS(e){return new uk(e)}function yS(e){return new ok(e)}function bS(e){return new ck(e)}function xS(e){return new lk(e)}function wS(e){return new ik(e)}function vS(e){return new ak(e)}function kS(e){return new mk(e)}function IS(e){return new fk(e)}function SS(e){return new rk(e)}function NS(e){return new hk(e)}function TS(e){return new oI(e)}function ES(e){return new iI(e)}
5057bI.className="RandomWidth",Ho(bI);const CS=hS,$S=dS,AS=pS,RS=fS;function _S(e){return new Dk(e)}function MS(e){return new Ok(e)}function FS(e){return new Lk(e)}function DS(e){return new Sk(e)}function OS(e){return new uI(e)}function LS(e){return new hI(e)}function zS(e){return new fI(e)}function PS(e){return new dI(e)}function BS(e){return new bI(e)}function VS(e,t){return dw(e,t)}function US(e,t){return gw(e,t)}function WS(e,t){return yw(e,t)}function GS(e,t){return pw(e,t)}function HS(e,t){return bw(e,t)}function jS(e,t){return mw(e,t)}function qS(e,t){return function(e,t){return ui(()=>{const n=fw(e,t),r=function(e,t){return ui(()=>Io(oh(Fh(Wc(e,1),Wc(t,0))),"float32"))}(e,t),s=To(n,r);return Io(Gc(bh(s,0),Co(n,s),0),"float32")})}(e,t)}function KS(e,t){return lw(e,t)}function XS(e,t){return sw(e,t)}function YS(e,t){return aw(e,t)}function JS(e,t){return aw(e,t)}function ZS(e,t){return aw(e,t)}function QS(e,t){return rw(e,t)}function eN(e,t){return rw(e,t)}function tN(e,t){return rw(e,t)}function nN(e,t){return function(e,t){return ui(()=>{const n=e.sub(t).square().sum(),r=e.sub(e.mean()).square().sum();return Bo(1).sub(n.div(r))})}(e,t)}function rN(e){return new Tv(e)}function sN(e){return Sv(t=e),new Tv({l1:null!=t?t.l1:null,l2:0});var t}function aN(e){return Sv(t=e),new Tv({l2:null!=t?t.l2:null,l1:0});var t}class iN extends qx{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Xw))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function oN(e,t){return e<t}function uN(e,t){return e>t}class lN extends iN{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new dy("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,-1===["auto","min","max"].indexOf(this.mode)&&(console.warn(`EarlyStopping mode \'${this.mode}\' is invalid. Falling back to mode \'auto\'.`),this.mode="auto"),"min"===this.mode?this.monitorFunc=oN:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=uN:this.monitorFunc=oN,this.monitorFunc===oN&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===oN?1/0:-1/0}async onEpochEnd(e,t){await Gx(t);const n=this.getMonitorValue(t);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){null==e&&(e={});const t=e[this.monitor];return null==t&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const cN={earlyStopping:function(e){return new lN(e)}};var hN,dN;Xe().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&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.")}),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(hN||(hN={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}
vendor: 4,211 bytes, line 5057
5057(dN||(dN={}));const pN={};function fN(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};pN[e]=n}function mN(e){return pN[e]}function gN(e){delete pN[e]}function yN(e,t,n,r,s){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===a.type)return bN(t.inputNames[o],n,r,s);if("tensors"===a.type){const a=t.inputs.slice(e,i);return t.inputNames.slice(e,i).filter((e,t)=>{var n;return"NoOp"!==(null===(n=a[t])||void 0===n?void 0:n.op)}).map(e=>bN(e,n,r,s))}const u=bN(t.inputNames[o],n,r,s),l=u.dataSync();return"number"===a.type?l[0]:Le(u.shape,l)}const i=t.attrParams[e];return i&&i.value}function bN(e,t,n,r){const[s,a]=kN(e,n);if(null!=r){const e=r.getHashTableHandleByName(s);if(null!=e)return e}const i=n.currentContextIds.find(e=>!!t[vN(s,e)]);return void 0!==i?t[vN(s,i)][a]:void 0}function xN(e,t,n){return t[vN(e,n.currentContextId)]}function wN(e,t){const[n,r,s]=kN(e,t);return[vN(n,t&&t.currentContextId),r,s]}function vN(e,t){return t?`${e}-${t}`:e}function kN(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let s;if(1===r.length)s=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;s=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,s),s}function IN(e,t,n){let r=yN("pad",e,t,n);if("explicit"===r){r=yN("explicitPaddings",e,t,n);const s=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)s[e][0]=r[2*e],s[e][1]=r[2*e+1];return s}return r}function SN(e){return e.kept?e:So(e)}const NN=[{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}
5057]},{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}]}],TN=[{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}
5057]},{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}]}],EN
vendor: 7,589 bytes, line 5057
5057=[{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"}]}]
5057,CN=[{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}
5057,{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"}]}],$N=[{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}
5057]},{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"}]}],AN=[{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}
5057]},{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}]}],RN=[{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"}]}],_N=[{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"}]}],MN=[{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"}
5057],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"}]}],FN=[{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"}]}],DN=[{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"}]}],ON=[{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}
5057,{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"}]}],LN=[{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"}]}],zN=[{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}
5057]},{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"}]}],PN=[{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"}]}],BN=[{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"}]}
5057,{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"}]}],VN=[{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}]}],UN=[{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"}]}],WN=[{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:[]}];class GN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[N,T,E,C,$,A,R,_,M,F,D,O,L,z,P,B,V,U,W].map(e=>e.json));this.opMappers=e.reduce((e,t)=>
5057(e[t.tfOpName]=t,e),{})}transformGraph(e,t={}){const n=e.node,r=[],s=[],a=[],i=n.reduce((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?s.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e),{});let o=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach(e=>{const t=i[e];t.inputNames.forEach((e,n)=>{const[r,,s]=wN(e),a=i[r];if(null!=a.outputs){const e=a.outputs.indexOf(s);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(a),a.children.push(t)})}),0===Object.keys(c).length?h.forEach(e=>{const t=i[e];0===t.children.length&&u.push(t)}):Object.keys(c).forEach(e=>{const[t]=wN(e),n=i[t];null!=n&&(n.signatureKey=c[e],u.push(n))}),Object.keys(l).length>0?Object.keys(l).forEach(e=>{const[t]=wN(e),n=i[t];n&&(n.signatureKey=l[e],o.push(n))}):o=r;let d={};null!=e.library&&null!=e.library.function&&(d=e.library.function.reduce((e,t)=>(e[t.signature.name]=this.mapFunction(t),e),{}));const p={nodes:i,inputs:o,outputs:u,weights:s,placeholders:r,signature:t,functions:d};return a.length>0&&(p.initNodes=a),p}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=mN(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(e=>e.startsWith("^")?e.slice(1):e),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce((t,n)=>{const r=n.type;let s;switch(n.type){case"string":s=jN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=jN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":s=nT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=nT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":s=KN(e.attr,n.tfName,n.defaultValue||0),void 0===s&&n.tfDeprecatedName&&(s=KN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":s=tT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=tT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":s=qN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=qN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":s=sT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=sT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":s=eT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=eT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":s=rT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=rT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":s=JN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=JN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":s=ZN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=ZN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":s=YN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=YN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:s,type:r},t},{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e),{}));const s=[],a=[];e.signature.inputArg.forEach(e=>{const[t]=wN(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:XN(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,s.push(n),r[t]=n}),Object.keys(r).forEach(e=>{const t=r[e];t.inputNames.forEach((e,n)=>{const[s,,a]=wN(e),i=r[s];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(i),i.children.push(t)})});const i=e.ret;
5057e.signature.outputArg.forEach(e=>{const[t,n]=wN(i[e.name]),s=r[t];null!=s&&(s.defaultOutput=n,a.push(s))});const o=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:a,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function HN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Xe().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function jN(e,t,n,r=!1){const s=e[t];return null!=s?HN(s.s,r):n}function qN(e,t,n){const r=e[t];return r?r.b:n}function KN(e,t,n){const r=e[t]||{},s=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof s?s:parseInt(s,10)}function XN(e){switch("string"==typeof e&&(e=hN[e]),e){case hN.DT_FLOAT:case hN.DT_HALF:return"float32";case hN.DT_INT32:case hN.DT_INT64:case hN.DT_INT8:case hN.DT_UINT8:return"int32";case hN.DT_BOOL:return"bool";case hN.DT_DOUBLE:return"float32";case hN.DT_STRING:return"string";case hN.DT_COMPLEX64:case hN.DT_COMPLEX128:return"complex64";default:return null}}function YN(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function JN(e,t,n){const r=e[t];return r&&r.type?XN(r.type):n}function ZN(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map(e=>XN(e)):n}function QN(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(e=>"number"==typeof e.size?e.size:parseInt(e.size,10)):[]}function eT(e,t,n){const r=e[t];return r&&r.shape?QN(r.shape):n}function tT(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(e=>"number"==typeof e?e:parseInt(e,10)):n}function nT(e,t,n,r=!1){const s=e[t];return s&&s.list&&s.list.s?s.list.s.map(e=>HN(e,r)):n}function rT(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(e=>QN(e)):n}function sT(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class aT{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(e=>this.getInput(e)),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce((e,t)=>(e[t]=this.getAttr(t),e),{}))}getInput(e){return bN(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return bN(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return KN(this.node.rawAttrs,e,t);if(null!=n.s)return jN(this.node.rawAttrs,e,t);if(null!=n.b)return qN(this.node.rawAttrs,e,t);if(null!=n.shape)return eT(this.node.rawAttrs,e,t);if(null!=n.type)return JN(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return tT(this.node.rawAttrs,e,t);if(null!=n.list.s)return nT(this.node.rawAttrs,e,t);if(null!=n.list.shape)return rT(this.node.rawAttrs,e,t);if(null!=n.list.b)return sT(this.node.rawAttrs,e,t);if(null!=n.list.type)return ZN(this.node.rawAttrs,e,t)}return t}}function iT(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){ie(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;r<e.length;r++){const s=e[r],a=t[r];ie(s<0||a<0||s===a,()=>n+` Shapes ${e} and ${t} must match`)}}}function oT(e){return"number"!=typeof e&&!e.some(e=>e<0)}function uT(e,t,n){let r=lT(e,n);const s=!oT(r);if(s&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach(e=>{r=lT(e.shape,r)}),!oT(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function lT(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r<e.length;++r){const s=e[r],a=t[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}class cT{constructor(e,t,n,r,s,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_
5057=!1,this.idTensor=Bo(0),ci(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&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(e=>this.read(e))}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 n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\\n          because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),iT(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,ci(t),n.written=!0,this.tensors[e]=n}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((e,n)=>this.write(e,t[n]))}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 t=0;t<this.size();t++)e.push(t)}if(0===e.length)return Ja([],[0].concat(this.elementShape));const n=this.readMany(e);return iT(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ep(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return Ja([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return iT(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),oc(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n}  vs. ${this.maxSize})`);this.writeMany(e,fp(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 n=0;const r=e.map(e=>(n+=e,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\\n          tensor.shape[0], but sum of lengths is\\n        ${n}, 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 s=0===n?0:t.size/n,a=[];ui(()=>{t=sc(t,[1,n,s]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:r[n-1],0],o=[1,e[n],s];a[n]=sc(lc(t,i,o),this.elementShape)}return a});const i=[];for(let t=0;t<e.length;t++)i[t]=t;this.writeMany(i,a)}}class hT{get id(){return this.idTensor.id}constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach(e
5057=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);iT(t,e.shape,"TensorList shape mismatch: "),ci(e)}),this.idTensor=Bo(0),this.maxNumElements=r,ci(this.idTensor)}copy(){return new hT([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.id)||t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);iT(e,this.elementShape,"TensorList shape mismatch: ");const r=uT(this.elementShape,this.tensors,e);return ui(()=>{const e=this.tensors.map(e=>sc(e,r));return ep(e,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=uT(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,iT(r.shape,e,"TensorList shape mismatch: "),sc(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(iT(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");ci(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new hT([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);iT(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=uT(this.elementShape,this.tensors,t);return sc(this.tensors[e],r)}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||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);iT(this.elementShape,t.shape,"TensorList shape mismatch: "),ci(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);iT(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=uT(this.elementShape,this.tensors,n);return 0===e.length?Ja([],[0].concat(r)):ui(()=>{const t=e.map(e=>sc(this.tensors[e],r));return ep(t,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);iT(this.elementShape,t,"TensorList shape mismatch: ");const n=uT(this.elementShape,this.tensors,t);return 0===this.size()?Ja([],[0].concat(n)):ui(()=>{const e=this.tensors.map(e=>sc(e,n));return oc(e,0)})}}function dT(e,t,n){const[r,s]=yN("fusedOps",e,t,n),a="biasadd"===r,i=!a,o="prelu"===s,u="fusedbatchnorm"===r,l=yN("numArgs",e,t,n);if(a){if(o&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=yN("strides",e,t,n),h=IN(e,t,n),d=yN("dataFormat",e,t,n).toUpperCase(),p=yN("dilations",e,t,n);let[f,m]=yN("args",e,t,n);return i&&(m=f,f=void 0),{stride:c,pad:h,dataFormat:d,dilations:p,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:yN("leakyreluAlpha",e,t,n)}}function pT(e,t,n){return{boxes:yN("boxes",e,t,n),scores:yN("scores",e,t,n),maxOutputSize:yN("maxOutputSize",e,t,n),iouThreshold:yN("iouThreshold",e,t,n),scoreThreshold:yN("scoreThreshold",e,t,n),softNmsSigma:yN("softNmsSigma",e,t,n)}}class fT{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Bo(0),this.tensorMap=new Map,ci(this.handle)}
5057clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Bo(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),ui(()=>{const e=fp(t),r=n.length,s=e.length;ie(r===s,()=>`The number of elements doesn\'t match, keys has ${r} elements, the values has ${s} elements.`);for(let t=0;t<r;t++){const r=n[t],s=e[t];ci(s),this.tensorMap.set(r,s)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return ui(()=>{const e=[];for(let r=0;r<n.length;r++){const s=n[r],a=this.findWithDefault(s,t);e.push(a)}return ep(e)})}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function mT(e,t,n,r,s=ui){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(yN("a",e,t,n),yN("b",e,t,n))];case"AddN":return[r.addN(yN("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(yN("a",e,t,n),yN("b",e,t,n))];case"Mul":return[r.mul(yN("a",e,t,n),yN("b",e,t,n))];case"RealDiv":case"Div":return[r.div(yN("a",e,t,n),yN("b",e,t,n))];case"DivNoNan":return[r.divNoNan(yN("a",e,t,n),yN("b",e,t,n))];case"FloorDiv":return[r.floorDiv(yN("a",e,t,n),yN("b",e,t,n))];case"Sub":return[r.sub(yN("a",e,t,n),yN("b",e,t,n))];case"Minimum":return[r.minimum(yN("a",e,t,n),yN("b",e,t,n))];case"Maximum":return[r.maximum(yN("a",e,t,n),yN("b",e,t,n))];case"Pow":return[r.pow(yN("a",e,t,n),yN("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(yN("a",e,t,n),yN("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"basic_math":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(yN("x",e,t,n))];case"Acos":return[r.acos(yN("x",e,t,n))];case"Acosh":return[r.acosh(yN("x",e,t,n))];case"Asin":return[r.asin(yN("x",e,t,n))];case"Asinh":return[r.asinh(yN("x",e,t,n))];case"Atan":return[r.atan(yN("x",e,t,n))];case"Atan2":return[r.atan2(yN("x",e,t,n),yN("y",e,t,n))];case"Atanh":return[r.atanh(yN("x",e,t,n))];case"Ceil":return[r.ceil(yN("x",e,t,n))];case"Complex":return[r.complex(yN("real",e,t,n),yN("imag",e,t,n))];case"Cos":return[r.cos(yN("x",e,t,n))];case"Cosh":return[r.cosh(yN("x",e,t,n))];case"Elu":return[r.elu(yN("x",e,t,n))];case"Erf":return[r.erf(yN("x",e,t,n))];case"Exp":return[r.exp(yN("x",e,t,n))];case"Expm1":return[r.expm1(yN("x",e,t,n))];case"Floor":return[r.floor(yN("x",e,t,n))];case"Log":return[r.log(yN("x",e,t,n))];case"Log1p":return[r.log1p(yN("x",e,t,n))];case"Imag":return[r.imag(yN("x",e,t,n))];case"Neg":return[r.neg(yN("x",e,t,n))];case"Reciprocal":return[r.reciprocal(yN("x",e,t,n))];case"Real":return[r.real(yN("x",e,t,n))];case"Relu":return[r.relu(yN("x",e,t,n))];case"Round":return[r.round(yN("x",e,t,n))];case"Selu":return[r.selu(yN("x",e,t,n))];case"Sigmoid":return[r.sigmoid(yN("x",e,t,n))];case"Sin":return[r.sin(yN("x",e,t,n))];case"Sign":return[r.sign(yN("x",e,t,n))];case"Sinh":return[r.sinh(yN("x",e,t,n))];case"Softplus":return[r.softplus(yN("x",e,t,n))];case"Sqrt":return[r.sqrt(yN("x",e,t,n))];case"Square":return[r.square(yN("x",e,t,n))];case"Tanh":return[r.tanh(yN("x",e,t,n))];case"Tan":return[r.tan(yN("x",e,t,n))];case"ClipByValue":return[r.clipByValue(yN("x",e,t,n),yN("clipValueMin",e,t,n),yN("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(yN("x",e,t,n))];case"Rsqrt":return[r.rsqrt(bN(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(yN("x",e,t,n),yN("alpha",e,t,n))];case"Prelu":return[r.prelu(yN("x",e,t,n),yN("alpha",e,t,n))];case"IsNan":return[r.isNaN(bN(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(bN(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(bN(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=yN("thenBranch",e,t,n),s=yN("elseBranch",e,t,n),a=yN("cond",e,t,n),i=yN("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=yN("body",e,t,n),s=yN("cond",e,t,n),a=yN("args",e,t,n),i=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map(e=>e.id);let u=await i[0].data();
vendor: 7,360 bytes, line 5057
5057i.forEach(e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()});let l=a;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map(e=>e.id);e.forEach(e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()});const a=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await a[0].data(),a.forEach(e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()})}return l}case"LoopCond":return[SN(yN("pred",e,t,n))];case"Switch":{const r=yN("pred",e,t,n);let s=yN("data",e,t,n);return s.kept||(s=SN(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const r=e.inputNames.find(e=>void 0!==bN(e,t,n));return r?[SN(bN(r,t,n))]:void 0}case"Enter":{const r=yN("frameName",e,t,n),s=yN("tensor",e,t,n);return n.enterFrame(r),[SN(s)]}case"Exit":{const r=yN("tensor",e,t,n);return n.exitFrame(),[SN(r)]}case"NextIteration":{const r=yN("tensor",e,t,n);return n.nextIteration(),[SN(r)]}case"TensorArrayV3":{const r=yN("size",e,t,n),s=yN("dtype",e,t,n),a=yN("elementShape",e,t,n),i=yN("dynamicSize",e,t,n),o=yN("clearAfterRead",e,t,n),u=yN("identicalElementShapes",e,t,n),l=yN("name",e,t,n),c=new cT(l,s,r,a,u,i,o);return n.addTensorArray(c),[c.idTensor,Bo(1)]}case"TensorArrayWriteV3":{const r=yN("tensorArrayId",e,t,n),s=yN("index",e,t,n),a=yN("tensor",e,t,n),i=n.getTensorArray(r.id);return i.write(s,a),[i.idTensor]}case"TensorArrayReadV3":{const r=yN("tensorArrayId",e,t,n),s=yN("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{const r=yN("tensorArrayId",e,t,n),s=yN("indices",e,t,n),a=yN("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{const r=yN("tensorArrayId",e,t,n),s=yN("indices",e,t,n),a=yN("tensor",e,t,n),i=n.getTensorArray(r.id);return i.scatter(s,a),[i.idTensor]}case"TensorArrayConcatV3":{const r=yN("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=yN("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{const r=yN("tensorArrayId",e,t,n),s=yN("tensor",e,t,n),a=yN("lengths",e,t,n),i=n.getTensorArray(r.id);return i.split(a,s),[i.idTensor]}case"TensorArraySizeV3":{const r=yN("tensorArrayId",e,t,n);return[Bo(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=yN("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const r=yN("tensorListId",e,t,n),s=yN("index",e,t,n),a=yN("tensor",e,t,n),i=n.getTensorList(r.id);return i.setItem(s,a),[i.idTensor]}case"TensorListGetItem":{const r=yN("tensorListId",e,t,n),s=yN("index",e,t,n),a=yN("elementShape",e,t,n),i=yN("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const r=yN("indices",e,t,n),s=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const s=Math.max(...t);if(null!=r&&-1!==r&&s>=r)throw new Error(`Max index must be < array size (${s}  vs. ${r})`);const a=new hT([],n,e.dtype,r),i=fp(e,0);return t.forEach((e,t)=>{a.setItem(e,i[t])}),a}(yN("tensor",e,t,n),r,yN("elementShape",e,t,n),yN("numElements",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=yN("elementShape",e,t,n),s=yN("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=yN(a,e,t,n),o=function(e,t,n,r){return new hT([],e,t,r)}(r,s,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const r=yN("tensorListId",e,t,n),s=yN("indices",e,t,n),a=yN("elementShape",e,t,n),i=yN("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,i,a)]}case"TensorListStack":{const r=yN("tensorListId",e,t,n),s=yN("elementShape",e,t,n),a=yN("elementDType",e,t,n),i=yN("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,i)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);iT(e.shape.slice(1),t,"TensorList shape mismatch: ");const s=fp(e);return new hT(s,t,r)}(yN("tensor",e,t,n),yN("elementShape",e,t,n),yN("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=yN("tensorListId",e,t,n),s=n.getTensorList(r.id),a=yN("dtype",e,t,n),i=yN("elementShape",e,t,n);return[s.concat(a,i)]}case"TensorListPushBack":{const r=yN("tensorListId",e,t,n),s=yN("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const r=yN("tensorListId",e,t,n),s=yN("elementShape",e,t,n),a=yN("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{const r=yN("tensor",e,t,n),s=yN("elementShape",e,t,n),a=function(e,t,n){let r=0;const s=t.map(e=>(r+=e,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\\n          tensor.shape[0], but sum of lengths is\\n        ${r}, and tensor\'s shape is: ${e.shape}`);const a=lT(e.shape.slice(1),n),i=0===r?0:e.size/r,o=ui(()=>{const n=[];e=sc(e,[1,r,i]);for(let r=0;r<t.length;++r){const o=[0,0===r?0:s[r-1],0],u=[1,t[r],i];n[r]=sc(lc(e,o,u),a)}return e.dispose(),n}),u=new hT([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)u.setItem(e,o[e]);return u}(r,yN("lengths",e,t,n),s);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const r=yN("tensorListId",e,t,n);return[Bo(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=yN("tensorListId",e,t,n),s=yN("size",e,t,n),a=n.getTensorList(r.id).resize(s);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"convolution":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Conv1D":{const s=yN("stride",e,t,n),a=yN("pad",e,t,n),i=yN("dataFormat",e,t,n).toUpperCase(),o=yN("dilation",e,t,n);return[r.conv1d(yN("x",e,t,n),yN("filter",e,t,n),s,a,i,o)]}case"Conv2D":{const s=yN("strides",e,t,n),a=IN(e,t,n),i=yN("dataFormat",e,t,n).toUpperCase(),o=yN("dilations",e,t,n);return[r.conv2d(yN("x",e,t,n),yN("filter",e,t,n),[s[1],s[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=dT(e,t,n);return[r.fused.conv2d({x:yN("x",e,t,n),filter:yN("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=dT(e,t,n);return[r.fused.depthwiseConv2d({x:yN("x",e,t,n),filter:yN("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=yN("outputShape",e,t,n),a=yN("strides",e,t,n),i=IN(e,t,n);return[r.conv2dTranspose(yN("x",e,t,n),yN("filter",e,t,n),s,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=yN("strides",e,t,n),a=IN(e,t,n),i=yN("dilations",e,t,n),o=yN("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(yN("input",e,t,n),yN("filter",e,t,n),[s[1],s[2]],a,o,[i[
vendor: 20,044 bytes, line 5057
50571],i[2]])]}case"Conv3D":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("dataFormat",e,t,n).toUpperCase(),o=yN("dilations",e,t,n);return[r.conv3d(yN("x",e,t,n),yN("filter",e,t,n),[s[1],s[2],s[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("kernelSize",e,t,n);return[r.avgPool(yN("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("kernelSize",e,t,n);return[r.maxPool(yN("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("kernelSize",e,t,n),o=yN("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(yN("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a,o);return[u,l]}case"AvgPool3D":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("kernelSize",e,t,n);return[r.avgPool3d(yN("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("kernelSize",e,t,n);return[r.maxPool3d(yN("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=yN("strides",e,t,n),a=yN("pad",e,t,n),i=yN("dilations",e,t,n),o=s[1],u=s[2],l=i[1],c=i[2];return[r.dilation2d(yN("x",e,t,n),yN("filter",e,t,n),[o,u],a,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"creation":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Fill":{const s=yN("shape",e,t,n),a=yN("dtype",e,t,n),i=yN("value",e,t,n);return[r.fill(s,i,a)]}case"LinSpace":{const s=yN("start",e,t,n),a=yN("stop",e,t,n),i=yN("num",e,t,n);return[r.linspace(s,a,i)]}case"Multinomial":{const s=yN("logits",e,t,n),a=yN("numSamples",e,t,n),i=yN("seed",e,t,n);return[r.multinomial(s,a,i)]}case"OneHot":{const s=yN("indices",e,t,n),a=yN("depth",e,t,n),i=yN("onValue",e,t,n),o=yN("offValue",e,t,n),u=yN("dtype",e,t,n);return[r.oneHot(s,a,i,o,u)]}case"Ones":return[r.ones(yN("shape",e,t,n),yN("dtype",e,t,n))];case"OnesLike":return[r.onesLike(yN("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(yN("shape",e,t,n),yN("dtype",e,t,n),yN("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(yN("shape",e,t,n),yN("minval",e,t,n),yN("maxval",e,t,n),yN("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(yN("shape",e,t,n),yN("minval",e,t,n),yN("maxval",e,t,n),yN("seed",e,t,n))];case"Range":{const s=yN("start",e,t,n),a=yN("stop",e,t,n),i=yN("step",e,t,n);return[r.range(s,a,i,yN("dtype",e,t,n))]}case"TruncatedNormal":{const s=yN("shape",e,t,n),a=yN("mean",e,t,n),i=yN("stdDev",e,t,n),o=yN("seed",e,t,n);return[r.truncatedNormal(s,a,i,yN("dtype",e,t,n),o)]}case"Zeros":return[r.zeros(yN("shape",e,t,n),yN("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(yN("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"dynamic":return(async(e,t,n,r,s=G)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=pT(e,t,n),c=await s.image.nonMaxSuppressionWithScoreAsync(r,a,i,o,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=pT(e,t,n),l=yN("padToMaxOutputSize",e,t,n),c=await s.image.nonMaxSuppressionPaddedAsync(r,a,i,o,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=pT(e,t,n);return[await s.image.nonMaxSuppressionAsync(r,a,i,o,u)]}case"Where":{const r=s.cast(yN("condition",e,t,n),"bool"),a=[await s.whereAsync(r)];return r.dispose(),a}case"ListDiff":return s.setdiff1dAsync(yN("x",e,t,n),yN("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"LowerBound":{const s=yN("sortedSequence",e,t,n),a=yN("values",e,t,n);return[r.lowerBound(s,a)]}case"TopKV2":{const s=yN("x",e,t,n),a=yN("k",e,t,n),i=yN("sorted",e,t,n),o=r.topk(s,a,i);return[o.values,o.indices]}case"UpperBound":{const s=yN("sortedSequence",e,t,n),a=yN("values",e,t,n);return[r.upperBound(s,a)]}case"Unique":{const s=yN("x",e,t,n),a=r.unique(s);return[a.values,a.indices]}case"UniqueV2":{const s=yN("x",e,t,n),a=yN("axis",e,t,n),i=r.unique(s,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"image":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"ResizeBilinear":{const s=yN("images",e,t,n),a=yN("size",e,t,n),i=yN("alignCorners",e,t,n),o=yN("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(s,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const s=yN("images",e,t,n),a=yN("size",e,t,n),i=yN("alignCorners",e,t,n),o=yN("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(s,[a[0],a[1]],i,o)]}case"CropAndResize":{const s=yN("image",e,t,n),a=yN("boxes",e,t,n),i=yN("boxInd",e,t,n),o=yN("cropSize",e,t,n),u=yN("method",e,t,n),l=yN("extrapolationValue",e,t,n);return[r.image.cropAndResize(s,a,i,o,u,l)]}case"ImageProjectiveTransformV3":{const s=yN("images",e,t,n),a=yN("transforms",e,t,n),i=yN("outputShape",e,t,n),o=yN("fillValue",e,t,n),u=yN("interpolation",e,t,n),l=yN("fillMode",e,t,n);return[r.image.transform(s,a,u.toLowerCase(),l.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"graph":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=yN("default",e,t,n);return[bN(e.name,t,n)||s];case"Placeholder":return[bN(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[SN(yN("x",e,t,n))];case"IdentityN":return yN("x",e,t,n).map(e=>SN(e));case"Shape":return[r.tensor1d(yN("x",e,t,n).shape,"int32")];case"ShapeN":return yN("x",e,t,n).map(e=>r.tensor1d(e.shape));case"Size":return[r.scalar(yN("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(yN("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const a=yN("x",e,t,n),i=yN("data",e,t,n),o=yN("message",e,t,n),u=yN("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let e=0;e<i.length;e++)console.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,u));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"logical":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Equal":return[r.equal(yN("a",e,t,n),yN("b",e,t,n))];case"NotEqual":return[r.notEqual(yN("a",e,t,n),yN("b",e,t,n))];case"Greater":return[r.greater(yN("a",e,t,n),yN("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(yN("a",e,t,n),yN("b",e,t,n))];case"Less":return[r.less(yN("a",e,t,n),yN("b",e,t,n))];case"LessEqual":return[r.lessEqual(yN("a",e,t,n),yN("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(yN("a",e,t,n),yN("b",e,t,n))];case"LogicalNot":return[r.logicalNot(yN("a",e,t,n))];case"LogicalOr":return[r.logicalOr(yN("a",e,t,n),yN("b",e,t,n))];case"Select":case"SelectV2":return[r.where(yN("condition",e,t,n),yN("a",e,t,n),yN("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(yN("a",e,t,n),yN("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"matrices":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(yN("a",e,t,n),yN("b",e,t,n),yN("transposeA",e,t,n),yN("transposeB",e,t,n))];case"Einsum":return[r.einsum(yN("equation",e,t,n),...yN("tensors",e,t,n))];case"Transpose":return[r.transpose(yN("x",e,t,n),yN("perm",e,t,n))];case"_FusedMatMul":const[s,a]=yN("fusedOps",e,t,n),i="biasadd"===s,o="prelu"===a,u=yN("numArgs",e,t,n),l=yN("leakyreluAlpha",e,t,n);if(i){if(o&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=yN("args",e,t,n);return[r.fused.matMul({a:yN("a",e,t,n),b:yN("b",e,t,n),transposeA:yN("transposeA",e,t,n),transposeB:yN("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(yN("a",e,t,n),yN("numLower",e,t,n),yN("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"normalization":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(yN("x",e,t,n),yN("axis",e,t,n),yN("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(yN("x",e,t,n),yN("mean",e,t,n),yN("variance",e,t,n),yN("offset",e,t,n),yN("scale",e,t,n),yN("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(yN("x",e,t,n),yN("radius",e,t,n),yN("bias",e,t,n),yN("alpha",e,t,n),yN("beta",e,t,n))];case"Softmax":return[r.softmax(yN("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(yN("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"ragged":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:s,outputDenseValues:a}=r.raggedGather(yN("paramsNestedSplits",e,t,n),yN("paramsDenseValues",e,t,n),yN("indices",e,t,n),yN("outputRaggedRank",e,t,n));return s.concat(a)}case"RaggedRange":{const{rtNestedSplits:s,rtDenseValues:a}=r.raggedRange(yN("starts",e,t,n),yN("limits",e,t,n),yN("splits",e,t,n));return[s,a]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(yN("shape",e,t,n),yN("values",e,t,n),yN("defaultValue",e,t,n),yN("rowPartitionTensors",e,t,n),yN("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"reduction":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Max":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.max(yN("x",e,t,n),s,a)]}case"Mean":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.mean(yN("x",e,t,n),s,a)]}case"Min":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.min(yN("x",e,t,n),s,a)]}case"Sum":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.sum(yN("x",e,t,n),s,a)]}case"All":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.all(yN("x",e,t,n),s,a)]}case"Any":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.any(yN("x",e,t,n),s,a)]}case"ArgMax":{const s=yN("axis",e,t,n);return[r.argMax(yN("x",e,t,n),s)]}case"ArgMin":{const s=yN("axis",e,t,n);return[r.argMin(yN("x",e,t,n),s)]}case"Prod":{const s=yN("axis",e,t,n),a=yN("keepDims",e,t,n);return[r.prod(yN("x",e,t,n),s,a)]}case"Cumprod":{const s=yN("axis",e,t,n),a=yN("exclusive",e,t,n),i=yN("reverse",e,t,n);return[r.cumprod(yN("x",e,t,n),s,a,i)]}case"Cumsum":{const s=yN("axis",e,t,n),a=yN("exclusive",e,t,n),i=yN("reverse",e,t,n);return[r.cumsum(yN("x",e,t,n),s,a,i)]}case"Bincount":const s=yN("x",e,t,n),a=yN("weights",e,t,n),i=yN("size",e,t,n);return[r.bincount(s,a,i)];case"DenseBincount":{const s=yN("x",e,t,n),a=yN("weights",e,t,n),i=yN("size",e,t,n),o=yN("binaryOutput",e,t,n);return[r.denseBincount(s,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"slice_join":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=yN("n",e,t,n),a=yN("axis",e,t,n);let i=yN("tensors",e,t,n);return i=i.slice(0,s),[r.concat(i,a)]}case"Gather":{const s=yN("x",e,t,n),a=yN("indices",e,t,n);return[r.gather(s,r.cast(a,"int32"),0)]}case"GatherV2":{const s=yN("axis",e,t,n),a=yN("batchDims",e,t,n),i=yN("x",e,t,n),o=yN("indices",e,t,n);return[r.gather(i,r.cast(o,"int32"),s,a)]}case"Reverse":{const s=yN("dims",e,t,n),a=[];for(let e=0;e<s.length;e++)s[e]&&a.push(e);const i=yN("x",e,t,n);return[r.reverse(i,a)]}case"ReverseV2":{const s=yN("axis",e,t,n),a=yN("x",e,t,n);return[r.reverse(a,s)]}case"Slice":{const s=yN("begin",e,t,n),a=yN("size",e,t,n);return[r.slice(yN("x",e,t,n),s,a)]}case"StridedSlice":{const s=yN("begin",e,t,n),a=yN("end",e,t,n),i=yN("strides",e,t,n),o=yN("beginMask",e,t,n),u=yN("endMask",e,t,n),l=yN("ellipsisMask",e,t,n),c=yN("newAxisMask",e,t,n),h=yN("shrinkAxisMask",e,t,n),d=yN("x",e,t,n);return[r.stridedSlice(d,s,a,i,o,u,l,c,h)]}case"Pack":return ui(()=>{const s=yN("axis",e,t,n),a=yN("tensors",e,t,n),i=a[0].shape,o=r.squeeze(a[0]).shape,u=a.map(e=>{const t=de(e.shape,i);if(!t&&!de(r.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,i)});return[r.stack(u,s)]});case"Unpack":{const s=yN("axis",e,t,n),a=yN("tensor",e,t,n);return r.unstack(a,s)}case"Tile":{const s=yN("reps",e,t,n);return[r.tile(yN("x",e,t,n),s)]}case"Split":case"SplitV":{const s=yN("axis",e,t,n),a=yN("numOrSizeSplits",e,t,n),i=yN("x",e,t,n);return r.split(i,a,s)}case"ScatterNd":{const s=yN("indices",e,t,n),a=yN("values",e,t,n),i=yN("shape",e,t,n);return[r.scatterND(s,a,i)]}case"GatherNd":{const s=yN("x",e,t,n),a=yN("indices",e,t,n);return[r.gatherND(s,a)]}case"SparseToDense":{const s=yN("sparseIndices",e,t,n),a=yN("outputShape",e,t,n),i=yN("sparseValues",e,t,n),o=yN("defaultValue",e,t,n);return[r.sparseToDense(s,i,a,i.dtype===o.dtype?o:r.cast(o,i.dtype))]}case"TensorScatterUpdate":{const s=yN("indices",e,t,n),a=yN("values",e,t,n),i=yN("tensor",e,t,n);return[r.tensorScatterUpdate(i,s,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"sparse":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:s,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=r.sparse.sparseFillEmptyRows(yN("indices",e,t,n),yN("values",e,t,n),yN("denseShape",e,t,n),yN("defaultValue",e,t,n));return[s,a,i,o]}case"SparseReshape":{const{outputIndices:s,outputShape:a}=r.sparse.sparseReshape(yN("inputIndices",e,t,n),yN("inputShape",e,t,n),yN("newShape",e,t,n));return[s,a]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(yN("data",e,t,n),yN("indices",e,t,n),yN("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(yN("data",e,t,n),yN("indices",e,t,n),yN("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"spectral":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"FFT":return[r.fft(yN("x",e,t,n))];case"IFFT":return[r.ifft(yN("x",e,t,n))];case"RFFT":return[r.rfft(yN("x",e,t,n))];case"IRFFT":return[r.irfft(yN("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"string":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(yN("input",e,t,n),yN("pattern",e,t,n),yN("rewrite",e,t,n),yN("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:s,nGramsSplits:a}=r.string.stringNGrams(yN("data",e,t,n),yN("dataSplits",e,t,n),yN("separator",e,t,n),yN("nGramWidths",e,t,n),yN("leftPad",e,t,n),yN("rightPad",e,t,n),yN("padWidth",e,t,n),yN("preserveShortSequences",e,t,n));return[s,a]}case"StringSplit":{const{indices:s,values:a,shape:i}=r.string.stringSplit(yN("input",e,t,n),yN("delimiter",e,t,n),yN("skipEmpty",e,t,n));return[s,a,i]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(yN("input",e,t,n),yN("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"transformation":return s(()=>((e,t,n,r=G)=>{switch(e.op){case"Cast":return[r.cast(yN("x",e,t,n),yN("dtype",e,t,n))];case"ExpandDims":{const s=yN("axis",e,t,n);return[r.expandDims(yN("x",e,t,n),s)]}case"Squeeze":{const s=yN("axis",e,t,n);return[r.squeeze(yN("x",e,t,n),s)]}case"Reshape":return[r.reshape(yN("x",e,t,n),yN("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(yN("x",e,t,n),yN("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(yN("x",e,t,n),yN("padding",e,t,n),yN("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(yN("x",e,t,n),yN("padding",e,t,n),yN("constantValue",e,t,n))];case"SpaceToBatchND":{const s=yN("blockShape",e,t,n),a=yN("paddings",e,t,n);return[r.spaceToBatchND(yN("x",e,t,n),s,a)]}case"BatchToSpaceND":{const s=yN("blockShape",e,t,n),a=yN("crops",e,t,n);return[r.batchToSpaceND(yN("x",e,t,n),s,a)]}case"DepthToSpace":{const s=yN("blockSize",e,t,n),a=yN("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(yN("x",e,t,n),s,a)]}case"BroadcastTo":return[r.broadcastTo(yN("x",e,t,n),yN("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(yN("s0",e,t,n),yN("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const s=r.getHashTableHandleByName(e.name);if(null!=s)return[s];{const s=yN("keyDType",e,t,n),a=yN("valueDType",e,t,n),i=new fT(s,a);return r.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const s=yN("tableHandle",e,t,n,r),a=yN("keys",e,t,n),i=yN("values",e,t,n),o=r.getHashTableById(s.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const s=yN("tableHandle",e,t,n,r),a=yN("keys",e,t,n),i=yN("defaultValue",e,t,n),o=r.getHashTableById(s.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=yN("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const a=mN(e.op);if(a&&a.customExecutor)return a.customExecutor(new aT(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op \'${e.op}\'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return He(a)?a.then(e=>[].concat(e)):[].concat(a)}class gT{constructor(e={},t={},n={},r={},s){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=s,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;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.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))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{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))}}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)}}function yT(e,t,n,r){const s=new Set,a=[];let i=null,o=null;const u=new Set,l=new Set(Object.keys(e).map(e=>kN(e)[0]));r=r||[];const c=new Set(r.map(e=>kN(e.name)[0])),h=[...t];for(;h.length>0;){const e=h.pop();(kT(e)||IT(e)||ST(e))&&null==i&&(i=e,o=i.children.map(e=>e.name).filter(e=>s.has(e))),s.add(e.name),null==n[e.name]&&(l.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEac
5057h(e=>{u.has(e.name)||(u.add(e.name),h.push(e))}):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:i,syncInputs:o}}class bT extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const xT=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),wT=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),vT=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function kT(e){return xT.has(e.op)}function IT(e){return wT.has(e.op)}function ST(e){return vT.has(e.op)}class NT{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(t=>e[t].map(e=>e.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,null!=e.functions&&Object.keys(e.functions).forEach(t=>{this._functionExecutorMap[t]=new NT(e.functions[t],this)})}getCompilationKey(e,t){const n=e.map(e=>e.name).sort(),r=t.map(e=>e.name).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=yT(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(null!=s)throw new Error(`This execution contains the node \'${s.name}\', which has the dynamic op \'${s.op}\'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){const n=t.map(e=>e.name),s=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${s}]. Missing the following inputs: [${r}]`)}const i=function(e,t){const{usedNodes:n,inputs:r}=t,s=Object.keys(r).map(e=>kN(e)[0]).map(t=>e.nodes[t]),a=e.initNodes||[],i=e=>n.has("string"==typeof e?e:e.name);function o(e){return[...new Map(e.map(e=>[e.name,e])).values()]}const u=o([...s,...e.weights,...a]).filter(i),l=o([...u,...Object.values(e.nodes)]).filter(i),c=new Map(l.map(e=>[e.name,e])),h={};for(const e of l){h[e.name]=h[e.name]||0;for(const t of e.children)i(t)||(h[t.name]=Number.POSITIVE_INFINITY),h[t.name]=(h[t.name]||0)+1}const d=Object.entries(h).filter(([,e])=>0===e).map(([e])=>e),p=[...d];for(;d.length>0;){const e=d.pop(),t=c.get(e);for(const e of t.children.filter(i))0===--h[e.name]&&(p.push(e.name),d.push(e.name))}const f=function(e,t){const n=new Map(e.map(e=>[e.name,e])),r=t.map(e=>e.name),s=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!s.has(e.name)&&(s.add(e.name),r.push(e.name))}return e.filter(e=>s.has(e.name))}(p.map(e=>c.get(e)),u);return function(e,t){const n=new Map(e.map((e,t)=>[e.name,t])),r=new Set(t.map(e=>e.name)),s=e=>r.has("string"==typeof e?e:e.name),a=new Set(e.map(e=>e.name)),i=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(i)){if(!n.has(e.name))throw new bT(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new bT(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}
5057if(!s(t))for(const e of t.inputs){if(!n.has(e.name))throw new bT(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new bT(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}(this.graph,n),o=function(e){const t=new Map(e.map((e,t)=>[e.name,t])),n=Number.MAX_SAFE_INTEGER,r=e.map((e,t)=>kT(e)?n:t),s=e=>{const n=r[t.get(e.name)];return null==n?-1:n},a=e.map((e,t)=>e.children.map(s).reduce((e,t)=>Math.max(e,t),r[t])),i=new Map;for(let t=0;t<e.length;++t){const r=a[t];if(r===n)continue;const s=e[t],o=e[r];i.has(o.name)||i.set(o.name,[]),i.get(o.name).push(s)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return ci(t),t}cloneTensorList(e){if(!e)return null;const t=e.map(e=>this.cloneAndKeepTensor(e));return t}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,this.cloneTensorList(t)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map(e=>this.graph.nodes[kN(e)[0]]),s=t.map(e=>kN(e)[0]),a=new Set(s);let i=s.map(e=>this.graph.nodes[e]);0===i.length&&(i=this._outputs);const o=this.getCompilationKey(r,i);let u=this.compiledMap.get(o);null==u&&(u=this.compile(e,i),this.compiledMap.set(o,u));try{this.keepIntermediateTensors=Xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const l={},c={};return ui(()=>{const n=new gT(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(t=>{const[s,a]=kN(t,n),i=[];i[a]=e[t],r[s]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[s]=this.cloneTensorList(i))});const s=this.getFrozenTensorIds(r),{orderedNodes:i,nodeLiveUntilMap:o}=u;for(const e of i){if(r[e.name])continue;const t=mT(e,r,n,this._resourceManager);if(He(t))throw new Error(`The execution of the op \'${e.op}\' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,s,a,o.get(e.name))}return null==this.parent&&n.dispose(s),t.map(e=>bN(e,r,n))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(t=>e[t]).map(e=>e.map(e=>e.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,s,a,i){if(!kT(t)&&!a.has(e)){for(const r of n[e])null!=r&&(i[r.id]=(i[r.id]||0)+t.children.length);for(const e of t.inputs){if(kT(e))continue;const t=xN(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||s.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,s,a){function i(e){return kT(e)||s.has(e.name)}if(!kT(e)&&null!=a)for(const e of a){if(i(e))continue;const s=xN(e.name,t,n);for(const e of s)!e||e.kept||r.has(e.id)||e.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,n=!1,r={},s={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const a=new gT(this.weightMap,r,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map(e=>bN(e,i,a)),u=o.map(e=>e.id),l=Object.keys(e).map(t=>e[t].id),c=new Set([...u,...l,...this.weightIds]);
5057return Object.values(i).forEach(e=>{e.forEach(e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()})}),null==this.parent&&a.dispose(c),o}async executeFunctionAsync(e,t,n){const r=e.reduce((e,t,n)=>(e[this.inputs[n].name]=t,e),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const s=Object.keys(e),a=s.map(e=>this.graph.nodes[kN(e)[0]]),i=n.map(e=>kN(e)[0]),o=new Set(i);let u=i.map(e=>this.graph.nodes[e]);0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:h,syncInputs:d}=yT(e,u,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(e=>({node:e,contexts:t.currentContext})),f=Object.assign({},this.weightMap);Object.keys(e).forEach(t=>{const[n,r]=kN(t),s=[];s[r]=e[t],f[n]=s});const m={},g=this.getFrozenTensorIds(f),y={};for(;p.length>0;){const e=this.processStack(a,p,t,f,y,g,o,m,l);await Promise.all(e)}null!=h||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=u.filter(e=>!kT(e)&&!bN(e.name,f,t)).map(e=>e.name);if(b.length>0){let e="";throw null!=h&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,r,s,a,i,o,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&yN("isConstant",e.node,r,n)&&([c]=wN(e.node.name,n)),null==r[e.node.name]){const h=mT(e.node,r,n,this._resourceManager);c||([c]=wN(e.node.name,n));const d=n.currentContext;He(h)?l.push(h.then(l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=d,this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u),l))):(r[c]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(h)),this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u))}else this.processChildNodes(e.node,t,n,r,s,u)}return l}processChildNodes(e,t,n,r,s,a){e.children.forEach(e=>{const[i]=wN(e.name,n);!s[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some(e=>!!bN(e,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every(e=>!!bN(e,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(e=>e.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[r]=kN(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){const e=s.attrParams.shape.value;ie(e.length===n.shape.length&&n.shape.every((t,n)=>-1===e[n]||e[n]===t),()=>`The shape of dict[\'${s.name}\'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&ie(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict[\'${s.name}\'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){var t,n;const r={};for(const s in e){const a=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[s];null!=a?r[a.name]=e[s]:r[s]=e[s]}return r}checkInputs(e){const t=Object.keys(e).filter(e=>{const[t]=kN(e);return null==this.graph.nodes[t]});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(e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e},{})}checkOutputs(e){e.forEach(e=>{const[t]=kN(e);if(!this.graph.nodes[t])throw new Error(`The output \'${e}\' is not found in the graph`)})}}class TT{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]}}const ET="?tfjs-format=file",CT="model.json";class $T{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={},n=u){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new TT}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest
vendor: 6,358 bytes, line 5057
5057(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)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(),null==this.handler.load)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 He(e)?e.then(e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Ci(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new NT(GN.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=GN.Instance.transformGraph(e.modelInitializer);this.initializer=new NT(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL \'${e}\'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL \'${e}\'`);e=t[0]}if(null==e.save)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={};return(e instanceof pa?[e]:e).forEach((e,n)=>t[this.structuredOutputKeys[n]]=e),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof pa||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce((t,n)=>{var s,a,i;const o=null===(i=null===(a=null===(s=this.signature)||void 0===s?void 0:s.inputs)||void 0===a?void 0:a[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]:e[r++],t},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r<n.length;r++){const s=t[n[r]];this.resourceIdToCapturedInput[s.resourceId]=e[r]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&li(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function AT(e,t={},n=u){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){return e.endsWith("/")||(e+="/"),`${e}${CT}${ET}`}(e));const r=new $T(e,t,n);return await r.load(),r}function RT(e){if(null==e)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){const[n,r]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!(r&&r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing \'modelTopology\'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing \'weightsManifest\'");t=Eu(Di(n,zi(n.weightsManifest),r))}else if("load"in e)t=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");t=Eu(e)}const n=new $T(t);return n.load(),n}const _T="4.22.0";function MT(e,t,n=new Map,r=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");
vendor: 9,536 bytes, line 5057
5057if(n.has(e))return n.get(e);const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse){if(zT(e)){const s=Array.isArray(e)?[]:{};r.add(e);for(const a in e){const i=MT(e[a],t,n,r);s[a]=i}return r.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}throw new Error(`Can\'t recurse into non-iterable type: ${e}`)}return n.set(e,s.value),s.value}function FT(e,t=OT){return DT(e,t)}function DT(e,t,n=new Set){const r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse){if(zT(r)){const s=Array.isArray(r)?[]:{};n.add(r);for(const a in r){const r=DT(e.map(e=>e[a]),t,n);s[a]=r}return n.delete(r),s}throw new Error(`Can\'t recurse into non-iterable type: ${r}`)}return s.value}function OT(e){return null===e?null:zT(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function LT(e,t){const n=new Map;MT(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(He(t)){const r=await t;n.set(e,r)}}return MT(e,t,n)}function zT(e){let t=!1;if(Xe().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:r}=n(551);t=e instanceof r}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof pa)&&!(e instanceof Promise)&&!t)}function PT(e){return e instanceof pa?{value:e.clone(),recurse:!1}:zT(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class BT{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can\'t create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can\'t create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can\'t get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can\'t set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class VT extends BT{constructor(){super(VT.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e<n;e++)t[e]=this.get(this.wrap(this.begin+e));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}function UT(e){return new HT(e)}function WT(e){return new jT(e)}VT.INITIAL_CAPACITY=32;class GT{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new QT(this,e)}filter(e){return new JT(this,e)}map(e){return new ZT(this,e)}mapAsync(e){return new eE(this,e)}serialMapAsync(e){return new eE(this,e).serial()}flatmap(e){return new nE(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(e=>!0===e)}rowMajorBatch(e,t=!0){return new YT(this,e,t)}columnMajorBatch(e,t=!0,n=OT){return this.rowMajorBatch(e,t).map(e=>FT(e,n))}concatenate(e,t){return new rE(UT([this,e]),t)}take(e){return e<0||null==e?this:new XT(this,e)}skip(e){return e<0||null==e?this:new KT(this,e)}prefetch(e){return new iE(this,e)}shuffle(e,t){return new oE(this,e,t)}serial(){return new qT(this)}}class HT extends GT{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:(t=e,function(e,t){return MT(e,t)}(t,PT)),done:!1};var t}}class jT extends GT{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class qT extends GT{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class KT extends GT{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;li(e.value)}return this.upstream.next()}}class XT extends GT{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class YT extends GT{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class JT extends GT{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;li(e.value)}}}class ZT extends GT{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=$a(e.value),n=this.transform(e.value),r=$a(n);for(const e of t)Ca(e,r)||e.dispose();return{value:n,done:!1}}}class QT extends GT{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class eE extends GT{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=$a(e.value),n=await this.transform(e.value),r=$a(n);for(const e of t)Ca(e,r)||e.dispose();return{value:n,done:!1}}}class tE extends GT{constructor(){super(),this.outputQueue=new VT,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class nE extends tE{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=$a(e.value),n=this.transform(e.value),r=$a(n);this.outputQueue.pushAll(n);for(const e of t)Ca(e,r)||e.dispose();return!0}}class rE extends GT{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var sE;
5057!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(sE||(sE={}));class aE extends GT{constructor(e,t=sE.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;const r=await LT(this.iterators,function(e){return e instanceof GT?{value:e.next().then(e=>(t++,e.done&&n++,e.value)),recurse:!1}:{value:null,recurse:!0}});if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case sE.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case sE.SHORTEST:return{value:null,done:!0};case sE.LONGEST:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class iE extends GT{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new BT(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class oE extends iE{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=gd.alea(n||Xs().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class uE{constructor(){this.size=null}batch(e,t=!0){const n=this;let r;return ie(e>0,()=>`batchSize needs to be positive, but it is\\n      ${e}`),r=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),lE(async()=>(await n.iterator()).columnMajorBatch(e,t,dE),r)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,lE(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,lE(async()=>(await t.iterator()).filter(t=>ui(()=>e(t))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return lE(async()=>(await t.iterator()).map(t=>ui(()=>e(t))),this.size)}mapAsync(e){const t=this;return lE(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return lE(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,lE(async()=>{return n=WT(async()=>({value:await t.iterator(),done:!1})).take(e),new rE(n,r);var n,r},n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size<e||void 0===e||e<0)?0:null,lE(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\\`Dataset.shuffle()\\` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for \\`tf.Tensor\\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const r=this,s=gd.alea(t||Xs().toString());return lE(async()=>{let t=s.int32();return n&&(t+=s.int32()),(await r.iterator()).shuffle(e,t.toString())},this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,lE(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function lE(e,t=null){return new class extends uE{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function cE(e){return lE(async()=>UT(e),e.length)}function hE(e){if(!zT(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=null==t?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=null==t?e[n].size:Math.min(t,e[n].size);return lE(async()=>function(e,t=sE.FAIL){return new aE(e,t)}(await LT(e,e=>
5057{if(e instanceof uE)return{value:e.iterator(),recurse:!1};if(zT(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")}),sE.SHORTEST),t)}function dE(e){if(null===e)return null;return null==(t=e[0])||null===(n=t)||"object"!=typeof n&&"function"!=typeof n||Array.isArray(t)||"object"==typeof t&&t instanceof pa||Qs(t)?{value:function(e){if(0===e.length)throw new Error("Can\'t make a batch of zero elements.");return e[0]instanceof pa?ep(e):Ja(e)}(e),recurse:!1}:{value:null,recurse:!0};var t,n}uE.MAX_BUFFER_SIZE=1e4;class pE extends uE{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\\n").map(e=>(e.endsWith("\\r")&&(e=e.slice(0,-1)),e))}}const fE=\'"\',mE=Symbol("out"),gE=Symbol("field"),yE=Symbol("quote"),bE=Symbol("quoteafterquote"),xE=Symbol("quoteinquote");class wE extends uE{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&ie(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((e,t)=>(e[t]=e[t]+1||1,e),{}),n=Object.keys(t).filter(e=>t[e]>1);if(ie(0===n.length,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const e of Object.keys(this.columnConfigs))if(-1===this.fullColumnNames.indexOf(e))throw new Error(\'The key "\'+e+\'" provided in columnConfigs does not match any of the column names (\'+this.fullColumnNames.toString()+").");this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new pE(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(ie(null==t.delimiter,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(e=>this.makeDataElement(e))}makeDataElement(e){const t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){const a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!this.configuredColumnsOnly||i){const o=t[s];let u=null;if(""===o)if(i&&void 0!==i.default)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);u=void 0}else{const e=Number(o);if(isNaN(e))u=i&&"bool"===i.dtype?this.getBoolean(o):o;else if(i&&i.dtype)switch(i.dtype){case"float32":default:u=e;break;case"int32":u=Math.floor(e);break;case"bool":u=this.getBoolean(o)}else u=e}i&&i.isLabel?r[a]=u:n[a]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}}getBoolean(e){return"1"===e||"true"===e.toLowerCase()?1:0}parseRow(e,t=!0){const n=[];let r=0;const s=e.length;let a=mE;for(let t=0;t<s;t++)switch(a){case mE:switch(e.charAt(t)){case fE:r=t+1,a=yE;break;case this.delimiter:if(r=t+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=mE;break;default:a=gE,r=t}break;case gE:e.charAt(t)===this.delimiter&&(n.push(e.substring(r,t)),a=mE,r=t+1);break;case yE:e.charAt(t)===fE&&(a=bE);break;case bE:switch(e.charAt(t)){case this.delimiter:n.push(e.substring(r,t-1)),a=mE,r=t+1;break;case fE:a=yE;break;default:a=xE}break;case xE:e.charAt(t)===fE&&(a=yE)}
vendor: 4,322 bytes, line 5057
5057if(a===bE?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class vE extends GT{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!Xe().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new vE(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(e){throw new Error(`Error thrown while initializing video stream: ${e.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise(r=>{const s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),r({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((e,r)=>n.set(e,r*t)),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(le(t));return n.set(e,n.length-e.length),Ja(n,t)}}class kE extends GT{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=sp([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,r=(1-t)/2,s=n+e,a=t+r;this.cropBox=ap([r,n,a,s],[1,4])}else this.cropBox=ap([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}
5057){if(!Xe().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new kE(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&ie("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide \'user\' or \'environment\'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Hu(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return ui(()=>{const t=dh(Io(e,"float32"),0);let n;n=Df.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const r=n.shape;return sc(n,r.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class IE{}class SE extends GT{split(e){return new NE(this,e)}}class NE extends SE{constructor(e,t){super(),this.upstream=e,this.impl=new TE(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class TE extends tE{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split(\'${this.separator}\')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const e of t.slice(0,-1))this.outputQueue.push(e);return this.carryover=t[t.length-1],!0}}class EE extends GT{decodeUTF8(){return new CE(this)}}class CE extends SE{constructor(e){super(),this.upstream=e,this.impl=new $E(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class $E extends tE{constructor(e){if(super(),this.upstream=e,Xe().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=n(530);this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=Xe().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class AE extends EE{constructor(e,t={}){super(),this.file=e,this.options=t,ie(e instanceof Uint8Array||!!Xe().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise((e,t)=>
5057{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const r=new FileReader;r.onload=n=>{let s=r.result;if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),!(s instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(s)},r.onabort=e=>t(new Error("Aborted")),r.onerror=e=>t(new Error(e.type));const s=this.file.slice(this.offset,n);r.readAsArrayBuffer(s)}this.offset=n});return{value:await e,done:!1}}}function RE(e){return"string"==typeof e&&"file://"===e.slice(0,7)}class _E extends IE{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(RE(this.input)&&Xe().get("IS_NODE")){const e=n(108);this.input=e.readFileSync(this.input.slice(7))}return new AE(this.input,this.options)}}class ME extends IE{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return RE(this.url)?new _E(this.url,this.fileOptions).iterator():async function(e,t={},n){let r,s;var a;"string"==typeof e?r=e:(r=e.url,s={method:(a=e).method,headers:a.headers,body:a.body,mode:a.mode,credentials:a.credentials,cache:a.cache,redirect:a.redirect,referrer:a.referrer,integrity:a.integrity});const i=await(n||Ys)(r,s);if(i.ok){const e=new Uint8Array(await i.arrayBuffer());return new AE(e,t)}throw new Error(i.statusText)}(this.url,this.fileOptions)}}function FE(e,t={}){return new wE(new ME(e),t)}function DE(e){const t=WT(e);return lE(async()=>t)}function OE(e){return lE(async()=>{const t=await e();return WT(()=>t.next())})}async function LE(e,t){return kE.create(e,t)}async function zE(e){return vE.create(e)}const PE="4.22.0";function BE(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&ie("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const VE=yp;class UE extends Y{nextDataId(){return UE.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new X(this,ai())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Xe().get("IS_NODE")&&xs("\\n============================\\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \\n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&$e(n[0])){const s=n.map(e=>Js(e));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?dm(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):ze(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map(e=>Zs(e));return ko(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return ko(e.shape,e.dtype,t)}makeOutput(e,t,n){return ai().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Xs();return e(),{kernelMs:Xs()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){BE([e],"where");const t=this.readSync(e.dataId);return VE(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function WE(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}UE.nextDataId=0;const GE={kernelName:et,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;BE(t,"abs");let r=new Float32Array(le(t.shape));return r=WE(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,t.dtype)}};function HE(e){return(t,n,r,s,a)=>{const i=ru(t,n),o=i.length,u=De(i),l=ke(a,le(i)),c=t.length,h=n.length,d=De(t),p=De(n),f=tu(t,i),m=tu(n,i);if(f.length+m.length===0)for(let t=0;t<l.length;++t)l[t]=e(r[t%r.length],s[t%s.length]);else for(let t=0;t<l.length;++t){const n=Ge(t,o,u),a=n.slice(-c);
5057f.forEach(e=>a[e]=0);const i=We(a,c,d),g=n.slice(-h);m.forEach(e=>g[e]=0);const y=We(g,h,p);l[t]=e(r[i],s[y])}return[l,i]}}function jE(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=n.makeTensorInfo(r.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",i)},o}const qE={kernelName:Et,backendName:"cpu",kernelFunc:jE};function KE(e,t,n="float32"){if("complex64"===n)return jE({inputs:{real:KE(e,t,"float32"),imag:KE(e,t,"float32")},backend:e});const r=Be(le(t),n);return e.makeTensorInfo(t,n,r)}function XE(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const YE={kernelName:yn,backendName:"cpu",kernelFunc:XE};function JE(e){const{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.real,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}const ZE={kernelName:mr,backendName:"cpu",kernelFunc:JE};function QE(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=Ks([0],n),[s,a]=HE((e,t)=>e!==t?1:0)(t,[],e,r,"bool");return[a,"bool",s]}throw new Error(`Error in Cast: failed to cast ${n} to ${r}`)}function eC(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if("complex64"===a){if("complex64"===s.dtype)return XE({inputs:{x:s},backend:n});const e=KE(n,s.shape,s.dtype),t=eC({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),r=jE({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===s.dtype){const e=JE({inputs:{input:s},backend:n}),t=eC({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}
5057if(!Te(s.dtype,a)){const e=XE({inputs:{x:s},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}const i=n.data.get(s.dataId).values,[o,u,l]=QE(i,s.shape,s.dtype,a);return n.makeTensorInfo(o,u,l)}const tC={kernelName:St,backendName:"cpu",kernelFunc:eC};function nC(e,t,n,r){return null==n?({inputs:n,backend:s})=>{const{a,b:i}=n,o=s;BE([a,i],e);const u=o.data.get(a.dataId).values,l=o.data.get(i.dataId).values,c="string"===a.dtype?jm(u):u,h="string"===a.dtype?jm(l):l,d=r||a.dtype,[p,f]=t(a.shape,i.shape,c,h,d);return o.makeTensorInfo(f,d,p)}:({inputs:e,backend:s})=>{const{a,b:i}=e,o=s;if("complex64"===a.dtype||"complex64"===i.dtype){const e=eC({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),r=t.complexTensorInfos.real,s=t.complexTensorInfos.imag,u=o.data.get(r.dataId).values,l=o.data.get(s.dataId).values,c=eC({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),d=h.complexTensorInfos.real,p=h.complexTensorInfos.imag,f=o.data.get(d.dataId).values,m=o.data.get(p.dataId).values,[g,y,b]=n(a.shape,i.shape,u,l,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=jE({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(a.dataId).values,n=o.data.get(i.dataId).values,s=r||a.dtype,[u,l]=t(a.shape,i.shape,e,n,s);return o.makeTensorInfo(l,s,u)}}}function rC(e){return(t,n,r,s,a,i)=>{const o=ru(t,n),u=le(o),l=o.length,c=De(o),h=ke("float32",u),d=ke("float32",u),p=tu(t,o),f=tu(n,o),m=dm(r,s),g=dm(a,i),y=t.length,b=De(t),x=n.length,w=De(n);if(p.length+f.length===0)for(let t=0;t<h.length;t++){const n=t%m.length,r=t%g.length,s=e(m[2*n],m[2*n+1],g[2*r],g[2*r+1]);h[t]=s.real,d[t]=s.imag}else for(let t=0;t<h.length;t++){const n=Ge(t,l,c),r=n.slice(-y);p.forEach(e=>r[e]=0);const s=We(r,y,b),a=n.slice(-x);f.forEach(e=>a[e]=0);const i=We(a,x,w),o=e(m[2*s],m[2*s+1],g[2*i],g[2*i+1]);h[t]=o.real,d[t]=o.imag}return[h,d,o]}}const sC=HE((e,t)=>e+t),aC=rC((e,t,n,r)=>({real:e+n,imag:t+r})),iC=nC(rt,sC,aC),oC={kernelName:rt,backendName:"cpu",kernelFunc:iC};function uC(e,t,n,r,s){const a=le(r),i=Be(s,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0)throw new Error("Input x must be non-negative!");r>=s||(i[r]+=a>0?t[n]:1)}return i}function lC(e,t,n,r=!1){const s=e.shape[0],a=e.shape[1],i=ko([s,n],t.dtype);for(let o=0;o<s;o++)for(let s=0;s<a;s++){const a=e.get(o,s);if(a<0)throw new Error("Input x must be non-negative!");a>=n||(r?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,s),o,a):i.set(i.get(o,a)+1,o,a))}return i}const cC=HE((e,t)=>e&t),hC=nC(vt,cC),dC={kernelName:vt,backendName:"cpu",kernelFunc:hC};function pC(e){return(t,n,r)=>{const s=Ie(n,t.length);for(let n=0;n<t.length;++n)s[n]=e(t[n],r);return s}}function fC(e,t,n){return mC(e,pC(t),n)}function mC(e,t,n){return({inputs:r,attrs:s,backend:a})=>{const{x:i}=r;BE(i,e);const o=a,u=o.data.get(i.dataId).values;let l;if("string"===i.dtype){if(!Array.isArray(u))throw new Error("String tensor\'s value was not an instance of Array");l=jm(u)}else l=u;const c=n||i.dtype,h=t(l,c,s);return o.makeTensorInfo(i.shape,c,h)}}const gC=pC(e=>Math.ceil(e)),yC=mC(Nt,gC),bC={kernelName:Nt,backendName:"cpu",kernelFunc:yC};function xC(e,t,n,r){const s=Ie(n,le(t));if(r&&"string"!==n){let t=0;e.forEach(e=>{const n=le(e.shape);s.set(e.vals,t),t+=n})}else{let r=0;e.forEach(e=>{const a="string"===n?jm(e.vals):e.vals;let i=0;for(let n=0;n<e.shape[0];++n){const o=n*t[1]+r;for(let t=0;t<e.shape[1];++t)s[o+t]=a[i++]}r+=e.shape[1]})}return s}const wC=HE((e,t)=>e===t?1:0),vC=nC(nn,wC,null,"bool"),kC={kernelName:nn,backendName:"cpu",kernelFunc:vC},IC=pC(e=>Math.exp(e)),SC=mC(rn,IC,"float32"),NC={kernelName:rn,backendName:"cpu",kernelFunc:SC},TC=pC(e=>Math.expm1(e)),EC=mC(an,TC),CC={kernelName:an,backendName:"cpu",kernelFunc:EC},$C=pC(e=>Math.floor(e)),AC=mC(cn,$C),RC={kernelName:cn,backendName:"cpu",kernelFunc:AC},_C=HE((e,t)=>Math.floor(e/t)),MC=nC(hn,_C,null,"int32"),FC={kernelName:hn,backendName:"cpu",kernelFunc:MC};function DC(e,t,n,r,s,a,i,o,u){const l=ko([r,a],n);for(let n=0;n<r;n++){const r=[];let c=0;for(let t=0;t<s;t++){const a=e[n*s+t];c+=a*i[t],r.push(a)}if(c<0||c>=u/a)throw new Error(`Invalid indices: ${r} does not index into ${o}`);for(let e=0;e<a;e++)l.values[n*a+e]=t.get(...t.indexToLoc(c*a+e))}return l}
5057function OC(e,t,n){const r=ko(n,e.dtype);for(let n=0;n<r.size;++n){const s=r.indexToLoc(n).slice(),a=s[0],i=s[2],o=t.locToIndex([a,i]);s[2]=t.values[o];const u=e.locToIndex(s);0<=u&&u<e.values.length&&(r.values[n]=e.values[u])}return r}const LC=HE((e,t)=>e>t?1:0),zC=nC(mn,LC,null,"bool"),PC={kernelName:mn,backendName:"cpu",kernelFunc:zC},BC=HE((e,t)=>e>=t?1:0),VC=nC(gn,BC,null,"bool"),UC={kernelName:gn,backendName:"cpu",kernelFunc:VC},WC=HE((e,t)=>e<t?1:0),GC=nC(Sn,WC,null,"bool"),HC={kernelName:Sn,backendName:"cpu",kernelFunc:GC},jC=HE((e,t)=>e<=t?1:0),qC=nC(Nn,jC,null,"bool"),KC={kernelName:Nn,backendName:"cpu",kernelFunc:qC};function XC(e,t,n){const r=(t-e)/(n-1),s=Be(n,"float32");s[0]=e;for(let e=1;e<s.length;e++)s[e]=s[e-1]+r;return s}const YC=pC(e=>Math.log(e)),JC=mC(En,YC),ZC={kernelName:En,backendName:"cpu",kernelFunc:JC};function QC(e,t,n,r){const s=ke(r,le(n));for(let n=0;n<s.length;++n){const r=n*t;let a=e[r];for(let n=0;n<t;++n){const t=e[r+n];(Number.isNaN(t)||t>a)&&(a=t)}s[n]=a}return s}const e$=HE((e,t)=>Math.max(e,t)),t$=nC(Pn,e$),n$={kernelName:Pn,backendName:"cpu",kernelFunc:t$},r$=HE((e,t)=>Math.min(e,t)),s$=nC(qn,r$),a$={kernelName:qn,backendName:"cpu",kernelFunc:s$},i$=HE((e,t)=>e*t),o$=rC((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n})),u$=nC(Jn,i$,o$),l$={kernelName:Jn,backendName:"cpu",kernelFunc:u$};function c$(e,t,n){const r=qs(-1,n);return i$([],t,r,e,n)}const h$={kernelName:Zn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;BE(r,"neg");const s=n.data.get(r.dataId).values,[a,i]=c$(s,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,a)}},d$=HE((e,t)=>e!==t?1:0),p$=nC(Qn,d$,null,"bool"),f$={kernelName:Qn,backendName:"cpu",kernelFunc:p$};function m$(e,t,n,r,s){const a=t.length,i=le(t),o=De(t),u=De(s),l=ke(n,le(s));for(let t=0;t<i;++t){const n=Ge(t,a,o),s=new Array(n.length);for(let e=0;e<s.length;e++)s[e]=n[r[e]];l[We(s,a,u)]=e[t]}return l}function g$(e){const{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{perm:a}=n;BE(s,"transpose");const i=s.shape.length,o=new Array(i);for(let e=0;e<o.length;e++)o[e]=s.shape[a[e]];const u=m$(r.data.get(s.dataId).values,s.shape,s.dtype,a,o);return{dataId:r.write(u,o,s.dtype),shape:o,dtype:s.dtype}}const y$={kernelName:os,backendName:"cpu",kernelFunc:g$};function b$(e,t,n,r){const[s,a]=Qc(e,r),i=ka(t,"int32"),o=Be(le(s),i),u=le(a);for(let e=0;e<o.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e)r*=n[t+e];o[e]=r}return{outVals:o,outShape:s,outDtype:i}}const x$={kernelName:cr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;BE(s,"prod");const o=s.shape.length,u=we(a,s.shape),l=nh(u,o);let c=u,h=s;const d=[];null!=l&&(h=g$({inputs:{x:s},backend:n,attrs:{perm:l}}),d.push(h),c=sh(c.length,o));const p=n.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=b$(h.shape,h.dtype,p,c);let y=m;return i&&(y=eh(m,u)),d.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(y,g,f)}};function w$(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let r=t;r<e.length;r++)n[t-1]*=e[r];return n}function v$(e,t,n,r,s,a,i,o){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach((e,r)=>{if(e<0||e>=n){const s=Ge(r,t.length,De(t)).join(",");throw new Error(`indices[${s}] = ${e} is not in [0, ${n})`)}})}(a,i,t[0][0]-1),0===r.length)throw new Error("params.rank must be nonzero");const u=r[0],{outSplits:l,valueSlices:c,numValues:h}=function(e,t,n,r){const s=[];let a=0;const i=t.length-1+n.length,o=new Array(i).fill(null).map(()=>[0]);!function(e,t){for(let n=0;n<e.length;++n){const r=e[n],s=n===e.length-1?t:e[n+1].length;if(0===r.length)throw new Error("Ragged splits may not be empty");if(r[0]<0)throw new Error("Ragged splits must be non-negative");if(r[r.length-1]>s)throw new Error("Ragged splits must not point past values");for(let e=1;e<r.length;++e)if(r[e-1]>r[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,r);let u=1;for(let e=0;e<t.length-1;++e){u*=t[e];const n=t[e+1];for(let t=1;t<u+1;++t)o[e].push(t*n)}for(let r=0;r<e.length;++r){let i=e[r],u=e[r]+1;for(let e=0;e<n.length;++e){const r=n[e],s=e+t.length-1;if(s>=0){const e=o[s],t=e[e.length-1]-r[i];for(let e=i;e<u;++e)o[s].push(r[e+1]+t)}i=r[i],u=r[u]}u!==i&&(s.push([i,u]),a+=u-i)}
vendor: 26,215 bytes, line 5057
5057return{outSplits:o,valueSlices:s,numValues:a}}(a,i,e,u),d=function(e){const t=[];for(let n=0;n<e.length;++n){const r=Ie("int32",e[n].length);t.push(r),e[n].forEach((e,t)=>r[t]=e)}return t}(l),p=function(e,t,n,r,s){const a=t.slice();a[0]=s;const i=Ie(n,le(a)),o=e.length;return function(e,t,n,r,s,a){const i=w$(t,2)[1],o=w$(a,2)[1];let u=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<r;++t)s[u*o+t]=e[n*i+t];++u}}(e,t,r,0===o?0:o/t[0],i,a),[i,a]}(n,r,s,c,h);return[d,p[0],p[1]]}const k$=2147483647;function I$(e,t,n,r,s,a,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(s.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");const o=0===t.length,u=0===s.length,l=0===i.length,c=[];o||c.push(t[0]),u||c.push(s[0]),l||c.push(i[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const h=0===c.length?1:c[0],d=Ie("int32",h+1);d[0]=0;for(let t=0;t<h;++t){const n=o?e[0]:e[t],s=u?r[0]:r[t],i=l?a[0]:a[t];if(0===i)throw new Error("Requires delta != 0");let c;if(i>0&&s<n||i<0&&s>n)c=0;else if(c=Math.ceil(Math.abs((s-n)/i)),c>k$)throw new Error(`Requires ((limit - start) / delta) <= ${k$}`);d[t+1]=d[t]+c}const p=Ie(n,d[h]);let f=0;for(let t=0;t<h;++t){const n=d[t+1]-d[t];let r=o?e[0]:e[t];const s=l?a[0]:a[t];for(let e=0;e<n;++e)p[f++]=r,r+=s}return[d,p]}var S$=Hf;class N${constructor(e,t,n,r,s,a,i,o,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=s,this.defaultValue=a,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=qf(l),this.raggedRank=Kf(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===S$.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===S$.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case S$.VALUE_ROWIDS:return N$.getMaxWidthValueRowID(t);case S$.ROW_SPLITS:return N$.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${S$[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let r=0;r<t-1;++r){const t=e[r+1]-e[r];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,r=e[0],s=0;for(let a=1;a<t;++a){const t=e[a];t!==r&&(r=t,s=Math.max(a-n,s),n=a)}return Math.max(t-n,s)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return E$(e,n)}calculateOutputSize(e){const t=this.valuesShape;Xf(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=jf(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let e=1;e<=this.raggedRank;++e)r[e]<0&&(r[e]=this.getMaxWidth(e));return r}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),s=[];let a=0;for(let e=0;e<r;++e,a+=t)s.push(a);for(let t=r;t<e;++t)s.push(-1);return ie(s.length===e,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(e,t,n,r){const s=e.length,a=[];for(let i=0;i<s-1;++i){const s=e[i+1]-e[i];let o=Math.min(r,s),u=t[i];-1===u&&(o=0);for(let e=0;e<o;++e)a.push(u),u+=n;for(let e=0;e<s-o;++e)a.push(-1)}if(s>0&&a.length!==e[s-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,r){const s=e.length,a=[];if(0===s)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let u=t[o];a.push(u);for(let l=1;l<s;++l){const s=e[l];if(s===o)u>=0&&(++i,i<r?u+=n:u=-1);else{if(i=0,o=s,s>=t.length)throw new Error(`Got nextValueRowId=${s} which is not less than ${t.length}`);u=t[s]}a.push(u)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,r){const s=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case S$.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,t,n,r);case S$.ROW_SPLITS:if(s.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(s,t,n,r);default:throw new Error(`Unsupported partition type: ${S$[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case S$.FIRST_DIM_SIZE:return e[0];case S$.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case S$.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${S$[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const r=E$(t,!1),s=Ie(this.valuesDType,le(r));if(n[0]*t[0]>0){let a=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e)a=this.calculateOutputIndex(e-1,a,n[e],t[e]);this.setOutput(this.raggedRank,a,s,r)}return[r,s]}setOutput(e,t,n,r){if(0===n.length)return;const s=this.values,a=n;let i=r.slice();i=i.slice(e+1);const o=le(i),u=t.length;let l=this.defaultValue;if(l.length!==o&&1!==l.length){const e=this.defaultValueShape;ui(()=>{const t=sc(l,e),n=wc(t,i);l=n.dataSync()})}let c=0,h=0,d=0;for(let e=0;e<=u;++e){let r=e<u?t[e]:-1;if(r!==d){if(h<d){const e=s.subarray(c*o);T$(a.subarray(h*o),e,(d-h)*o)}if(e>=u){const e=n.length;r=Math.floor(e/o)}if(r>d)if(1===this.defaultValue.length)a.subarray(d*o,r*o).fill(this.defaultValue[0]),d=r;else for(;r>d;)T$(a.slice(d*o),l,o),++d;r<0?(c=e+1,h=d):(c=e,h=d,d=h+1)}else++d}}}function T$(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function E$(e,t){const n=[];for(let r of e){if(r<0){if(!t)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}n.push(r)}return n}function C$(e,t,n,r,s,a,i,o,u,l){return new N$(e,t,n,r,s,a,i,o,u,l).compute()}function $$(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return Be(0,r);const s=Be(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),s[0]=e;for(let e=1;e<s.length;e++)s[e]=s[e-1]+n;return s}const A$=pC(e=>1/Math.sqrt(e)),R$=mC(Tr,A$),_$={kernelName:Tr,backendName:"cpu",kernelFunc:R$};function M$(e,t,n,r,s,a,i,o,u,l){const c=[r/s,s],h=e.values,d=t.values;if(0===r)return ko(n,t.dtype);const p=u instanceof la?u:ko(c,t.dtype);"string"==typeof u||"number"==typeof u?p.values.fill(u):"boolean"==typeof u&&p.values.fill(+u);for(let e=0;e<a;e++){const a=[];let u=0;for(let t=0;t<i;t++){const n=h[e*i+t];a.push(n),u+=n*o[t]}if(u<0||u>=r/s)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n<s;n++)l?p.values[u*s+n]+=d[e*s+n]:p.values[u*s+n]=0===t.rank?d[0]:d[e*s+n]}return p}const F$=pC(e=>1/(1+Math.exp(-e))),D$=fC(Or,e=>1/(1+Math.exp(-e))),O$={kernelName:Or,backendName:"cpu",kernelFunc:D$};function L$(e,t,n,r,s){const a=cl(r,t,n),i=le(n),o=De(r);if(a){const n=hl(t,o);return"string"===s?e.slice(n,n+i):e.subarray(n,n+i)}const u=ko(r,s,"string"===s?jm(e):e),l=ko(n,s);for(let e=0;e<l.size;++e){const n=l.indexToLoc(e),r=n.map((e,n)=>e+t[n]);l.set(u.get(...r),...n)}return"string"===s?qm(l.values):l.values}function z$(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r;BE(s,"slice");const[o,u]=dl(s,a,i);Zu(s,o,u);const l=L$(n.data.get(s.dataId).values,o,u,s.shape,s.dtype);return n.makeTensorInfo(u,s.dtype,l)}const P$={kernelName:_r,backendName:"cpu",kernelFunc:z$};function B$(e,t,n,r,s,a,i){const o=t[0],u=a[0],l=new Array(u),c=new Array(o),h=t[1];if(0===u){if(0!==o)throw new Error(Rm(o));return[Ie(n,0),[0,h],Ie(s,0),l,c]}let d=!0,p=0;const f=new Array(u).fill(0);for(let t=0;t<o;++t){const n=e[t*h];if(n<0)throw new Error(_m(t,n));if(n>=u)throw new Error(Mm(t,n,u));++f[n],d=d&&n>=p,p=n}let m=!0;for(let e=0;e<u;++e){const t=0===f[e];l[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&d){const t=e,n=r;for(let e=0;e<o;++e)c[e]=e;return[t,[o,h],n,l,c]}{const t=f[u-1],a=Ie(n,t*h),d=Ie(s,t),p=new Array(u).fill(0);for(let t=0;t<o;++t){const n=e[t*h],s=p[n],i=(0===n?0:f[n-1])+s;p[n]++;for(let n=0;n<h;++n)a[i*h+n]=e[t*h+n];d[i]=r[t],c[t]=i}for(let e=0;e<u;++e)if(0===p[e]){const t=0===e?0:f[e-1];a[t*h+0]=e;for(let e=1;e<h;++e)a[t*h+e]=0;d[t]=i}return[a,[t,h],d,l,c]}}function V$(e,t,n,r,s){const a=le(r),i=t[0],o=s.length,u=[];let l=1,c=-1;for(let e=0;e<o;++e){const t=s[e];if(-1===t){if(-1!==c)throw new Error(Fm(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Dm(e,t));l*=t,u.push(t)}}if(-1!==c){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(a/l);if(l*e!==a)throw new Error(Lm(r,u));u[c]=e}if(le(u)!==a)throw new Error(zm(r,u));const h=r.length,d=[];if(h>0){d[h-1]=1;for(let e=h-2;e>=0;--e)d[e]=d[e+1]*r[e+1]}const p=[];if(o>0){p[o-1]=1;for(let e=o-2;e>=0;--e)p[e]=p[e+1]*u[e+1]}const f=Ie(n,i*o);for(let t=0;t<i;++t){let n=0;for(let r=0;r<h;++r)n+=e[t*h+r]*d[r];for(let e=0;e<o;++e)f[t*o+e]=Math.trunc(n/p[e]),n%=p[e]}return[f,[i,o],u]}function U$(e,t,n,r,s,a=!1,i=0){const o=r.length,u=[t[0],e.length/t[0]],l=u[1],c=o>0?s[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const d=Ie(n,h.reduce((e,t)=>e*t,1));if(0===o)return c>0&&d.fill(i),[d,h];if(c<=0)throw new Error("segment ids must be >= 0");let p=0,f=1,m=0,g=s[p];for(;;){let t=0;if(f<o){if(t=s[f],g===t){++f;continue}if(g>=t)throw new Error(Bm())}if(g<0||g>=c)throw new Error(Vm(g,c));g>m&&d.fill(i,m*l,g*l);for(let t=p;t<f;++t){const n=r[t];if(n<0||n>=u[0])throw new Error(Um(t,r[t],u[0]));for(let t=0;t<l;t++)d[g*l+t]+=e[n*l+t]}if(a)for(let e=0;e<l;e++)d[g*l+e]/=f-p;if(p=f,++f,m=g+1,g=t,f>o)break}return m<c&&d.fill(i,m*l,c*l),[d,h]}const W$=pC(e=>Math.sqrt(e)),G$=fC(zr,e=>Math.sqrt(e)),H$={kernelName:zr,backendName:"cpu",kernelFunc:G$},j$=HE((e,t)=>{const n=e-t;return n*n}),q$=nC(Kr,j$),K$={kernelName:Kr,backendName:"cpu",kernelFunc:q$},X$=pC((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:s}=t;return e.replace(new RegExp(n,r?"g":""),s)}),Y$=mC(Yr,X$),J$={kernelName:Yr,backendName:"cpu",kernelFunc:Y$};function Z$(e,t,n,r){const s=ko(e,t.dtype);for(let e=0;e<s.size;e++){const a=s.indexToLoc(e),i=new Array(a.length);for(let e=0;e<i.length;e++)i[e]=a[e]*n[e]+r[e];s.set(t.get(...i),...a)}return s}class Q${constructor(e,t,n,r,s,a){this.separator=Js(e),this.nGramWidths=t,this.leftPad=Js(n),this.rightPad=Js(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let i=0;i<s;++i){const o=this.getPadWidth(a),u=Math.max(0,o-i),l=Math.max(0,o-(s-(i+1))),c=a-(u+l),h=t+(u>0?0:i-o);let d=0;d+=u*this.leftPad.length;for(let t=0;t<c;++t)d+=e[h+t].length;d+=l*this.rightPad.length,d+=(u+l+c-1)*this.separator.length,n[r+i]=new Uint8Array(d);const p=n[r+i];let f=0;const m=e=>e.forEach(e=>p[f++]=e);for(let e=0;e<u;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[h+t]),m(this.separator);if(c>0){m(e[h+c-1]);for(let e=0;e<l;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<l-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,r=t.length;if(r>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let s=1;s<r;++s){let r=t[s]>=e;if(r=r&&t[s]<=n,!r)throw new Error(`Invalid split value ${t[s]}, must be in [${e}, ${n}]`);e=t[s]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const s=r-1,a=Ie("int32",r);if(0===n||0===r){const e=new Array(n);for(let e=0;e<=s;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=s;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach(e=>{r+=this.getNumNGrams(n,e)}),this.preserveShort&&n>0&&0===r&&(r=1),a[e]=a[e-1]+r}const i=new Array(a[s]);for(let n=0;n<s;++n){const r=t[n];let s=a[n];if(this.nGramWidths.forEach(a=>{const o=t[n+1]-t[n],u=this.getNumNGrams(o,a);this.createNGrams(e,r,i,s,u,a),s+=u}),this.preserveShort&&s===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,u=1;this.createNGrams(e,r,i,s,u,o)}}return[i,a]}}function eA(e,t,n,r,s,a,i,o){return new Q$(n,r,s,a,i,o).compute(e,t)}function tA(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)r.push(e.subarray(t,t+1));return}if(1===t.length){const s=t[0];let a=e.indexOf(s);for(;-1!==a;){const t=e.subarray(0,a);n&&0===t.length||r.push(t),a=(e=e.subarray(a+1)).indexOf(s)}return void(n&&0===e.length||r.push(e))}let s=0;for(let a=0;a<e.length+1;a++)if(a===e.length||-1!==t.indexOf(e[a])){const t=e.subarray(s,a);n&&0===t.length||r.push(t),s=a+1}}function nA(e,t,n){const r=e.length,s=[];let a=0,i=0;const o=new Array(r);for(let u=0;u<r;++u){const r=s.length;tA(e[u],t,n,s);const l=s.length-r;o[u]=l,a+=l,i=Math.max(i,l)}const u=Ie("int32",2*a),l=new Array(a),c=[r,i];let h=0;for(let e=0;e<r;++e)for(let t=0;t<o[e];++t)u[2*h]=e,u[2*h+1]=t,l[h]=s[h],++h;return[u,l,c]}function rA(e,t){const n=Ie("int32",e.length);for(let r=0;r<e.length;++r)n[r]=js(e[r]).modulo(t).getLowBitsUnsigned();return n}const sA=HE((e,t)=>e-t),aA=rC((e,t,n,r)=>({real:e-n,imag:t-r})),iA=nC(ts,sA,aA),oA={kernelName:ts,backendName:"cpu",kernelFunc:iA};function uA(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const r=ko(n,e.dtype);for(let t=0;t<r.values.length;++t){const n=r.indexToLoc(t),s=new Array(e.rank);for(let t=0;t<s.length;t++)s[t]=n[t]%e.shape[t];const a=e.locToIndex(s);r.values[t]=e.values[a]}return r}const lA=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function cA(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const s=r-n+1,a=t-n+1,i=Math.log(s),o=.5*Math.exp(2*i/3),u=.5*Math.sqrt(i*o*(s-o)/s)*Math.sign(a-s/2);cA(e,t,Math.max(n,Math.floor(t-a*o/s+u)),Math.min(r,Math.floor(t+(s-a)*o/s+u)))}const s=e[t];let a=n,i=r;for(ne(e,n,t),lA(e[r],s)>0&&ne(e,n,r);a<i;){for(ne(e,a,i),a++,i--;lA(e[a],s)<0;)a+=1;for(;lA(e[i],s)>0;)i-=1}0===lA(e[n],s)?ne(e,n,i):(i+=1,ne(e,i,r)),i<=t&&(n=i+1),t<=i&&(r=i-1)}}function hA(e,t,n,r,s){const a=t[t.length-1],[i,o]=[e.length/a,a],u=ke(n,i*r),l=ke("int32",i*r);for(let t=0;t<i;t++){const n=t*o,a=e.subarray(n,n+o);let i=new Array(a.length);a.forEach((e,t)=>i[t]={value:e,index:t}),r<i.length&&(cA(i,r),i=i.slice(0,r)),s&&i.sort(lA);const c=t*r,h=u.subarray(c,c+r),d=l.subarray(c,c+r);for(let e=0;e<r;e++)h[e]=i[e].value,d[e]=i[e].index}const c=t.slice();return c[c.length-1]=r,[ko(c,n,u),ko(c,"int32",l)]}function dA(e,t,n,r){const s=we(t,n)[0],a=[1,n[0],1];for(let e=0;e<s;e++)a[0]*=n[e];a[1]=n[s];for(let e=s+1;e<n.length;e++)a[2]*=n[e];const i=new Map,o=new Int32Array(n[s]),u=new la(a,r,e),l=[],c=1===a[0]&&1===a[2];for(let t=0;t<n[s];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<a[0];n++)for(let r=0;r<a[2];r++)e.push(u.get(n,t,r));n=e.join(",")}const r=i.get(n);if(null!=r)o[t]=r;else{const e=i.size;i.set(n,e),o[t]=e,l.push(t)}}const h=a.slice();h[1]=i.size;const d=new la(h,r);l.forEach((e,t)=>{for(let n=0;n<a[0];n++)for(let r=0;r<a[2];r++)d.set(u.get(n,e,r),n,t,r)});const p=n.slice();return p[s]=h[1],{outputValues:d.values,outputShape:p,indices:o}}const pA="4.22.0";bi("cpu",()=>new UE,1);const fA=fC(Qt,e=>e>=0?e:Math.exp(e)-1),mA={kernelName:Qt,backendName:"cpu",kernelFunc:fA};function gA(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r;BE([s],"leakyRelu");const i=le(s.shape),o=n.data.get(s.dataId).values,u=ke("float32",i);for(let e=0;e<o.length;e++)u[e]=o[e]<0?a*o[e]:o[e];return n.makeTensorInfo(s.shape,"float32",u)}const yA={kernelName:In,backendName:"cpu",kernelFunc:gA},bA=HE((e,t)=>e<0?t*e:e);function xA(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t;BE([r,s],"prelu");const a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,[o,u]=bA(r.shape,s.shape,a,i,"float32");return n.makeTensorInfo(u,"float32",o)}const wA={kernelName:lr,backendName:"cpu",kernelFunc:xA},vA=fC(yr,e=>Math.max(0,e)),kA={kernelName:yr,backendName:"cpu",kernelFunc:vA},IA=fC(Ir,e=>Math.min(Math.max(0,e),6)),SA={kernelName:Ir,backendName:"cpu",kernelFunc:IA};function NA(e,t,n,r,s){if("linear"===n)return XE({inputs:{x:t},backend:e});if("relu"===n)return vA({inputs:{x:t},backend:e});if("elu"===n)return fA({inputs:{x:t},backend:e});if("relu6"===n)return IA({inputs:{x:t},backend:e});if("prelu"===n)return xA({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return gA({inputs:{x:t},backend:e,attrs:{alpha:s}});if("sigmoid"===n)return D$({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function TA(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,i=le(s.shape),o=xe(a,i),u=le(o);ie(i===u,()=>`The new shape (${o}) has ${u} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),n.incRef(s.dataId);const l=n.data.get(s.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:s.dataId,shape:o,dtype:s.dtype}}const EA={kernelName:br,backendName:"cpu",kernelFunc:TA};function CA(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;BE([s,a],"matMul");const u=s.shape.length,l=a.shape.length,c=i?s.shape[u-2]:s.shape[u-1],h=o?a.shape[l-1]:a.shape[l-2],d=i?s.shape[u-1]:s.shape[u-2],p=o?a.shape[l-2]:a.shape[l-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=le(f),y=le(m),b=ru(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,p]);ie(c===h,()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`);const x=o?[y,p,h]:[y,h,p],w=TA({inputs:{x:s},backend:n,attrs:{shape:i?[g,c,d]:[g,d,c]}}),v=TA({inputs:{x:a},backend:n,attrs:{shape:x}}),k=i?w.shape[1]:w.shape[2],I=i?w.shape[2]:w.shape[1],S=o?v.shape[1]:v.shape[2],N=Math.max(g,y),T=n.data.get(w.dataId).values,E=n.data.get(v.dataId).values,C=De(w.shape),$=De(v.shape),[A,R,_]=i?[C[0],1,C[1]]:[C[0],C[1],1],[M,F,D]=o?[1,$[1],$[0]]:[$[1],1,$[0]],O=I*S,L=ko([N,I,S],w.dtype),z=L.values,P=n.blockSize;for(let e=0;e<N;e++){const t=e%g,n=e%y;for(let r=0;r<I;r+=P){const s=Math.min(r+P,I);for(let a=0;a<S;a+=P){const i=Math.min(a+P,S);for(let o=0;o<k;o+=P){const u=Math.min(o+P,k);for(let l=r;l<s;l++)for(let r=a;r<i;r++){let s=0;for(let e=o;e<u;e++)s+=T[t*A+l*R+e*_]*E[e*M+r*F+n*D];z[e*O+(l*S+r)]+=s}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}const $A={kernelName:bt,backendName:"cpu",kernelFunc:CA},AA={kernelName:gs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:h}=r;let d,p,f;const m=[];d=CA({inputs:{a:s,b:a},attrs:{transposeA:u,transposeB:l},backend:n}),i&&(p=iC({inputs:{a:d,b:i},backend:n}),m.push(d),d=p),c&&(f=NA(n,d,c,o,h),m.push(d),d=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return d}},RA=fC(tt,e=>Math.acos(e)),_A={kernelName:tt,backendName:"cpu",kernelFunc:RA},MA=fC(nt,e=>Math.acosh(e)),FA={kernelName:nt,backendName:"cpu",kernelFunc:MA},DA={kernelName:st,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;BE(t,"addN");const s=r.map(e=>n.data.get(e.dataId).values),a=ko(r[0].shape,r[0].dtype),i=a.values;for(let e=0;e<r.length;e++){const t=s[e];for(let e=0;e<i.length;e++)i[e]+=t[e]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}},OA={kernelName:at,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;BE(s,"all");const o=we(a,s.shape);let u=o;const l=nh(u,s.shape.length);let c=s;null!=l&&(c=g$({inputs:{x:s},backend:n,attrs:{perm:l}}),u=sh(u.length,s.shape.length)),th("all",u,c.shape.length);const[h,d]=Qc(c.shape,u),p=le(d),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const r=m[t+e];n=n&&r}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=TA({inputs:{x:g},backend:n,attrs:{shape:eh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},LA={kernelName:it,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;BE(s,"any");const o=we(a,s.shape);let u=o;const l=nh(u,s.shape.length);let c=s;null!=l&&(c=g$({inputs:{x:s},backend:n,attrs:{perm:l}}),u=sh(u.length,s.shape.length)),th("any",u,c.shape.length);const[h,d]=Qc(c.shape,u),p=le(d),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const r=m[t+e];n=n||r}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=TA({inputs:{x:g},backend:n,attrs:{shape:eh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},zA={kernelName:ot,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;BE(s,"argMax");let i=we(a,s.shape);const o=nh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=g$({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=sh(i.length,u.shape.length)),i=[i[0]],th("argMax",i,u.shape.length);const[c,h]=Qc(u.shape,i),d=Be(le(c),"int32"),p=le(h),f=n.data.get(u.dataId).values;for(let e=0;e<d.length;++e){const t=e*p;let n=f[t],r=0;for(let e=0;e<p;++e){const s=f[t+e];s>n&&(n=s,r=e)}d[e]=r}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(c,"int32",d)}},PA={kernelName:ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;BE(s,"argMin");let i=we(a,s.shape);const o=nh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=g$({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=sh(i.length,u.shape.length)),i=[i[0]],th("argMin",i,u.shape.length);const[c,h]=Qc(u.shape,i),d=Be(le(c),"int32"),p=le(h),f=n.data.get(u.dataId).values;for(let e=0;e<d.length;++e){const t=e*p;let n=f[t],r=0;for(let e=0;e<p;++e){const s=f[t+e];s<n&&(n=s,r=e)}d[e]=r}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(c,"int32",d)}},BA=fC(lt,e=>Math.asin(e)),VA={kernelName:lt,backendName:"cpu",kernelFunc:BA},UA=fC(ct,e=>Math.asinh(e)),WA={kernelName:ct,backendName:"cpu",kernelFunc:UA},GA=fC(ht,e=>Math.atan(e)),HA={kernelName:ht,backendName:"cpu",kernelFunc:GA},jA=HE((e,t)=>Math.atan2(e,t)),qA=nC(pt,jA),KA={kernelName:pt,backendName:"cpu",kernelFunc:qA},XA=fC(dt,e=>Math.atanh(e)),YA={kernelName:dt,backendName:"cpu",kernelFunc:XA};function JA(e,t,n,r,s,a){const i=s.strideHeight,o=s.strideWidth,u=s.dilationHeight,l=s.dilationWidth,c=s.effectiveFilterHeight,h=s.effectiveFilterWidth,d=s.padInfo.top,p=s.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=ko(s.outShape,n),g=m.values,y=s.outShape[1]*s.outShape[2]*s.outShape[3],b=s.outShape[2]*s.outShape[3],x=s.outShape[3];for(let t=0;t<s.batchSize;++t){const n=t*y,m=t*r[0];for(let t=0;t<s.inChannels;++t)for(let y=0;y<s.outHeight;++y){const w=y*i-d,v=Math.max(0,w),k=Math.min(s.inHeight,c+w),I=n+y*b;for(let n=0;n<s.outWidth;++n){const i=n*o-p,c=Math.max(0,i),d=Math.min(s.inWidth,h+i);let y=f,b=0,w=0;for(let n=v;n<k;n+=u){const s=m+n*r[1];for(let n=c;n<d;n+=l){const i=e[s+n*r[2]+t];"max"===a&&i>y?y=i:"avg"===a&&(b+=i,w++)}if(isNaN(y))break}g[I+n*x+t]="avg"===a?b/w:y}}}return m}function ZA(e,t,n,r,s=!1,a=!1){const i=ko(r.outShape,"int32"),o=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=r.padInfo.top,f=r.padInfo.left,m=ko(t,n,e);for(let e=0;e<r.batchSize;++e)for(let t=0;t<r.inChannels;++t)for(let n=0;n<r.outHeight;++n){const g=n*o-p;let y=g;for(;y<0;)y+=l;const b=Math.min(r.inHeight,h+g);for(let o=0;o<r.outWidth;++o){const h=o*u-f;let p=h;for(;p<0;)p+=c;const x=Math.min(r.inWidth,d+h);let w=Number.NEGATIVE_INFINITY,v=-1;for(let n=y;n<b;n+=l){const i=n-g;for(let o=p;o<x;o+=c){const u=o-h,l=m.get(e,n,o,t);l>w&&(w=l,v=s?a?((e*r.inHeight+n)*r.inWidth+o)*r.inChannels+t:(n*r.inWidth+o)*r.inChannels+t:i*d+u)}}i.set(v,e,n,o,t)}}return i}function QA(e,t,n,r,s,a){const i=s.strideDepth,o=s.strideHeight,u=s.strideWidth,l=s.dilationDepth,c=s.dilationHeight,h=s.dilationWidth,d=s.effectiveFilterDepth,p=s.effectiveFilterHeight,f=s.effectiveFilterWidth,m=s.padInfo.front,g=s.padInfo.top,y=s.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=ko(s.outShape,n),w=x.values,v=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],k=s.outShape[2]*s.outShape[3]*s.outShape[4],I=s.outShape[3]*s.outShape[4],S=s.outShape[4];for(let t=0;t<s.batchSize;++t){const n=t*v,x=t*r[0];for(let t=0;t<s.inChannels;++t)for(let v=0;v<s.outDepth;++v){const N=v*i-m;let T=N;for(;T<0;)T+=l;const E=Math.min(s.inDepth,d+N),C=n+v*k;for(let n=0;n<s.outHeight;++n){const i=n*o-g;let d=i;for(;d<0;)d+=c;const m=Math.min(s.inHeight,p+i),v=C+n*I;for(let n=0;n<s.outWidth;++n){const i=n*u-y;let o=i;for(;o<0;)o+=h;const p=Math.min(s.inWidth,f+i),g=v+n*S;let k=b,I=0,N=0;for(let n=T;n<E;n+=l){const s=x+n*r[1];for(let n=d;n<m;n+=c){const i=s+n*r[2];for(let n=o;n<p;n+=h){const s=e[i+n*r[3]+t];if("max"===a&&s>k?k=s:"avg"===a&&(I+=s,N++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?I/Math.max(N,1):k}}}}return x}const eR={kernelName:ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;BE(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(ec(i,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations \'1\'`);const l=Gl(s.shape,a,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&de(l.inShape,l.outShape))c=XE({input
5057s:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=De(s.shape),r=JA(e,s.shape,s.dtype,t,l,"avg");c=n.makeTensorInfo(l.outShape,s.dtype,r.values)}return c}},tR={kernelName:gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;BE(s,"avgPool3d");const c=Hl(s.shape,a,i,1,o,u,l),h=QA(n.data.get(s.dataId).values,s.shape,s.dtype,De(s.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}},nR={kernelName:yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;BE([s,a],"avgPool3DGrad");const c=Hl(a.shape,i,o,1,u,l),h=c.strideDepth,d=c.strideHeight,p=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,I=w-1-c.padInfo.front,S=k-1-c.padInfo.left,N=v-1-c.padInfo.top,T=ko(a.shape,"float32"),E=1/(f*m*g),C=n.bufferSync(s);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let s=0;s<c.inWidth;++s){const a=n-I,i=r-N,o=s-S;let u=0;for(let n=0;n<w;n+=y){const r=(a+n)/h;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let n=0;n<v;n+=b){const s=(i+n)/d;if(!(s<0||s>=c.outHeight||Math.floor(s)!==s))for(let n=0;n<k;n+=x){const a=(o+n)/p;a<0||a>=c.outWidth||Math.floor(a)!==a||(u+=C.get(e,r,s,a,t))}}}T.set(u*E,e,n,r,s,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}},rR={kernelName:mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;BE([s,a],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=Gl(i.shape,o,u,1,l),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,v=ko(i.shape,"float32"),k=1/(p*f),I=n.data.get(s.dataId).values,S=ko(s.shape,"float32",I);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inHeight;++n)for(let r=0;r<c.inWidth;++r){const s=n-w,a=r-x;let i=0;for(let n=0;n<y;n+=m){const r=(s+n)/h;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let n=0;n<b;n+=g){const s=(a+n)/d;s<0||s>=c.outWidth||Math.floor(s)!==s||(i+=S.get(e,r,s,t))}}v.set(i*k,e,n,r,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}},sR={kernelName:dn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,scale:a,offset:i,mean:o,variance:u}=t;ie(o.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),ie(null==i||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),ie(null==a||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),BE([s,o,u,a,i],"batchNorm");let{varianceEpsilon:l}=r;null==l&&(l=.001);const c=n.data.get(s.dataId).values,h=n.data.get(o.dataId).values,d=n.data.get(u.dataId).values,p=a?n.data.get(a.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=p.length,b=d.length,x=h.length;let w=0,v=0,k=0,I=0;for(let e=0;e<c.length;++e)m[e]=f[w++]+(c[e]-h[v++])*p[k++]/Math.sqrt(d[I++]+l),w>=g&&(w=0),v>=x&&(v=0),k>=y&&(k=0),I>=b&&(I=0);return n.makeTensorInfo(s.shape,s.dtype,m)}},aR={kernelName:xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;BE([s],"batchToSpaceND");const o=a.reduce((e,t)=>e*t),u=Qf(s.shape,a,o),l=em(u.length,a.length),c=tm(s.shape,a,o),h=nm(i,a.length),d=rm(c,i,a.length),p=TA({inputs:{x:s},backend:n,attrs:{shape:u}}),f=g$({inputs:{x:p},backend:n,attrs:{perm:l}}),m=TA({inputs:{x:f},backend:n,attrs:{shape:c}}),g=z$({inputs:{x:m},backend:n,attrs:{begin:h,size:d}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},iR={kernelName:wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=uC(n.data.get(s.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}},oR={kernelName:It,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=ru(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},uR=fC(Tt,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),lR={kernelName:Tt,backendName:"cpu",kernelFunc:uR},cR={kernelName:Ct,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(le(t.shape)),s=n.data.get(t.dataId),a=s.complexTensorInfos.real,i=s.complexTensorInfos.imag,o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values;for(let e=0;e<o.length;e++){const t=o[e],n=u[e];r[e]=Math.hypot(t,n)}return n.makeOutput(r,t.shape,"float32")}};function hR(e){const{inputs:t,backend:n}
5057=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.imag,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}const dR={kernelName:xn,backendName:"cpu",kernelFunc:hR};function pR(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=we(s,t[0].shape)[0];Wf(t.map(e=>e.shape),a);let i=Gf(t.map(e=>e.shape),a);if(0===le(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter(e=>le(e.shape)>0);if(1===o.length)return XE({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map(e=>JE({inputs:{input:e},backend:n})),t=o.map(e=>hR({inputs:{input:e},backend:n})),r=pR({inputs:e,backend:n,attrs:{axis:a}}),s=pR({inputs:t,backend:n,attrs:{axis:a}}),i=jE({inputs:{real:r,imag:s},backend:n});return e.forEach(e=>n.disposeIntermediateTensorInfo(e)),t.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),i}const u=o.map(e=>{const t=le(e.shape.slice(a));return TA({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})}),l=u.map(e=>({vals:n.data.get(e.dataId).values,shape:e.shape}));i=Gf(u.map(e=>e.shape),1);const c=1===u[0].shape[0],h=xC(l,i,t[0].dtype,c),d=Gf(o.map(e=>e.shape),a),p=n.makeTensorInfo(d,t[0].dtype,h);return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),p}const fR={kernelName:$t,backendName:"cpu",kernelFunc:pR};function mR(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r;BE([s,a],"conv2d");const h=nc(u),d=jl(s.shape,a.shape,i,l,o,c,!1,h),p=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,b=d.padInfo.top,x="channelsLast"===d.dataFormat,w=new la(d.outShape,s.dtype),v=De(s.shape),k=De(a.shape),I=v[0],S=x?v[1]:v[2],N=x?v[2]:1,T=x?1:v[1],E=w.strides[0],C=x?w.strides[1]:w.strides[2],$=x?w.strides[2]:1,A=x?1:w.strides[1],R=n.data.get(s.dataId).values,_=n.data.get(a.dataId).values,M=w.values;for(let e=0;e<d.batchSize;++e){const t=e*I,n=e*E;for(let e=0;e<d.outHeight;++e){const r=n+e*C,s=e*d.strideHeight-b;for(let e=0;e<p;++e){const n=s+e*m;if(n<0||n>=d.inHeight)continue;const a=e*k[0],i=t+n*S;for(let e=0;e<d.outWidth;++e){const t=r+e*$,n=e*d.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=d.inWidth)continue;const s=i+r*N;let o=a+e*k[1];for(let e=0;e<d.inChannels;++e){const n=R[s+e*T];for(let e=0;e<d.outChannels;++e)M[t+e*A]+=n*_[o+e];o+=d.outChannels}}}}}}return n.makeTensorInfo(w.shape,w.dtype,M)}const gR={kernelName:At,backendName:"cpu",kernelFunc:mR},yR={kernelName:Rt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r;BE([s,a],"conv2dBackpropFilter");const h=nc(u),d=jl(s.shape,c,i,1,o,l,!1,h),{strideHeight:p,strideWidth:f,filterHeight:m,filterWidth:g}=d,y="channelsLast"===d.dataFormat,b=new la(d.filterShape,"float32"),x=d.padInfo.left,w=d.padInfo.top,v=n.data.get(s.dataId).values,k=n.data.get(a.dataId).values,I=new la(s.shape,s.dtype,v),S=new la(a.shape,a.dtype,k);for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((w-e)/p)),n=Math.min(d.outHeight,(d.inHeight+w-e)/p);for(let r=0;r<g;++r){const s=Math.max(0,Math.ceil((x-r)/f)),a=Math.min(d.outWidth,(d.inWidth+x-r)/f);for(let i=0;i<d.inChannels;++i)for(let o=0;o<d.outChannels;++o){let u=0;for(let l=0;l<d.batchSize;++l)for(let c=t;c<n;++c){const t=e+c*p-w;for(let e=s;e<a;++e){const n=r+e*f-x;u+=y?I.get(l,t,n,i)*S.get(l,c,e,o):I.get(l,i,t,n)*S.get(l,o,c,e)}}b.set(u,e,r,i,o)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}},bR={kernelName:_t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r;BE([s,a],"conv2dBackpropInput");const h=De(a.shape),d=De(s.shape);let p=nc(l);const f=jl(i,a.shape,o,1,u,c,!1,p),m=new la(f.inShape,"float32"),g=m.values,y=n.data.get(s.dataId).values,b=n.data.get(a.dataId).values,[x,w,v]=h,{batchSize:k,filterHeight:I,filterWidth:S,inChannels:N,inHeight:T,inWidth:E,outChannels:C,outHeight:$,outWidth:A,strideHeight:R,strideWidth:_}=f;p=f.dataFormat;const M=I-1-f.padInfo.top,F=S-1-f.padInfo.left,D="channelsLast"===p,O=m.strides[0],L=D?m.strides[1]:m.strides[2],z=D?m.strides[2]:1,P=D?1:m.strides[1],B=d[0],V=D?d[1]:d[2],U=D?d[2]:1,W=D?1:d[1];for(let e=0;e<k;++e)for(let t=0;t<N;++t)for(let n=0;n<T;++n){const r=n-M,s=Math.max(0,Math.ceil(r/R)),a=Math.min($,(I+r)/R);for(let i=0;i<E;++i){const o=i-F,u=Math.max(0,Math.ceil(o/_)),l=Math.min(A,(S+o)/_);let c=0;for(let n=s;n<a;++n){const s=n*R-r;for(let r=u;r<l;++r){const a=B*e+V*n+U*r,i=x*(I-1-s)+w*(S-1-(r*_-o))+v*t;for(let e=0;e<C;++e)c+=y[a+W*e]*b[i+e]}}g[O*e+L*n+z*i+P*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}},xR={kernelName:Mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r;BE([s,a],"conv3d");const l=ql(s.shape,a.shape,i,u,o),{filterDepth:c,filterHeight:h,filterWidth:d,dilationDepth:p,dilationHeight:f,dilationWidth:m,padInfo:g}=l,y=g.front,b=g.left,x=g.top,w=new la(l.outShape,s.dtype),v=n.data.get(s.dataId).values,k=n.data.get(a.dataId).values,I=w.values,S=De(s.shape),N=De(a.shape);for(let e=0;e<l.batchSize;++e){const t=e*S[0],n=e*w.strides[0];for(let e=0;e<l.outDepth;++e){const r=n+e*w.strides[1],s=e*l.strideDepth-y;for(let e=0;e<c;++e){const n=s+e*p;if(n<0||n>=l.inDepth)continue;const a=e*N[0],i=t+n*S[1];for(let e=0;e<l.outHeight;++e){const t=r+e*w.strides[2],n=e*l.strideHeight-x;for(let e=0;e<h;++e){const r=n+e*f;if(r<0||r>=l.inHeight)continue;const s=a+e*N[1],o=i+r*S[2];for(let e=0;e<l.outWidth;++e){const n=t+e*l.outChannels,r=e*l.strideWidth-b;
vendor: 16,328 bytes, line 5057
5057for(let e=0;e<d;++e){const t=r+e*m;if(t<0||t>=l.inWidth)continue;const a=s+e*N[2],i=o+t*l.inChannels;let u=a;for(let e=0;e<l.inChannels;++e){const t=v[i+e];for(let e=0;e<l.outChannels;++e)I[n+e]+=t*k[u+e];u+=l.outChannels}}}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}},wR={kernelName:Ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,filterShape:u}=r;BE([s,a],"conv3dBackpropFilterV2");const l=De(s.shape),c=De(a.shape),h=ql(s.shape,u,i,1,o),d=h.strideDepth,p=h.strideHeight,f=h.strideWidth,m=h.filterDepth,g=h.filterHeight,y=h.filterWidth,b=new la(h.filterShape,"float32"),x=b.values,[w,v,k,I]=b.strides,S=n.data.get(a.dataId).values,[N,T,E,C]=c,$=n.data.get(s.dataId).values,[A,R,_,M]=l,F=h.padInfo.front,D=h.padInfo.left,O=h.padInfo.top;for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((F-e)/d)),n=Math.min(h.outDepth,(h.inDepth+F-e)/d),r=e*w;for(let s=0;s<g;++s){const a=Math.max(0,Math.ceil((O-s)/p)),i=Math.min(h.outHeight,(h.inHeight+O-s)/p),o=s*v+r;for(let r=0;r<y;++r){const u=Math.max(0,Math.ceil((D-r)/f)),l=Math.min(h.outWidth,(h.inWidth+D-r)/f),c=r*k+o;for(let o=0;o<h.inChannels;++o){const m=o*I+c;for(let c=0;c<h.outChannels;++c){let g=0;for(let m=0;m<h.batchSize;++m){const h=m*A,y=m*N;for(let m=t;m<n;++m){const t=(e+m*d-F)*R+h,n=m*T+y;for(let e=a;e<i;++e){const a=(s+e*p-O)*_+t,i=e*E+n;for(let e=u;e<l;++e){const t=e*C+i;g+=$[(r+e*f-D)*M+a+o]*S[t+c]}}}}x[m+c]=g}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}},vR={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:i,strides:o,inputShape:u}=r;BE([s],"conv3dBackpropInputV2");const l=De(s.shape),c=De(a.shape),h=ql(u,a.shape,o,1,i),d=new la(h.inShape,"float32"),p=d.values,[f,m,g,y]=d.strides,b=n.data.get(s.dataId).values,[x,w,v,k]=l,I=n.data.get(a.dataId).values,[S,N,T,E]=c,{batchSize:C,filterDepth:$,filterHeight:A,filterWidth:R,inChannels:_,inDepth:M,inHeight:F,inWidth:D,outChannels:O,outDepth:L,outHeight:z,outWidth:P,strideDepth:B,strideHeight:V,strideWidth:U}=h,W=$-1-h.padInfo.front,G=A-1-h.padInfo.top,H=R-1-h.padInfo.left;for(let e=0;e<C;++e)for(let t=0;t<_;++t)for(let n=0;n<M;++n){const r=n-W,s=Math.max(0,Math.ceil(r/B)),a=Math.min(L,($+r)/B);for(let i=0;i<F;++i){const o=i-G,u=Math.max(0,Math.ceil(o/V)),l=Math.min(z,(A+o)/V);for(let c=0;c<D;++c){const h=c-H,d=Math.max(0,Math.ceil(h/U)),C=Math.min(P,(R+h)/U);let _=0;for(let n=s;n<a;++n){const s=n*B-r;for(let r=u;r<l;++r){const a=r*V-o;for(let i=d;i<C;++i){const o=x*e+w*n+v*r+k*i,u=S*($-1-s)+N*(A-1-a)+T*(R-1-(i*U-h))+E*t;for(let e=0;e<O;++e)_+=b[o+e]*I[u+e]}}}p[f*e+m*n+g*i+y*c+t]=_}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}},kR=fC(Ot,e=>Math.cos(e)),IR={kernelName:Ot,backendName:"cpu",kernelFunc:kR},SR=fC(Lt,e=>Math.cosh(e)),NR={kernelName:Lt,backendName:"cpu",kernelFunc:SR},TR={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,[c,h,d,p]=s.shape,f=a.shape[0],[m,g]=o,y=ko([f,m,g,p],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(s.dataId).values,v=De(s.shape),k=De(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],r=b[t+1],s=b[t+2],a=b[t+3],i=x[e];if(i>=c)continue;const o=m>1?(s-n)*(h-1)/(m-1):0,f=g>1?(a-r)*(d-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(h-1)+t*o:.5*(n+s)*(h-1);if(c<0||c>h-1)for(let n=0;n<g;n++)for(let r=0;r<p;r++){const s=r+n*k[2]+t*k[1]+e*k[0];y.values[s]=l}else if("bilinear"===u){const n=Math.floor(c),s=Math.ceil(c),o=c-n;for(let u=0;u<g;u++){const c=g>1?r*(d-1)+u*f:.5*(r+a)*(d-1);if(c<0||c>d-1){for(let n=0;n<p;n++){const r=n+u*k[2]+t*k[1]+e*k[0];y.values[r]=l}continue}const h=Math.floor(c),m=Math.ceil(c),b=c-h;for(let r=0;r<p;r++){let a=r+h*v[2]+n*v[1]+i*v[0];const l=w[a];a=r+m*v[2]+n*v[1]+i*v[0];const c=w[a];a=r+h*v[2]+s*v[1]+i*v[0];const d=w[a];a=r+m*v[2]+s*v[1]+i*v[0];const p=l+(c-l)*b,f=d+(w[a]-d)*b;a=r+u*k[2]+t*k[1]+e*k[0],y.values[a]=p+(f-p)*o}}}else for(let n=0;n<g;++n){const s=g>1?r*(d-1)+n*f:.5*(r+a)*(d-1);if(s<0||s>d-1){for(let r=0;r<p;r++){const s=r+n*k[2]+t*k[1]+e*k[0];y.values[s]=l}continue}const o=Math.round(s),u=Math.round(c);for(let r=0;r<p;r++){const s=r+o*v[2]+u*v[1]+i*v[0],a=r+n*k[2]+t*k[1]+e*k[0];y.values[a]=w[s]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}},ER={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;BE(s,"cumprod");const u=nh([a],s.shape.length);let l=s;null!=u&&(l=g$({inputs:{x:s},backend:n,attrs:{perm:u}}));const c=sh(1,s.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const h=ka(l.dtype,"int32"),d=Pe(le(l.shape),h),p=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<p.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)d[n]=i?1:p[n];else{const r=m(e,t-1);d[n]=i?p[r]*d[r]:p[n]*d[r]}}const g=n.makeTensorInfo(l.shape,h,d);if(null!=u){const e=g$({inputs:{x:g},backend:n,attrs:{perm:rh(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}},CR={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;BE(s,"cumsum");const u=nh([a],s.shape.length);let l=s;null!=u&&(l=g$({inputs:{x:s},backend:n,attrs:{perm:u}}));const c=sh(1,s.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const h=ka(l.dtype,"int32"),d=Be(le(l.shape),h),p=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<p.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)d[n]=i?0:p[n];else{const r=m(e,t-1);d[n]=i?p[r]+d[r]:p[n]+d[r]}}const g=n.makeTensorInfo(l.shape,h,d);if(null!=u){const e=g$({inputs:{x:g},backend:n,attrs:{perm:rh(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}},$R={kernelName:Vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i,binaryOutput:o}=r;if(1===s.shape.length){const e=uC(n.data.get(s.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,e)}if(2===s.shape.length){const e=lC(n.bufferSync(s),n.bufferSync(a),i,o);return n.makeTensorInfo(e.shape,a.dtype,e.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}},AR={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:i}=r;ie("NHWC"===i,()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);const o=s.shape[0],u=s.shape[1],l=s.shape[2],c=s.shape[3],h=u*a,d=l*a,p=c/(a*a),f=n.data.get(s.dataId).values,m=new Float32Array(o*h*d*p);let g=0;for(let e=0;e<o;++e)for(let t=0;t<h;++t){const n=Math.floor(t/a),r=t%a;for(let t=0;t<d;++t){const s=Math.floor(t/a),i=(r*a+t%a)*p;for(let t=0;t<p;++t){const r=t+i+c*(s+l*(n+u*e));m[g++]=f[r]}}}return n.makeTensorInfo([o,h,d,p],s.dtype,m)}};function RR(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;BE([s,a],"depthwiseConv2DNative");const c=De(s.shape),h=De(a.shape);let d=u;null==d&&(d=[1,1]),ie(ec(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations \'${d}\'`);const p=jl(s.shape,a.shape,i,d,o,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=p,x=b.left,w=b.top,v=p.outChannels/p.inChannels,k=new la(p.outShape,s.dtype),I=n.data.get(s.dataId).values,S=n.data.get(a.dataId).values,N=k.values;for(let e=0;e<p.batchSize;++e){const t=e*c[0],n=e*k.strides[0];for(let e=0;e<p.outHeight;++e){const r=n+e*k.strides[1],s=e*p.strideHeight-w;for(let e=0;e<f;++e){const n=s+e*g;if(n<0||n>=p.inHeight)continue;const a=e*h[0],i=t+n*c[1];for(let e=0;e<p.outWidth;++e){const t=r+e*k.strides[2],n=e*p.strideWidth-x;for(let e=0;e<m;++e){const r=n+e*y;if(r<0||r>=p.inWidth)continue;const s=a+e*h[1],o=i+r*p.inChannels;let u=t,l=s;for(let e=0;e<p.inChannels;++e){const t=I[o+e];for(let e=0;e<v;++e)N[u+e]+=t*S[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const _R={kernelName:Wt,backendName:"cpu",kernelFunc:RR},MR={kernelName:Gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r;BE([s,a],"depthwiseConv2dNativeBackpropFilter");const h=jl(s.shape,c,i,o,u,l,!0),{strideHeight:d,strideWidth:p,filterHeight:f,filterWidth:m}=h,g=new la(h.filterShape,"float32"),y=h.padInfo.left,b=h.padInfo.top,x=h.outChannels/h.inChannels,w=n.data.get(s.dataId).values,v=new la(s.shape,s.dtype,w),k=n.data.get(a.dataId).values,I=new la(a.shape,a.dtype,k);for(let e=0;e<f;++e){const t=Math.max(0,Math.ceil((b-e)/d)),n=Math.min(h.outHeight,(h.inHeight+b-e)/d);for(let r=0;r<m;++r){const s=Math.max(0,Math.ceil((y-r)/p)),a=Math.min(h.outWidth,(h.inWidth+y-r)/p);for(let i=0;i<h.outChannels;++i){const o=Math.trunc(i/x),u=i%x;let l=0;for(let u=0;u<h.batchSize;++u)for(let c=t;c<n;++c){const t=e+c*d-b;for(let e=s;e<a;++e){const n=r+e*p-y;l+=v.get(u,t,n,o)*I.get(u,c,e,i)}}g.set(l,e,r,o,u)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}},FR={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r;BE([s,a],"depthwiseConv2DNativeBackpropInput");const h=De(s.shape),d=De(a.shape),p=jl(c,a.shape,i,o,u,l,!0),f=new la(p.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(s.dataId).values,[w,v,k]=h,I=n.data.get(a.dataId).values,[S,N,T]=d,{batchSize:E,filterHeight:C,filterWidth:$,inChannels:A,inHeight:R,inWidth:_,outChannels:M,outHeight:F,outWidth:D,strideHeight:O,strideWidth:L}=p,z=C-1-p.padInfo.top,P=$-1-p.padInfo.left,B=M/A;for(let e=0;e<E;++e)for(let t=0;t<A;++t)for(let n=0;n<R;++n){const r=n-z,s=Math.max(0,Math.ceil(r/O)),a=Math.min(F,(C+r)/O);for(let i=0;i<_;++i){const o=i-P,u=Math.max(0,Math.ceil(o/L)),l=Math.min(D,($+o)/L);let c=0;for(let n=s;n<a;++n){const s=n*O-r;for(let r=u;r<l;++r){const a=w*e+v*n+k*r,i=S*(C-1-s)+N*($-1-(r*L-o))+T*t;for(let e=0;e<B;++e)c+=x[a+(t*B+e)]*I[i+e]}}m[g*e+y*n+b*i+t]=c}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}},DR={kernelName:jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=le(r.shape),a=n.data.get(r.dataId).values,i=ko([s,s],r.dtype),o=i.values;for(let e=0;e<a.length;e++)o[e*s+e]=a[e];const u=[...r.shape,...r.shape];return n.makeTensorInfo(u,i.dtype,i.values)}},OR={kernelName:qt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s}=e,{strides:a,pad:i,dilations:o}=n,u=t,l=u.data.get(r.dataId).values,c=r.shape.length,h=u.data.get(s.dataId).values,d=s.shape.length,{batchSize:p,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:I,dilationHeight:S,dilationWidth:N,outShape:T}=Wl(r.shape,s.shape,a,i,"NHWC",o),E=le(T),C=T.length,$=Ie(r.dtype,E);for(let e=0;e<p;++e)for(let t=0;t<y;++t){const n=t*w-x.top;for(let a=0;a<b;++a){const i=a*v-x.left;for(let o=0;o<g;++o){let u=Number.MIN_SAFE_INTEGER;for(let t=0;t<k;++t){const a=n+t*S;if(a>=0&&a<f)for(let n=0;n<I;++n){const p=i+n*N;if(p>=0&&p<m){const i=We([e,a,p,o],c,De(r.shape)),f=We([t,n,o],d,De(s.shape)),m=l[i]+h[f];m>u&&(u=m)}}}$[We([e,t,a,o],C,De(T))]=u}}}return{dataId:u.write(Ks($,r.dtype),T,r.dtype),shape:T,dtype:r.dtype}}},LR={kernelName:Xt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=Le(r.shape,l.data.get(r.dataId).values),h=Le(s.shape,l.data.get(s.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:S,outShape:N}=Wl(r.shape,s.shape,i,o,"NHWC",u);ie(a.rank===N.length,()=>`Error in ${Xt}, dy must have the same rank as output ${N.length}, but got ${a.rank}`);const T=Le(N,l.data.get(a.dataId).values),E=Ve(s.shape,s.dtype);for(let e=0;e<d;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let r=0;r<y;++r){const s=r*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=0,u=0;for(let t=0;t<v;++t){const r=n+t*I;if(r>=0&&r<p)for(let n=0;n<k;++n){const l=s+n*S;if(l>=0&&l<f){const s=c[e][r][l][a]+h[t][n][a];s>i&&(i=s,o=t,u=n)}}}E[o][u][a]+=T[e][t][r][a]}}}return{dataId:l.write(Ks(E,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},zR={kernelName:Kt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=Le(r.shape,l.data.get(r.dataId).values),h=Le(s.shape,l.data.get(s.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:S,outShape:N}=Wl(r.shape,s.shape,i,o,"NHWC",u);ie(a.rank===N.length,()=>`Error in ${Kt}, dy must have the same rank as output ${N.length}, but got ${a.rank}`);const T=Le(N,l.data.get(a.dataId).values),E=Ve(r.shape,r.dtype);for(let e=0;e<d;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let r=0;r<y;++r){const s=r*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=n<0?0:n,u=s<0?0:s;for(let t=0;t<v;++t){const r=n+t*I;if(r>=0&&r<p)for(let n=0;n<k;++n){const l=s+n*S;if(l>=0&&l<f){const s=c[e][r][l][a]+h[t][n][a];s>i&&(i=s,o=r,u=l)}}}E[e][o][u][a]+=T[e][t][r][a]}}}return{dataId:l.write(Ks(E,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},PR={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s}=t,{canvas:a,options:i}=r,{contextOptions:o,imageOptions:u}=i||{},l=(null==u?void 0:u.alpha)||1,c=(null==o?void 0:o.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=a.getContext(c,(null==o?void 0:o.contextAttributes)||{});if(null==h)throw new Error(`Could not get the context with ${c} type.`);const[d,p]=s.shape.slice(0,2),f=2===s.shape.length?1:s.shape[2],m=n.data.get(s.dataId).values,g="float32"===s.dtype?255:1,y=new Uint8ClampedArray(p*d*4);for(let e=0;e<d*p;++e){const t=[0,0,0,255*l];for(let n=0;n<f;n++){const r=m[e*f+n];if("float32"===s.dtype){if(r<0||r>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${r}.`)}else if("int32"===s.dtype&&(r<0||r>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${r}.`);1===f?(t[0]=r*g,t[1]=r*g,t[2]=r*g):t[n]=r*g}const n=4*e;y[n+0]=Math.round(t[0]),y[n+1]=Math.round(t[1]),y[n+2]=Math.round(t[2]),y[n+3]=Math.round(t[3])}a.width=p,a.height=d;const b=new ImageData(y,p,d);return h.putImageData(b,0,0),s}};function BR(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;let o;BE(s,"sum"),o="bool"===s.dtype?eC({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):XE({inputs:{x:s},backend:n});const u=o.shape.length,l=we(a,o.shape),c=nh(l,u);let h=l,d=o;null!=c&&(d=g$({inputs:{x:o},backend:n,attrs:{perm:c}}),h=sh(h.length,u)),th("sum",h,d.shape.length);const[p,f]=Qc(d.shape,h);let m=KE(n,p,ka(d.dtype,"int32"));const g=le(f),y=n.data.get(m.dataId).values,b=n.data.get(d.dataId).values;for(let e=0;e<y.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=b[t+e];y[e]=n}if(i){const e=m;m=TA({inputs:{x:m},backend:n,attrs:{shape:eh(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(d),m}const VR={kernelName:Pr,backendName:"cpu",kernelFunc:BR},UR={kernelName:Zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:i,summedDims:o,idDims:u}=Sm(s,a.length);Tm(i.length,u,a);const{path:l,steps:c}=Em(o,u),h=c.length;let d=null,p=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:r}=Nm(p,u[t]);let s;Cm(e)?s=a[t]:(s=g$({inputs:{x:a[t]},backend:n,attrs:{perm:e}}
5057),f.push(s));const i=s.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);de(s.shape,i)||(s=TA({inputs:{x:s},backend:n,attrs:{shape:i}}),f.push(s)),null===d?d=s:(d=u$({inputs:{a:s,b:d},backend:n}),f.push(d))}e<h-1&&(l[e]>=0&&(d=BR({inputs:{x:d},backend:n,attrs:{axis:l[e]-(i.length-p),keepDims:!1}}),f.push(d)),p--)}for(const e of f)e!==d&&n.disposeIntermediateTensorInfo(e);return d}},WR={kernelName:en,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:s}=t;BE([r,s],"eluGrad");const a=new Float32Array(le(s.shape)),i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values;for(let e=0;e<i.length;++e){const t=i[e];a[e]=t>=0?o[e]:o[e]*(t+1)}return n.makeTensorInfo(s.shape,"float32",a)}},GR=im,HR=om,jR=um,qR=lm,KR=cm,XR=hm,YR=fC(tn,e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+GR*n);return t*(1-((((XR*r+KR)*r+qR)*r+jR)*r+HR)*r*Math.exp(-n*n))}),JR={kernelName:tn,backendName:"cpu",kernelFunc:YR};function ZR(e){const{inputs:t,backend:n,attrs:r}=e,{input:s}=t,{dim:a}=r,i=s.shape.length,o=s.shape.slice();let u=a;return a<0&&(ie(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+a+1),o.splice(u,0,1),TA({inputs:{x:s},backend:n,attrs:{shape:o}})}const QR={kernelName:sn,backendName:"cpu",kernelFunc:ZR},e_=HE((e,t)=>e/t),t_=nC(Jt,e_),n_={kernelName:Jt,backendName:"cpu",kernelFunc:t_};function r_(e,t,n){const r=e.shape,s=r[0],a=r[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,u=i.complexTensorInfos.imag,l=[s,a],c=le(l),h=ke("float32",c),d=ke("float32",c);for(let e=0;e<s;e++){const r=z$({inputs:{x:o},backend:n,attrs:{begin:[e,0],size:[1,a]}}),s=z$({inputs:{x:u},backend:n,attrs:{begin:[e,0],size:[1,a]}}),i=jE({inputs:{real:r,imag:s},backend:n}),{real:l,imag:c}=s_(i,t,n),p=dm(l,c);for(let t=0;t<a;t++){const n=gm(p,t);h[e*a+t]=n.real,d[e*a+t]=n.imag}n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i)}const p=n.makeTensorInfo(l,"float32",h),f=n.makeTensorInfo(l,"float32",d),m=jE({inputs:{real:p,imag:f},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),m}function s_(e,t,n){const r=le(e.shape),s=n.data.get(e.dataId),a=n.data.get(s.complexTensorInfos.real.dataId).values,i=n.data.get(s.complexTensorInfos.imag.dataId).values;if((o=r)&o-1){const e=function(e,t,n){const r=new Float32Array(2*t);for(let s=0;s<t;s++){let a=0,i=0;for(let r=0;r<t;r++){const o=xm(s*r,t,n),u=gm(e,r);a+=u.real*o.real-u.imag*o.imag,i+=u.real*o.imag+u.imag*o.real}n&&(a/=t,i/=t),ym(r,a,i,s)}return r}(dm(a,i),r,t);return pm(e)}{const s=a_(a,i,r,t,n),o=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(o,"float32",s.real),t=n.makeTensorInfo(o,"float32",s.imag),a=n.makeTensorInfo([],"float32",qs(r,"float32")),i=XE({inputs:{x:a},backend:n}),u=n_.kernelFunc({inputs:{a:e,b:a},backend:n}),l=n_.kernelFunc({inputs:{a:t,b:i},backend:n}),c=n.data.get(u.dataId).values,h=n.data.get(l.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),{real:c,imag:h}}return s}var o}function a_(e,t,n,r,s){if(1===n)return{real:e,imag:t};const a=dm(e,t),i=n/2,o=fm(a),u=o.real,l=o.imag,c=[u.length],h=s.makeTensorInfo(c,"float32",u),d=s.makeTensorInfo(c,"float32",l),p=jE({inputs:{real:h,imag:d},backend:s}),f=mm(a),m=f.real,g=f.imag,y=[m.length],b=s.makeTensorInfo(y,"float32",m),x=s.makeTensorInfo(y,"float32",g),w=jE({inputs:{real:b,imag:x},backend:s}),v=a_(u,l,i,r,s),k=v.real,I=v.imag,S=[k.length],N=s.makeTensorInfo(S,"float32",k),T=s.makeTensorInfo(S,"float32",I),E=jE({inputs:{real:N,imag:T},backend:s}),C=a_(m,g,i,r,s),$=C.real,A=C.imag,R=[$.length],_=s.makeTensorInfo(R,"float32",$),M=s.makeTensorInfo(R,"float32",A),F=jE({inputs:{real:_,imag:M},backend:s}),D=bm(n,r),O=[D.real.length],L=s.makeTensorInfo(O,"float32",D.real),z=s.makeTensorInfo(O,"float32",D.imag),P=jE({inputs:{real:L,imag:z},backend:s}),B=u$({inputs:{a:P,b:F},backend:s}),V=iC({inputs:{a:E,b:B},backend:s}),U=iA({inputs:{a:E,b:B},backend:s}),W=JE({inputs:{input:V},backend:s}),G=JE({inputs:{input:U},backend:s}),H=hR({inputs:{input:V},backend:s}),j=hR({inputs:{input:U},backend:s}),q=pR({inputs:[W,G],backend:s,attrs:{axis:0}}),K=pR({inputs:[H,j],backend:s,attrs:{axis:0}}),X=s.data.get(q.dataId).values,Y=s.data.get(K.dataId).values;return s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(b),s.disposeIntermediateTensorInfo(x),s.disposeIntermediateTensorInfo(w),s.disposeIntermediateTensorInfo(N),s.disposeIntermediateTensorInfo(T),s.disposeIntermediateTensorInfo(E),s.disposeIntermediateTensorInfo(_),s.disposeIntermediateTensorInfo(M),s.disposeIntermediateTensorInfo(F),s.disposeIntermediateTensorInfo(L),s.disposeIntermediateTensorInfo(z),s.disposeIntermediateTensorInfo(P),s.disposeIntermediateTensorInfo(B),s.disposeIntermediateTensorInfo(V),s.disposeIntermediateTensorInfo(U),s.disposeIntermediateTensorInfo(W),s.disposeIntermediateTensorInfo(H),s.disposeIntermediateTensorInfo(G),s.disposeIntermediateTensorInfo(j),s.disposeIntermediateTensorInfo(q),s.disposeIntermediateTensorInfo(K),{real:X,imag:Y}}const i_={kernelName:on,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}
5057=e,{input:r}=t,s=le(r.shape),a=r.shape[r.shape.length-1],i=TA({inputs:{x:r},backend:n,attrs:{shape:[s/a,a]}}),o=r_(i,!1,n),u=TA({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}};function o_(e){const{backend:t,attrs:n}=e,{shape:r,value:s,dtype:a}=n,i=a||_e(s),o=Ie(i,le(r));return function(e,t){e.fill(t)}(o,s),t.makeTensorInfo(r,i,o)}const u_={kernelName:un,backendName:"cpu",kernelFunc:o_},l_={kernelName:ln,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,s=n,a=ke(r.dtype,le(r.shape)),[i,o,u,l]=r.shape,c=s.data.get(r.dataId).values;for(let e=0;e<i;e++){const t=e*u*o*l;for(let e=0;e<o;e++){const n=e*(u*l);for(let e=0;e<u;e++){const r=e*l;for(let s=0;s<l;s++){const i=Math.round(u-e-1),o=t+n+r+s;let h=c[o];i>=0&&i<u&&(h=c[t+n+i*l+s]),a[o]=h}}}}return{dataId:s.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},c_={kernelName:ys,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=r;let m=mR({inputs:{x:s,filter:a},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=TA({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=iC({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=iC({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(p){const e=m;if("NCHW"===c&&"prelu"===p&&1===o.shape.length&&1!==o.shape[0]){const e=TA({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=NA(n,m,p,e,f),n.disposeIntermediateTensorInfo(e)}else m=NA(n,m,p,o,f);n.disposeIntermediateTensorInfo(e)}return m}},h_={kernelName:bs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=r;let m=RR({inputs:{x:s,filter:a},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const e=m;m=iC({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(p){const e=m;m=NA(n,m,p,o,f),n.disposeIntermediateTensorInfo(e)}return m}},d_={kernelName:fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=le(r.shape),i=s.shape,o=i[i.length-1],[u,l,c,h]=ju(r,s);if(0===l)return n.makeTensorInfo(u,r.dtype,[]);const d=DC(n.data.get(s.dataId).values,n.bufferSync(r),r.dtype,l,o,c,h,r.shape,a);return n.makeTensorInfo(u,r.dtype,d.values)}},p_={kernelName:pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:i,batchDims:o}=r;BE([s,a],"gatherV2");const u=we(i,s.shape)[0],l=n.data.get(a.dataId).values,c=s.shape[u];for(let e=0;e<l.length;++e){const t=l[e];ie(t<=c-1&&t>=0,()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`)}let h=o;null==o&&(h=0);const d=le(a.shape),p=Hm(s,a,u,h),f=TA({inputs:{x:s},backend:n,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),m=TA({inputs:{x:a},backend:n,attrs:{shape:[p.batchSize,d/p.batchSize]}}),g=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],y=n.bufferSync(m),b=OC(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(p.outputShape,b.dtype,b.values)}},f_={kernelName:bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,s=le(r.shape),a=r.shape[r.shape.length-1],i=TA({inputs:{x:r},backend:n,attrs:{shape:[s/a,a]}}),o=r_(i,!0,n),u=TA({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}},m_=fC(wn,e=>Number.isFinite(e)?1:0,"bool"),g_={kernelName:wn,backendName:"cpu",kernelFunc:m_},y_=fC(vn,e=>Math.abs(e)===1/0?1:0,"bool"),b_={kernelName:vn,backendName:"cpu",kernelFunc:y_},x_=fC(kn,e=>Number.isNaN(e)?1:0,"bool"),w_={kernelName:kn,backendName:"cpu",kernelFunc:x_},v_={kernelName:Tn,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,i=XC(r,s,a);return t.makeTensorInfo([i.length],"float32",i)}},k_=fC(Cn,e=>Math.log1p(e)),I_={kernelName:Cn,backendName:"cpu",kernelFunc:k_},S_=HE((e,t)=>e&&t),N_=nC($n,S_,null,"bool"),T_={kernelName:$n,backendName:"cpu",kernelFunc:N_},E_=fC(An,e=>e?0:1,"bool"),C_={kernelName:An,backendName:"cpu",kernelFunc:E_},$_=HE((e,t)=>e||t),A_=nC(Rn,$_,null,"bool"),R_={kernelName:Rn,backendName:"cpu",kernelFunc:A_},__={kernelName:Dn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:u}=r;BE(s,"LRN");const l=s.shape[3],c=l-1,h=n.data.get(s.dataId).values,d=le(s.shape),p=new Float32Array(d);function f(e){const t=e%l;let n=e-t+Math.max(0,t-a);const r=e-t+Math.min(t+a,c);let s=0;for(;n<=r;n++){const e=h[n];s+=e*e}return s}for(let e=0;e<d;e++){const t=f(e),n=h[e]*Math.pow(i+o*t,-u);p[e]=n}return n.makeTensorInfo(s.shape,s.dtype,p)}},M_={kernelName:On,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r;BE(i,"LRNGrad");
vendor: 10,661 bytes, line 5057
5057const h=le(i.shape),d=i.shape[3],p=n.data.get(i.dataId).values,f=n.data.get(s.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(h),y=h;for(let e=0;e<y;e++){const t=e%d,n=e-t+Math.max(0,t-o),r=e-t+Math.min(d,t+o+1);let s=0;for(let e=n;e<r;e++)s+=Math.pow(f[e],2);s=l*s+u;for(let t=n;t<r;t++){let n=-2*l*c*f[t]*m[e]/s;e===t&&(n+=Math.pow(s,-c)),n*=p[e],g[t]+=n}}return n.makeTensorInfo(i.shape,s.dtype,g)}};function F_(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=n;let u=s.shape;const l=u.length,c=we(a,u);let h=c;const d=nh(h,l);let p=o.data.get(s.dataId).values;if(null!=d){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[d[t]];p=m$(p,u,s.dtype,d,e),h=sh(h.length,l),u=e}BE(s,"max"),th("max",h,l);const[f,m]=Qc(u,h),g=QC(p,le(m),f,s.dtype),y=o.write(g,f,s.dtype);let b=f;return i&&(b=eh(f,c)),{dataId:y,shape:b,dtype:s.dtype}}const D_={kernelName:zn,backendName:"cpu",kernelFunc:F_},O_={kernelName:Bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;BE(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(ec(i,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations \'1\'`);const l=Gl(s.shape,a,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&de(l.inShape,l.outShape))c=XE({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=De(s.shape),r=JA(e,s.shape,s.dtype,t,l,"max");c=n.makeTensorInfo(l.outShape,s.dtype,r.values)}return c}},L_={kernelName:Un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;BE(s,"maxPool3d");const c=Hl(s.shape,a,i,1,o,u,l),h=QA(n.data.get(s.dataId).values,s.shape,s.dtype,De(s.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}},z_={kernelName:Wn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;BE([s,a],"maxPool3DGrad");const c=Hl(a.shape,i,o,1,u,l),h=function(e,t){const n=ko(t.outShape,"int32"),r=t.strideDepth,s=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,u=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,d=t.padInfo.front,p=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*r-d;let x=b;for(;x<0;)x+=i;const w=Math.min(t.inDepth,l+b);for(let r=0;r<t.outHeight;++r){const l=r*s-p;let d=l;for(;d<0;)d+=o;const v=Math.min(t.inHeight,c+l);for(let s=0;s<t.outWidth;++s){const p=s*a-f;let k=p;for(;k<0;)k+=u;const I=Math.min(t.inWidth,h+p);let S=Number.NEGATIVE_INFINITY,N=-1;for(let t=x;t<w;t+=i){const n=t-b;for(let r=d;r<v;r+=o){const s=r-l;for(let a=k;a<I;a+=u){const i=a-p,o=e.get(m,t,r,a,g);o>=S&&(S=o,N=n*c*h+s*c+i)}}}n.set(N,m,y,r,s,g)}}}return n}(n.bufferSync(a),c),d=c.strideDepth,p=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,I=x-1-c.padInfo.top,S=ko(a.shape,"float32"),N=n.bufferSync(s);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let s=0;s<c.inWidth;++s){const a=n-v,i=r-I,o=s-k;let u=0;for(let n=0;n<b;n+=m){const r=(a+n)/d;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let s=0;s<x;s+=g){const a=(i+s)/p;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let i=0;i<w;i+=y){const l=(o+i)/f;if(l<0||l>=c.outWidth||Math.floor(l)!==l)continue;const d=b*x*w-1-h.get(e,r,a,l,t)===n*x*w+s*w+i?1:0;0!==d&&(u+=N.get(e,r,a,l,t)*d)}}}S.set(u,e,n,r,s,t)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}},P_={kernelName:Vn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;BE([a,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:h}=r,d=Gl(o.shape,u,l,1,c,h),p=n.data.get(o.dataId).values,f=ko(d.outShape,o.dtype,ZA(p,o.shape,o.dtype,d).values),m=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,b=d.dilationWidth,x=d.effectiveFilterHeight,w=d.effectiveFilterWidth,v=w-1-d.padInfo.left,k=x-1-d.padInfo.top,I=ko(o.shape,"float32"),S=n.data.get(s.dataId).values,N=ko(s.shape,"float32",S);for(let e=0;e<d.batchSize;++e)for(let t=0;t<d.inChannels;++t)for(let n=0;n<d.inHeight;++n)for(let r=0;r<d.inWidth;++r){const s=n-k,a=r-v;let i=0;for(let n=0;n<x;n+=y){const r=(s+n)/m;if(!(r<0||r>=d.outHeight||Math.floor(r)!==r))for(let s=0;s<w;s+=b){const o=(a+s)/g;if(o<0||o>=d.outWidth||Math.floor(o)!==o)continue;const u=x*w-1-f.get(e,r,o,t)===n*w+s?1:0;0!==u&&(i+=N.get(e,r,o,t)*u)}}I.set(i,e,n,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}},B_={kernelName:Gn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,u=n;BE(r,"MaxPoolWithArgmax");const l=u.data.get(r.dataId).values,c=Gl(r.shape,s,a,[1,1],i),[h,d]=function(e,t,n,r,s){const a=JA(e,0,n,De(t),s,"max"),i=ZA(e,t,n,s,!0,r);return[a.values,i.values]}(l,r.shape,r.dtype,o,c),p=u.write(h,c.outShape,r.dtype),f=u.write(d,c.outShape,r.dtype);return[{dataId:p,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}},V_={kernelName:Hn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=we(a,s.shape),u=le(Qc(s.shape,o)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const h=eC({inputs:{x:s},backend:n,attrs:{dtype:"float32"}});l.push(h);const d=t_({inputs:{a:h,b:c},backend:n});l.push(d);const p=BR({inputs:{x:d},backend:n,attrs:{axis:a,keepDims:i}});return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),p}},U_={kernelName:jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;BE(s,"min");const o=we(a,s.shape);let u=o;const l=nh(u,s.shape.length);let c=s;null!=l&&(c=g$({inputs:{x:s},backend:n,attrs:{perm:l}}),u=sh(u.length,s.shape.length)),th("min",u,c.shape.length);const[h,d]=Qc(c.shape,u),p=le(d),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const r=m[t+e];(Number.isNaN(r)||r<n)&&(n=r)}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=TA({inputs:{x:g},backend:n,attrs:{shape:eh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},W_={kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,mode:i}=r;BE(s,"mirrorPad");const o=a.map((e,t)=>e[0]+s.shape[t]+e[1]),u=a.map(e=>e[0]),l=a.map((e,t)=>e[0]+s.shape[t]),c="reflect"===i?0:1,h=n.data.get(s.dataId).values,d=s.shape.length,p=De(s.shape),f=le(o),m=o.length,g=De(o),y=ke(s.dtype,f);for(let e=0;e<f;e++){let t=Ge(e,m,g);for(let e=0;e<m;e++)t[e]<u[e]?t[e]=2*u[e]-t[e]-c:t[e]>=l[e]&&(t[e]=2*(l[e]-1)-t[e]+c);t=t.map((e,t)=>e-u[t]);const n=We(t,d,p);y[e]=h[n]}return{dataId:n.write(y,o,s.dtype),shape:o,dtype:s.dtype}}},G_=HE((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),H_=nC(Xn,G_),j_={kernelName:Xn,backendName:"cpu",kernelFunc:H_};function q_(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=s.shape.length;let o=a;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const u=we([o],s.shape),l=F_({inputs:{x:s},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=eh(l.shape,u),h=TA({inputs:{x:l},backend:n,attrs:{shape:c}}),d=iA({inputs:{a:s,b:h},backend:n}),p=SC({inputs:{x:d},backend:n}),f=BR({inputs:{x:p},backend:n,attrs:{axis:u,keepDims:!1}}),m=TA({inputs:{x:f},backend:n,attrs:{shape:c}}),g=t_({inputs:{a:p,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const K_={kernelName:Ur,backendName:"cpu",kernelFunc:q_},X_={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}=r;BE(s,"multinomial");const u=o?s:q_({inputs:{logits:s},backend:n,attrs:{dim:-1}}),l=u.shape[0],c=u.shape[1],h=n.data.get(u.dataId).values,d=[l,a],p=Be(le(d),"int32");for(let e=0;e<l;++e){const t=e*c,n=new Float32Array(c-1);n[0]=h[t];for(let e=1;e<n.length;++e)n[e]=n[e-1]+h[t+e];const r=gd.alea(i.toString()),s=e*a;for(let e=0;e<a;++e){const t=r();p[s+e]=n.length;for(let r=0;r<n.length;r++)if(t<n[r]){p[s+e]=r;break}}}return o||n.disposeIntermediateTensorInfo(u),n.makeTensorInfo(d,"int32",p)}},Y_=Jp,J_={kernelName:er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=r;BE(s,"NonMaxSuppression");const l=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:h}=Y_(l,c,i,o,u);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},Z_=Zp,Q_={kernelName:tr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r;BE(s,"NonMaxSuppressionPadded");const c=n.data.get(s.dataId).values,h=n.data.get(a.dataId).values,{selectedIndices:d,validOutputs:p}=Z_(c,h,i,o,u,l);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([p]))]}},eM=Qp,tM={kernelName:nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r;BE(s,"NonMaxSuppressionWithScore");const c=n.data.get(s.dataId).values,h=n.data.get(a.dataId).values,d=i,p=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=eM(c,h,d,p,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}},nM={kernelName:sr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{dtype:a,depth:i,onValue:o,offValue:u}=r;BE(s,"oneHot");const l=le(s.shape),c=new Float32Array(l*i);c.fill(u);const h=n.data.get(s.dataId).values;for(let e=0;e<l;++e)h[e]>=0&&h[e]<i&&(c[e*i+h[e]]=o);return n.makeTensorInfo([...s.shape,i],a,c)}};function rM(e){const{inputs:t,backend:n}=e,{x:r}=t;if("string"===r.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===r.dtype){const e=JE({inputs:{input:r},backend:n}
5057),t=rM({inputs:{x:e},backend:n}),s=hR({inputs:{input:r},backend:n}),a=rM({inputs:{x:s},backend:n}),i=jE({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}return o_({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const sM={kernelName:ds,backendName:"cpu",kernelFunc:rM},aM={kernelName:rr,backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:s}=n;if("string"===s.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===s.dtype){const t=JE({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r}),a=hR({inputs:{input:s},backend:r}),i=rM({inputs:{x:a},backend:r}),o=jE({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}return o_({backend:r,attrs:{shape:s.shape,value:1,dtype:s.dtype}})}};function iM(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(1===t.length)return ZR({inputs:{input:t[0]},backend:n,attrs:{dim:s}});const a=t[0].shape,i=t[0].dtype;t.forEach(e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],u=pR({inputs:t.map(e=>{const t=ZR({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t}),backend:n,attrs:{axis:s}});return o.forEach(e=>n.disposeIntermediateTensorInfo(e)),u}const oM={kernelName:ar,backendName:"cpu",kernelFunc:iM},uM={kernelName:ir,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;BE(s,"pad");const o=a.map((e,t)=>e[0]+s.shape[t]+e[1]),u=a.map(e=>e[0]),l=n.data.get(s.dataId).values,c=le(s.shape),h=s.shape.length,d=De(s.shape),p=le(o),f=o.length,m=De(o),g=ke(s.dtype,p);0!==i&&g.fill(i);for(let e=0;e<c;e++)g[We(Ge(e,h,d).map((e,t)=>e+u[t]),f,m)]=l[e];return{dataId:n.write(g,o,s.dtype),shape:o,dtype:s.dtype}}},lM=HE((e,t)=>Math.pow(e,t)),cM=nC(ur,lM),hM={kernelName:ur,backendName:"cpu",kernelFunc:cM},dM={kernelName:hr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=r,u=s.map(e=>n.data.get(e.dataId).values),l=s.map(e=>e.shape),c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,[d,p,f]=v$(u,l,c,a.shape,a.dtype,h,i.shape),m=d.map(e=>n.makeTensorInfo([e.length],"int32",e)),g=n.makeTensorInfo(f,a.dtype,p);return m.concat([g])}},pM={kernelName:dr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:s,deltas:a}=t,i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=I$(i,r.shape,r.dtype,o,s.shape,u,a.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}},fM={kernelName:pr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,d=o.map(e=>n.data.get(e.dataId).values),p=o.map(e=>e.shape),[f,m]=C$(l,s.shape,c,a.shape,a.dtype,h,i.shape,d,p,u);return n.makeTensorInfo(f,a.dtype,m)}},mM={kernelName:fr,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,dtype:a,step:i}=n,o=$$(r,s,i,a);return t.makeTensorInfo([o.length],a,o)}},gM=fC(gr,e=>1/e),yM={kernelName:gr,backendName:"cpu",kernelFunc:gM},bM={kernelName:vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r;BE(s,"resizeBilinear");const u=De(s.shape),[l,c]=o,[h,d,p,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(le([h,l,c,f])),y=[a&&l>1?d-1:d,a&&c>1?p-1:p],b=[a&&l>1?l-1:l,a&&c>1?c-1:c];let x=0;const w=y[0]/b[0],v=y[1]/b[1];for(let e=0;e<h;e++)for(let t=0;t<l;t++){let n;n=i?w*(t+.5)-.5:w*t;const r=Math.max(0,Math.floor(n)),s=n-r,a=Math.min(d-1,Math.ceil(n)),o=e*u[0]+r*u[1],l=e*u[0]+a*u[1];for(let e=0;e<c;e++){let t;t=i?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),r=t-n,a=Math.min(p-1,Math.ceil(t)),c=o+n*u[2],h=l+n*u[2],d=o+a*u[2],y=l+a*u[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[h+e],a=t+(m[d+e]-t)*r,i=a+(n+(m[y+e]-n)*r-a)*s;g[x++]=i}}}return n.makeTensorInfo([h,l,c,f],"float32",g)}},xM={kernelName:kr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r;BE([a,s],"resizeBilinearGrad");const o=De(s.shape),[u,l,c,h]=s.shape,[,d,p]=a.shape,f=new Float32Array(u*l*c*h),m=[i&&d>1?l-1:l,i&&p>1?c-1:c],g=[i&&d>1?d-1:d,i&&p>1?p-1:p],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(a.dataId).values;let w=0;for(let e=0;e<u;e++){const t=e*o[0];for(let e=0;e<d;e++){const n=e*y,r=Math.floor(n),s=Math.min(Math.ceil(n),l-1),a=t+r*o[1],i=t+s*o[1],u=n-r,d=1-u;for(let e=0;e<p;e++){const t=e*b,n=Math.floor(t),r=Math.min(Math.ceil(t),c-1),s=t-n,l=1-s,p=a+n*o[2],m=a+r*o[2],g=i+n*o[2],y=i+r*o[2],v=d*l,k=d*s,I=u*l,S=u*s;for(let e=0;e<h;e++){const t=x[w++];f[p+e]+=t*v,f[m+e]+=t*k,f[g+e]+=t*I,f[y+e]+=t*S}}}}return n.makeTensorInfo([u,c,l,h],"float32",f)}},wM={kernelName:xr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r;BE(s,"resizeNearestNeighbor");const u=De(s.shape),[l,c]=o,[h,d,p,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(h*l*c*f),y=[a&&l>1?d-1:d,a&&c>1?p-1:p],b=[a&&l>1?l-1:l,a&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let v=0;for(let e=0;e<h;e++){const t=e*u[0];for(let e=0;e<l;e++){const n=i?x*(e+.5):x*e;let r=Math.min(d-1,a?Math.round(n):Math.floor(n));i&&(r=Math.max(0,r));const s=t+r*u[1];for(let e=0;e<c;e++){const t=i?w*(e+.5):w*e;let n=Math.min(p-1,a?Math.round(t):Math.floor(t));i&&(n=Math.max(0,n));const r=s+n*u[2];for(let e=0;e<f;e++){const t=m[r+e];g[v++]=t}}}}return n.makeTensorInfo([h,l,c,f],s.dtype,g)}},vM={kernelName:wr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r;BE([a,s],"resizeNearestNeighborGrad");const o=De(s.shape),u=De(a.shape),[l,c,h,d]=s.shape,[,p,f]=a.shape,m=ne
5057w Float32Array(l*c*h*d),g=n.data.get(a.dataId).values,y=[i&&p>1?c-1:c,i&&f>1?h-1:h],b=[i&&p>1?p-1:p,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,I=2*Math.ceil(v)+2,S=2*Math.ceil(k)+2;for(let e=0;e<l;e++){const t=e*o[0];for(let e=0;e<c;e++){const n=t+e*o[1],r=Math.floor(e*v),s=Math.floor(r-I/2);for(let r=0;r<h;r++){const a=n+r*o[2],l=Math.floor(r*k),y=Math.floor(l-S/2);for(let n=0;n<d;n++){let o=0;for(let a=0;a<I;a++){const l=a+s;if(l<0||l>=p)continue;const d=t+l*u[1],m=l*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e<S;e++){const t=e+y;if(t<0||t>=f)continue;const s=d+t*u[2],a=t*w;r===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[s+n])}}m[a+n]=o}}}}return n.makeTensorInfo(s.shape,s.dtype,m)}},kM={kernelName:Sr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r;BE(s,"reverse");const i=s.shape.length,o=we(a,s.shape);if(0===i)return XE({inputs:{x:s},backend:n});const u=new la(s.shape,s.dtype),l=n.bufferSync(s);for(let e=0;e<u.size;e++){const t=u.indexToLoc(e),n=t.slice();o.forEach(e=>n[e]=s.shape[e]-1-n[e]),u.set(l.get(...n),...t)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},IM={kernelName:ms,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,u=ke(r.dtype,le(r.shape)),[l,c,h,d]=r.shape,[p,f]=Zf(i,c,h),m=Math.sin(s),g=Math.cos(s),y=o.data.get(r.dataId).values;for(let e=0;e<l;e++){const t=e*h*c*d;for(let e=0;e<c;e++){const n=e*(h*d);for(let r=0;r<h;r++){const s=r*d;for(let i=0;i<d;i++){const o=[l,e,r,i],b=o[2],x=o[1];let w=(b-p)*g-(x-f)*m,v=(b-p)*m+(x-f)*g;w=Math.round(w+p),v=Math.round(v+f);let k=a;"number"!=typeof a&&(k=3===i?255:a[i]),w>=0&&w<h&&v>=0&&v<c&&(k=y[t+v*(h*d)+w*d+i]),u[t+n+s+i]=k}}}}return{dataId:o.write(u,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},SM=fC(Nr,e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),NM={kernelName:Nr,backendName:"cpu",kernelFunc:SM},TM={kernelName:Er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=Xu(0,s,i),d=M$(n.bufferSync(s),n.bufferSync(a),i,h,l,u,o,c,0,!0);return n.makeTensorInfo(i,d.dtype,d.values)}};function EM(e,t){let n=0,r=e.length,s=0;for(;n<r;)s=Math.floor((n+r)/2),e[s]<t?n=s+1:r=s;return r}function CM(e,t){let n=0,r=e.length,s=0;for(;n<r;)s=Math.floor((n+r)/2),e[s]<=t?n=s+1:r=s;return r}const $M={kernelName:$r,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:s,values:a}=t,{side:i}=r,o=function(e,t,n,r,s,a){const i=Ie("int32",n*s);for(let o=0;o<n;++o){const n=e.slice(o*r,(o+1)*r),u=o*s;for(let e=0;e<s;++e)i[u+e]="left"===a?EM(n,t[e+u]):CM(n,t[e+u])}return i}(n.data.get(s.dataId).values,n.data.get(a.dataId).values,s.shape[0],s.shape[1],a.shape[1],i);return n.makeTensorInfo(a.shape,"int32",o)}},AM={kernelName:Ar,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t;BE([r,s,a],"select");const i=r.shape.length,o=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,c=ka(s.dtype,a.dtype),h=Be(le(s.shape),c);let d=0;const p=0===i||i>1||1===s.shape.length?1:le(s.shape.slice(1));for(let e=0;e<o.length;e++)for(let t=0;t<p;t++)1===o[e]?h[d++]=u[e]:h[d++]=l[e];return n.makeTensorInfo(s.shape,c,h)}},RM=sm,_M=am,MM=fC(Rr,e=>e>=0?_M*e:RM*(Math.exp(e)-1)),FM={kernelName:Rr,backendName:"cpu",kernelFunc:MM},DM=fC(Dr,e=>e<0?-1:e>0?1:0),OM={kernelName:Dr,backendName:"cpu",kernelFunc:DM},LM=fC(Mr,e=>Math.sin(e)),zM={kernelName:Mr,backendName:"cpu",kernelFunc:LM},PM=fC(Fr,e=>Math.sinh(e)),BM={kernelName:Fr,backendName:"cpu",kernelFunc:PM},VM=Math.log(1.1920928955078125e-7)+2,UM=fC(Lr,e=>{const t=e>-VM,n=e<VM,r=Math.exp(e);let s;return s=n?r:t?e:Math.log(1+r),s}),WM={kernelName:Lr,backendName:"cpu",kernelFunc:UM},GM={kernelName:Br,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:i}=r;BE([s],"spaceToBatchND");const o=le(a),u=[[0,0]];u.push(...i);for(let e=1+a.length;e<s.shape.length;++e)u.push([0,0]);
vendor: 11,280 bytes, line 5057
5057const l=uM.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:u,constantValue:0}}),c=Qf(l.shape,a,o,!1),h=em(c.length,a.length,!1),d=tm(l.shape,a,o,!1),p=TA({inputs:{x:l},backend:n,attrs:{shape:c}}),f=g$({inputs:{x:p},backend:n,attrs:{perm:h}}),m=TA({inputs:{x:f},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),m}},HM={kernelName:Wr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\\n        ${a.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\\n        ${r.shape}`);if(1!==s.shape.length)throw new Error(`Values must be a vector, saw:\\n        ${s.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\\n        ${i.shape}`);const o=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,c=n.data.get(i.dataId).values[0],[h,d,p,f,m]=B$(o,r.shape,r.dtype,u,s.dtype,l,c);return[n.makeTensorInfo(d,r.dtype,h),n.makeTensorInfo([d[0]],s.dtype,p),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(e=>Number(e)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}},jM={kernelName:Gr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\\n        ${r.shape}`);if(1!==s.shape.length)throw new Error(`Input shape should be a vector but received shape\\n        ${s.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.data.get(s.dataId).values),o=n.data.get(r.dataId).values,u=Array.from(n.data.get(a.dataId).values),[l,c,h]=V$(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},qM={kernelName:Hr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\\n          ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\\n          ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=U$(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}},KM={kernelName:jr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\\n         ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\\n         ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=U$(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}},XM={kernelName:qr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:h,outputSize:d}=Xu(0,s,o),p=!1,f=n.bufferSync(s);let m;switch(a.dtype){case"bool":m=M$(f,n.bufferSync(a),o,d,c,l,u,h,Boolean(n.data.get(i.dataId).values[0]),p);break;case"float32":case"int32":m=M$(f,n.bufferSync(a),o,d,c,l,u,h,n.data.get(i.dataId).values[0],p);break;case"string":m=M$(f,n.bufferSync(a),o,d,c,l,u,h,Zs(n.data.get(i.dataId).values[0]),p);break;default:throw new Error(`Unsupported type ${a.dtype}`)}return n.makeTensorInfo(o,m.dtype,m.values)}},YM={kernelName:Vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:i}=r,o=we(i,s.shape)[0],u=Am(s,a,o),l=new Array(s.shape.length).fill(0),c=s.shape.slice();return u.map(e=>{const t=[...c];t[o]=e;const r=z$({inputs:{x:s},backend:n,attrs:{begin:l,size:t}});return l[o]+=e,r})}},JM={kernelName:Xr,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;BE(n,"square");const s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let e=0;e<s.length;++e){const t=s[e];a[e]=t*t}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},ZM=fC(ps,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),QM={kernelName:ps,backendName:"cpu",kernelFunc:ZM},eF={kernelName:Jr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=r;BE(s,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=pl(s.shape,a,i,o,u,l,c,h,d);let v;if(m)v=TA({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){ie(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const e=el(b,x,w),t=z$({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=TA({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=Z$(p,n.bufferSync(s),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}},tF={kernelName:Zr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:h}=t,d=n.data.get(c.dataId).values,p=n.data.get(h.dataId).values,[f,m]=eA(d,p,s,a,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}},nF={kernelName:Qr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values[0],[l,c,h]=nA(o,u,s),d=c.length;return[n.makeTensorInfo([d,2],"int32",l),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}},rF={kernelName:es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=rA(n.data.get(a.dataId).values,s);return n.makeTensorInfo(a.shape,"int32",i)}},sF=fC(ns,e=>Math.tan(e)),aF={kernelName:ns,backendName:"cpu",kernelFunc:sF},iF=fC(rs,e=>Math.tanh(e)),oF={kernelName:Cr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:r,indices:s,updates:a}=t,{sliceRank:i,numUpdates:o,sliceSize:u,strides:l,outputSize:c}=Xu(0,s,r.shape),h=n.bufferSync(s),d=n.bufferSync(a),p=n.bufferSync(r),f=M$(h,d,r.shape,c,u,o,i,l,p,!1);return n.makeTensorInfo(r.shape,f.dtype,f.values)}},uF={kernelName:ss,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;BE(s,"tile");const i=uA(n.bufferSync(s),a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}},lF={kernelName:as,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:i}=r;BE(s,"topk");const o=n.data.get(s.dataId).values,[u,l]=hA(o,s.shape,s.dtype,a,i);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}},cF={kernelName:is,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{image:s,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=n,[c,h,d,p]=s.shape,[f,m]=null!=l?l:[h,d],g=[c,f,m,p],y=De(s.shape),b=y[0],x=y[1],w=y[2],v=De(g),k=v[0],I=v[1],S=v[2],N=ke(s.dtype,le(g));N.fill(u);const T=r.data.get(s.dataId).values,E=r.data.get(a.dataId).values;for(let e=0;e<c;++e){const t=1===a.shape[0]?E:E.subarray(8*e,8*e+8);for(let n=0;n<f;++n)for(let r=0;r<m;++r)for(let s=0;s<p;++s){let a;const l=t[6]*r+t[7]*n+1;if(0===l)continue;const c=(t[0]*r+t[1]*n+t[2])/l,p=(t[3]*r+t[4]*n+t[5])/l,f=hF(c,d,o),m=hF(p,h,o);switch(i){case"nearest":a=pF(T,h,d,b,x,w,e,m,f,s,u);break;case"bilinear":a=fF(T,h,d,b,x,w,e,m,f,s,u);break;default:throw new Error(`Error in Transform: Expect \'nearest\' or \'bilinear\', but got ${i}`)}N[e*k+n*I+r*S+s]=a}return r.makeTensorInfo(g,s.dtype,N)}return{dataId:r.write(N,g,s.dtype),shape:s.shape,dtype:s.dtype}}};function hF(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return ee(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return ee(0,n,t-1)}(e,t);case"nearest":return function(e,t){return ee(0,e,t-1)}(e,t);default:return e}}function dF(e,t,n,r,s,a,i,o,u,l,c){return 0<=o&&o<t&&0<=u&&u<n?e[i*r+o*s+u*a+l]:c}function pF(e,t,n,r,s,a,i,o,u,l,c){return dF(e,t,n,r,s,a,i,Math.round(o),Math.round(u),l,c)}function fF(e,t,n,r,s,a,i,o,u,l,c){const h=Math.floor(o),d=Math.floor(u),p=h+1,f=d+1;return(p-o)*((f-u)*dF(e,t,n,r,s,a,i,h,d,l,c)+(u-d)*dF(e,t,n,r,s,a,i,h,f,l,c))+(o-h)*((f-u)*dF(e,t,n,r,s,a,i,p,d,l,c)+(u-d)*dF(e,t,n,r,s,a,i,p,f,l,c))}const mF={kernelName:us,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;BE(a,"unique");const i=r.data.get(a.dataId).values,{outputValues:o,outputShape:u,indices:l}=dA(i,s,a.shape,a.dtype);return[r.makeTensorInfo(u,a.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}},gF={kernelName:ls,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s.shape.length,o=s.shape[a],u=new Array(i-1);let l=0;for(let e=0;e<i;e++)e!==a&&(u[l++]=s.shape[e]);const c=new Array(i).fill(0),h=s.shape.slice();h[a]=1;const d=new Array(o);for(let e=0;e<d.length;e++){c[a]=e;const t=z$({inputs:{x:s},backend:n,attrs:{begin:c,size:h}});d[e]=TA({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return d}},yF={kernelName:cs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:i}=r;BE(s,"unsortedSegmentSum");const o=[],u=[],l=s.shape.length-a.shape.length;let c=a;for(let e=0;e<l;++e){const t=ZR({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,u.push(t)}for(let e=0;e<i;++e){const t=qs(e,"int32"),r=n.makeTensorInfo([],"int32",t),a=vC({inputs:{a:r,b:c},backend:n}),i=eC({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),l=u$({inputs:{a:i,b:s},backend:n}),h=BR({inputs:{x:l},backend:n,attrs:{axis:0,keepDims:!1}});o.push(h),u.push(r),u.push(a),u.push(i),u.push(l),u.push(h)}const h=iM({inputs:o,backend:n,attrs:{axis:0}});
5057return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),h}},bF=[AA,GE,_A,FA,oC,DA,OA,LA,zA,PA,VA,WA,HA,KA,YA,eR,tR,nR,rR,$A,sR,aR,iR,dC,oR,tC,bC,lR,qE,cR,fR,gR,yR,bR,xR,wR,vR,IR,NR,TR,ER,CR,$R,AR,_R,MR,FR,DR,OR,LR,zR,PR,UR,mA,WR,kC,JR,NC,QR,CC,i_,u_,l_,RC,FC,c_,h_,d_,p_,PC,UC,YE,f_,dR,g_,b_,w_,yA,HC,KC,v_,ZC,I_,T_,C_,R_,__,M_,D_,n$,O_,L_,z_,P_,B_,V_,U_,a$,W_,j_,X_,l$,h$,J_,Q_,tM,f$,nM,aM,oM,uM,hM,wA,x$,dM,pM,fM,mM,ZE,n_,yM,kA,SA,EA,bM,xM,wM,vM,kM,IM,NM,_$,TM,$M,AM,FM,O$,OM,zM,BM,P$,K_,WM,GM,HM,jM,qM,KM,XM,YM,H$,JM,K$,J$,QM,eF,tF,nF,rF,oA,VR,aF,{kernelName:rs,backendName:"cpu",kernelFunc:iF},oF,uF,lF,cF,y$,mF,gF,yF,sM];for(const e of bF)Ts(e);const xF={},wF={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function vF(e,t){xF[e]=t}function kF(e,t){if(!(e in xF)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if(Xe().getBool("IS_SAFARI")||"undefined"==typeof OffscreenCanvas||2!==e){if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e):t;return n.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete xF[e]},!1),Xe().getBool("SOFTWARE_WEBGL_ENABLED")&&(wF.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",wF)||n.getContext("experimental-webgl",wF):n.getContext("webgl2",wF)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;xF[e]=n}const n=xF[e];return null==n||n.isContextLost()?(delete xF[e],kF(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),xF[e])}var IF,SF,NF;function TF(e,t){return[t,e]}function EF(e){const t=le(e);return me(Math.ceil(t/4))}function CF(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function $F(e,t){const n=e;let r,s,a,i,o,u,l,c,h,d;return 2===Xe().getNumber("WEBGL_VERSION")?(r=n.R32F,s=n.R16F,a=n.RGBA16F,i=n.RGBA32F,o=n.RED,l=4,c=1,h=n.HALF_FLOAT,d=n.FLOAT,u=n.RGBA8):(r=e.RGBA,s=e.RGBA,a=e.RGBA,i=n.RGBA,o=e.RGBA,l=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,d=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:d}}function AF(e,t){const n=t();return Xe().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+FF(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(IF||(IF={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(SF||(SF={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(NF||(NF={}));const RF=5.96e-8,_F=65504;function MF(e){return!!(Xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||RF<Math.abs(e)&&Math.abs(e)<_F)}function FF(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function DF(e,t){return iD(e,()=>e.getExtension(t),\'Extension "\'+t+\'" not supported on this browser.\')}function OF(e,t){const n=iD(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(AF(e,()=>e.shaderSource(n,t)),AF(e,()=>e.compileShader(n)),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function LF(e,t){const n=iD(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(AF(e,()=>e.shaderSource(n,t)),AF(e,()=>e.compileShader(n)),Xe().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw PF(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const zF=/ERROR: [0-9]+:([0-9]+):/g;function PF(e,t){const n=zF.exec(t);if(null==n)return console.log(`Couldn\'t parse line number in error: ${t}`),void console.log(e);const r=+n[1],s=e.split("\\n"),a=s.length.toString().length+2,i=s.map((e,t)=>ye((t+1).toString(),a)+e);let o=0;for(let e=0;e<i.length;e++)o=Math.max(i[e].length,o);const u=i.slice(0,r-1),l=i.slice(r-1,r),c=i.slice(r);console.log(u.join("\\n")),console.log(t.split("\\n")[0]),console.log(`%c ${ye(l[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\\n"))}function BF(e){return iD(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function VF(e,t){if(AF(e,()=>e.linkProgram(t)),!Xe().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function UF(e,t){if(AF(e,()=>e.validateProgram(t)),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function WF(e,t){const n=iD(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return AF(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),AF(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function GF(e,t){const n=iD(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return AF(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),AF(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function HF(){return 2===Xe().getNumber("WEBGL_VERSION")?1:4}function jF(e){return iD(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function qF(e,t){const n=Xe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}
5057] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}function KF(e){return iD(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function XF(e,t,n,r,s,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(AF(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),AF(e,()=>e.vertexAttribPointer(o,s,e.FLOAT,!1,a,i)),AF(e,()=>e.enableVertexAttribArray(o)),!0)}function YF(e,t,n){oD(e,n),AF(e,()=>e.activeTexture(e.TEXTURE0+n)),AF(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function JF(e,t){oD(e,t),AF(e,()=>e.activeTexture(e.TEXTURE0+t)),AF(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function ZF(e,t,n){return iD(e,()=>e.getUniformLocation(t,n),\'uniform "\'+n+\'" not present in program.\')}function QF(e,t,n){return e.getUniformLocation(t,n)}function eD(e,t,n,r){AF(e,()=>YF(e,t,r)),AF(e,()=>e.uniform1i(n,r))}function tD(e){AF(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),AF(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),AF(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function nD(e,t,n){AF(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),AF(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function rD(e,t){AF(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),AF(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function sD(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+aD(e,t))}function aD(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function iD(e,t,n){const r=AF(e,()=>t());if(null==r)throw new Error(n);return r}function oD(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)}function uD(e,t=2){return le(e.slice(0,e.length-t))}function lD(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function cD(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[uD(e),...lD(e)]),t}function hD(e,t=!1){let n=Xe().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=Xe().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&Xe().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,1===(e=e.map((t,n)=>n>=e.length-2?te(e[n]):e[n])).length&&(e=[2,e[0]])),2!==e.length){const t=ve(e);e=t.newShape}let s=le(e),a=null;e.length<=1&&s<=n?a=[1,s]:2===e.length&&e[0]<=n&&e[1]<=n?a=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);const i=null!=a&&Math.max(...a)>r&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||i)if(t){const t=uD(e);let n=2,r=2;e.length&&([n,r]=lD(e)),s=t*(n/2)*(r/2),a=me(s).map(e=>2*e)}else a=me(s);return a}function dD(e){return e%2==0}function pD(e,t){if(de(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e[e.length-1],r=t[t.length-1];if(n===r)return!0;if(dD(n)&&dD(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&dD(e[0])&&dD(t[0])}let fD,mD;function gD(e){if(null==fD){const t=kF(e);fD=t.getParameter(t.MAX_TEXTURE_SIZE)}return fD}function yD(){fD=null}function bD(){mD=null}function xD(e){if(null==mD){const t=kF(e);mD=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,mD)}function wD(e){if(0===e)return 0;let t;const n=kF(e);return t=vD(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:vD(n,"EXT_disjoint_timer_query")?1:0,t}function vD(e,t){return null!=e.getExtension(t)}function kD(e){try{if(null!=kF(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function ID(e){if(0===e)return!1;const t=kF(e);if(1===e){if(!vD(t,"OES_texture_float"))return!1}else if(!vD(t,"EXT_color_buffer_float"))return!1;return ND(t)}function SD(e){if(0===e)return!1;const t=kF(e);if(1!==e){if(vD(t,"EXT_color_buffer_float"))return ND(t);const e="EXT_color_buffer_half_float";if(vD(t,e)){const n=t.getExtension(e);return function(e,t){const n=$F(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),a}(t,n)}return!1}return!!vD(t,"OES_texture_float")&&(!!vD(t,"WEBGL_color_buffer_float")&&ND(t))}function ND(e){const t=$F(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),s}function TD(e){return 2===e&&null!=kF(e).fenceSync}
5057function ED(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&ie("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const CD=Xe();function $D(){let e,t,n,r,s,a,i,o,u,l;return 2===Xe().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",s="texture",a="outputColor",i="out vec4 outputColor;",o=Xe().getBool("WEBGL2_ISNAN_CUSTOM")?"\\n      bool isnan_custom(float val) {\\n        uint floatToUint = floatBitsToUint(val);\\n        return (floatToUint & 0x7fffffffu) > 0x7f800000u;\\n      }\\n\\n      bvec4 isnan_custom(vec4 val) {\\n        return bvec4(isnan_custom(val.x),\\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\\n      }\\n\\n      #define isnan(value) isnan_custom(value)\\n    ":"",u="",l="\\n      #define round(value) newRound(value)\\n      int newRound(float value) {\\n        return int(floor(value + 0.5));\\n      }\\n\\n      ivec4 newRound(vec4 value) {\\n        return ivec4(floor(value + vec4(0.5)));\\n      }\\n    "):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",i="",o="\\n      #define isnan(value) isnan_custom(value)\\n      bool isnan_custom(float val) {\\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\\n      }\\n      bvec4 isnan_custom(vec4 val) {\\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\\n      }\\n    ",u="\\n      uniform float INFINITY;\\n\\n      bool isinf(float val) {\\n        return abs(val) == INFINITY;\\n      }\\n      bvec4 isinf(vec4 val) {\\n        return equal(abs(val), vec4(INFINITY));\\n      }\\n    ",l="\\n      int round(float value) {\\n        return int(floor(value + 0.5));\\n      }\\n\\n      ivec4 round(vec4 value) {\\n        return ivec4(floor(value + vec4(0.5)));\\n      }\\n    "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:u,defineRound:l}}function AD(e,t,n="index"){const r=De(t);return r.map((t,s)=>`int ${e[s]} = ${n} / ${t}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${t}`:`index -= ${e[s]} * ${t}`};`).join("")}function RD(e,t,n="index"){const r=De(t);return r.map((t,s)=>`int ${e[s]} = ${n} / outShapeStrides[${s}]; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`};`).join("")}function _D(e){const t=De(e).map(e=>e.toString());return`\\n  int getFlatIndex(ivec3 coords) {\\n    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\\n  }\\n`}CD.registerFlag("HAS_WEBGL",()=>CD.getNumber("WEBGL_VERSION")>0),CD.registerFlag("WEBGL_VERSION",()=>kD(2)?2:kD(1)?1:0),CD.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),CD.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>2===CD.get("WEBGL_VERSION")),CD.registerFlag("WEBGL_CPU_FORWARD",()=>!0),CD.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),CD.registerFlag("WEBGL_PACK",()=>CD.getBool("HAS_WEBGL")),CD.registerFlag("WEBGL_PACK_NORMALIZATION",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_CLIP",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_REDUCE",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_LAZILY_UNPACK",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_CONV_IM2COL",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>CD.getBool("WEBGL_PACK")),CD.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>gD(CD.getNumber("WEBGL_VERSION"))),CD.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>xD(CD.getNumber("WEBGL_VERSION"))),CD.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=CD.getNumber("WEBGL_VERSION");return 0===e?0:wD(e)}),CD.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>CD.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Pa()),CD.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>ID(CD.getNumber("WEBGL_VERSION"))),CD.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>!CD.getBool("WEBGL_FORCE_F16_TEXTURES")&&CD.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),CD.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>SD(CD.getNumber("WEBGL_VERSION"))),CD.registerFlag("WEBGL_FENCE_API_ENABLED",()=>TD(CD.getNumber("WEBGL_VERSION"))),CD.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>CD.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),CD.registerFlag("WEBGL_DELET
5057E_TEXTURE_THRESHOLD",()=>-1,e=>{if("number"!=typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)}),CD.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Pa()?1:-1,e=>{if("number"!=typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)}),CD.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),CD.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),CD.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),CD.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),CD.registerFlag("WEBGL_EXP_CONV",()=>!1),CD.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>CD.getBool("IS_TEST")),CD.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),CD.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),CD.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),CD.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);const MD="\\n  const float FLOAT_MAX = 1.70141184e38;\\n  const float FLOAT_MIN = 1.17549435e-38;\\n\\n  lowp vec4 encode_float(highp float v) {\\n    if (isnan(v)) {\\n      return vec4(255, 255, 255, 255);\\n    }\\n\\n    highp float av = abs(v);\\n\\n    if(av < FLOAT_MIN) {\\n      return vec4(0.0, 0.0, 0.0, 0.0);\\n    } else if(v > FLOAT_MAX) {\\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\\n    } else if(v < -FLOAT_MAX) {\\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\\n    }\\n\\n    highp vec4 c = vec4(0,0,0,0);\\n\\n    highp float e = floor(log2(av));\\n    highp float m = exp2(fract(log2(av))) - 1.0;\\n\\n    c[2] = floor(128.0 * m);\\n    m -= c[2] / 128.0;\\n    c[1] = floor(32768.0 * m);\\n    m -= c[1] / 32768.0;\\n    c[0] = floor(8388608.0 * m);\\n\\n    highp float ebias = e + 127.0;\\n    c[3] = floor(ebias / 2.0);\\n    ebias -= c[3] * 2.0;\\n    c[2] += floor(ebias) * 128.0;\\n\\n    c[3] += 128.0 * step(0.0, -v);\\n\\n    return c / 255.0;\\n  }\\n",{getBroadcastDims:FD}=y;
5057function DD(e,t,n){const r=[];if(e.forEach(e=>{const t=le(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=HD(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEac
5057h(e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)});const s=r.join("\\n"),a=e.map(e=>function(e,t,n=!1,r){let s="";s+=n?LD(e,r):OD(e,r);const a=e.shapeInfo.logicalShape,i=t.logicalShape;return a.length<=i.length&&(s+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=FD(e.shapeInfo.logicalShape,t.logicalShape),u=GD(i),l=i-a;let c;const h=["x","y","z","w","u","v"];c=0===a?"":i<2&&o.length>=1?"coords = 0;":o.map(e=>`coords.${h[e+l]} = 0;`).join("\\n");let d="";d=i<2&&a>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>`coords.${h[t+l]}`).join(", ");let p="return outputValue;";const f=1===le(e.shapeInfo.logicalShape),m=1===le(t.logicalShape);if(1!==a||f||m){if(f&&!m)p=1===i?"\\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\\n      ":"\\n        return vec4(outputValue.x);\\n      ";else if(o.length){const e=a-2,t=a-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?p="return vec4(outputValue.x);":o.indexOf(e)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}}else p="\\n      return vec4(outputValue.xy, outputValue.xy);\\n    ";return`\\n    vec4 ${s}() {\\n      ${u} coords = getOutputCoords();\\n      ${c}\\n      vec4 outputValue = get${r}(${d});\\n      ${p}\\n    }\\n  `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===u&&null==e.shapeInfo.flatOffset&&de(i,a))return`\\n      float ${s}() {\\n        return sampleTexture(${n}, resultUV);\\n      }\\n    `;const l=GD(u),c=FD(e.shapeInfo.logicalShape,t.logicalShape),h=u-o;let d;const p=["x","y","z","w","u","v"];d=0===o?"":u<2&&c.length>=1?"coords = 0;":c.map(e=>`coords.${p[e+h]} = 0;`).join("\\n");let f="";return f=u<2&&o>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>`coords.${p[t+h]}`).join(", "),`\\n    float ${s}() {\\n      ${l} coords = getOutputCoords();\\n      ${d}\\n      return get${r}(${f});\\n    }\\n  `}(e,t)),s}(e,t,n.packedInputs,n.enableShapeUniforms)).join("\\n"),i=t.texShape,o=$D(),u=function(e){return`\\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\\n      return ${e.texture2D}(textureSampler, uv).r;\\n    }\\n  `}(o);let l,c,h=function(e){return`${e.version}\\n    precision highp float;\\n    precision highp int;\\n    precision highp sampler2D;\\n    ${e.varyingFs} vec2 resultUV;\\n    ${e.defineOutput}\\n    const vec2 halfCR = vec2(0.5, 0.5);\\n\\n    struct ivec5\\n    {\\n      int x;\\n      int y;\\n      int z;\\n      int w;\\n      int u;\\n    };\\n\\n    struct ivec6\\n    {\\n      int x;\\n      int y;\\n      int z;\\n      int w;\\n      int u;\\n      int v;\\n    };\\n\\n    uniform float NAN;\\n    ${e.defineSpecialNaN}\\n    ${e.defineSpecialInf}\\n    ${e.defineRound}\\n\\n    int imod(int x, int y) {\\n      return x - y * (x / y);\\n    }\\n\\n    int idiv(int a, int b, float sign) {\\n      int res = a / b;\\n      int mod = imod(a, b);\\n      if (sign < 0. && mod != 0) {\\n        res -= 1;\\n      }\\n      return res;\\n    }\\n\\n    //Based on the work of Dave Hoskins\\n    //https://www.shadertoy.com/view/4djSRW\\n    #define HASHSCALE1 443.8975\\n    float random(float seed){\\n      vec2 p = resultUV * seed;\\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\\n      p3 += dot(p3, p3.yzx + 19.19);\\n      return fract((p3.x + p3.y) * p3.z);\\n    }\\n\\n    ${zD}\\n    ${PD}\\n    ${BD}\\n  `}(o);return t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return"\\n    int getOutputCoords() {\\n      return 0;\\n    }\\n  ";case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?n?"\\n      int getOutputCoords() {\\n        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\\n      }\\n    ":`\\n      int getOutputCoords() {\\n        return 2 * int(resultUV.x * ${r[1]}.0);\\n      }\\n    `:1===r[1]?n?"\\n      int getOutputCoords() {\\n        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\\n      }\\n    ":`\\n      int getOutputCoords() {\\n        return 2 * int(resultUV.y * ${r[0]}.0);\\n      }\\n    `:n?"\\n    int getOutputCoords() {\\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
5057\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(packedTexShape[0], packedTexShape[1]));\\n      return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\\n    }\\n  ":`\\n    int getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${r[0]}, ${r[1]}));\\n      return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\\n    }\\n  `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(de(e,t))return n?"\\n      ivec2 getOutputCoords() {\\n        ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\\n        return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\\n      }\\n    ":`\\n      ivec2 getOutputCoords() {\\n        return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\\n      }\\n    `;const s=Math.ceil(e[1]/2);return n?"\\n    ivec2 getOutputCoords() {\\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\\n      int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(packedTexShape[0], packedTexShape[1]));\\n\\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\\n      int r = 2 * (index / texelsInLogicalRow);\\n      int c = imod(index, texelsInLogicalRow) * 2;\\n\\n      return ivec2(r, c);\\n    }\\n  ":`\\n    ivec2 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${r[0]}, ${r[1]}));\\n\\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\\n      int r = 2 * (index / ${s});\\n      int c = imod(index, ${s}) * 2;\\n\\n      return ivec2(r, c);\\n    }\\n  `}(e,t,n);case 3:return function(e,t,n){if(n)return"\\n    ivec3 getOutputCoords() {\\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\\n      int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(packedTexShape[0], packedTexShape[1]));\\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\\n\\n      int b = index / texelsInBatch;\\n      index -= b * texelsInBatch;\\n\\n      int r = 2 * (index / texelsInLogicalRow);\\n      int c = imod(index, texelsInLogicalRow) * 2;\\n\\n      return ivec3(b, r, c);\\n    }\\n  ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`\\n    ivec3 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${r[0]}, ${r[1]}));\\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\\n\\n      int b = index / ${a};\\n      index -= b * ${a};\\n\\n      int r = 2 * (index / ${s});\\n      int c = imod(index, ${s}) * 2;\\n\\n      return ivec3(b, r, c);\\n    }\\n  `}(e,t,n);default:return function(e,t,n){if(n)return"\\n    ivec4 getOutputCoords() {\\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(packedTexShape[0], packedTexShape[1]));\\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\\n\\n      int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\\n      int texelsInBatchN = texelsInBatch * outShape[1];\\n\\n      int b2 = index / texelsInBatchN;\\n      index -= b2 * texelsInBatchN;\\n\\n      int b = index / texelsInBatch;\\n      index -= b * texelsInBatch;\\n\\n      int r = 2 * (index / texelsInLogicalRow);\\n      int c = imod(index, texelsInLogicalRow) * 2;\\n\\n      return ivec4(b2, b, r, c);\\n    }\\n  ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2);let i=a,o="",u="b, r, c";for(let t=2;t<e.length-1;t++)i*=e[e.length-t-1],o=`\\n      int b${t} = index / ${i};\\n      index -= b${t} * ${i};\\n    `+o,u=`b${t}, `+u;return`\\n    ivec${e.length}
5057 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${r[0]}, ${r[1]}));\\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\\n\\n      ${o}\\n\\n      int b = index / ${a};\\n      index -= b * ${a};\\n\\n      int r = 2 * (index / ${s});\\n      int c = imod(index, ${s}) * 2;\\n\\n      return ivec${e.length}(${u});\\n    }\\n  `}(e,t,n)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\\n    void setOutput(vec4 val) {\\n      ${e.output} = val;\\n    }\\n  `}(o)):(l=function(e,t,n){switch(e.length){case 0:return"\\n    int getOutputCoords() {\\n      return 0;\\n    }\\n  ";case 1:return function(e,t,n){return 1===t[0]?n?"\\n      int getOutputCoords() {\\n        return int(resultUV.x * float(outTexShape[1]));\\n      }\\n    ":`\\n      int getOutputCoords() {\\n        return int(resultUV.x * ${t[1]}.0);\\n      }\\n    `:1===t[1]?n?"\\n      int getOutputCoords() {\\n        return int(resultUV.y * float(outTexShape[0]));\\n      }\\n    ":`\\n      int getOutputCoords() {\\n        return int(resultUV.y * ${t[0]}.0);\\n      }\\n    `:n?"\\n    int getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(outTexShape[0], outTexShape[1]));\\n      return resTexRC.x * outTexShape[1] + resTexRC.y;\\n    }\\n  ":`\\n    int getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${t[0]}, ${t[1]}));\\n      return resTexRC.x * ${t[1]} + resTexRC.y;\\n    }\\n  `}(0,t,n);case 2:return function(e,t,n){return de(e,t)?n?"\\n      ivec2 getOutputCoords() {\\n        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\\n      }\\n    ":`\\n      ivec2 getOutputCoords() {\\n        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\\n      }\\n    `:1===e[1]?n?"\\n      ivec2 getOutputCoords() {\\n        ivec2 resTexRC = ivec2(resultUV.yx *\\n                               vec2(outTexShape[0], outTexShape[1]));\\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\\n        return ivec2(index, 0);\\n      }\\n    ":`\\n      ivec2 getOutputCoords() {\\n        ivec2 resTexRC = ivec2(resultUV.yx *\\n                               vec2(${t[0]}, ${t[1]}));\\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n        return ivec2(index, 0);\\n      }\\n    `:1===e[0]?n?"\\n      ivec2 getOutputCoords() {\\n        ivec2 resTexRC = ivec2(resultUV.yx *\\n                               vec2(outTexShape[0], outTexShape[1]));\\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\\n        return ivec2(0, index);\\n      }\\n    ":`\\n      ivec2 getOutputCoords() {\\n        ivec2 resTexRC = ivec2(resultUV.yx *\\n                               vec2(${t[0]}, ${t[1]}));\\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n        return ivec2(0, index);\\n      }\\n    `:n?"\\n    ivec2 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(outTexShape[0], outTexShape[1]));\\n      int index = resTexRC.x * outTexShape[1] + resTexRC.y;\\n      int r = index / outShape[1];\\n      int c = index - r * outShape[1];\\n      return ivec2(r, c);\\n    }\\n  ":`\\n    ivec2 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${t[0]}, ${t[1]}));\\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n      int r = index / ${e[1]};\\n      int c = index - r * ${e[1]};\\n      return ivec2(r, c);\\n    }\\n  `}(e,t,n);case 3:return function(e,t,n){if(n)return`\\n  ivec3 getOutputCoords() {\\n    ivec2 resTexRC = ivec2(resultUV.yx *\\n                           vec2(outTexShape[0], outTexShape[1]));\\n    int index = resTexRC.x * outTexShape[1] + resTexRC.y;\\n    ${RD(["r","c","d"],e)}\\n    return ivec3(r, c, d);\\n  }\\n`;const r=AD(["r","c","d"],e);return`\\n    ivec3 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n                             vec2(${t[0]}, ${t[1]}));\\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n      ${r}\\n      return ivec3(r, c, d);\\n    }\\n  `}(e,t,n);case 4:return function(e,t,n){if(n)return`\\n    ivec4 getOutputCoords() {\\n      ivec2 resTexRC = ive
5057c2(resultUV.yx *\\n        vec2(outTexShape[0], outTexShape[1]));\\n      int index = resTexRC.x * outTexShape[1] + resTexRC.y;\\n      ${RD(["r","c","d","d2"],e)}\\n      return ivec4(r, c, d, d2);\\n    }\\n  `;const r=AD(["r","c","d","d2"],e);return`\\n    ivec4 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n        vec2(${t[0]}, ${t[1]}));\\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n      ${r}\\n      return ivec4(r, c, d, d2);\\n    }\\n  `}(e,t,n);case 5:return function(e,t){const n=AD(["r","c","d","d2","d3"],e);return`\\n    ivec5 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\\n                             ${t[1]}));\\n\\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n\\n      ${n}\\n\\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\\n      return outShape;\\n    }\\n  `}(e,t);case 6:return function(e,t){const n=AD(["r","c","d","d2","d3","d4"],e);return`\\n    ivec6 getOutputCoords() {\\n      ivec2 resTexRC = ivec2(resultUV.yx *\\n        vec2(${t[0]}, ${t[1]}));\\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\\n\\n      ${n}\\n\\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\\n      return result;\\n    }\\n  `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\\n    void setOutput(float val) {\\n      ${e.output} = vec4(val, 0, 0, 0);\\n    }\\n  `}(o)),n.packedInputs&&(h+=VD),[h,u,c,s,l,a,n.userCode].join("\\n")}function OD(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;const[s,a]=e.shapeInfo.texShape;if(1===s&&1===a)return`\\n      float ${r}() {\\n        return sampleTexture(${n}, halfCR);\\n      }\\n    `;const i=UD(n);if(t)return`\\n    float ${r}() {\\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});\\n      return sampleTexture(${n}, uv);\\n    }\\n  `;const[o,u]=e.shapeInfo.texShape;return`\\n    float ${r}() {\\n      vec2 uv = uvFromFlat(${o}, ${u}, ${i});\\n      return sampleTexture(${n}, uv);\\n    }\\n  `}(e,t);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\\n      float ${r}(int index) {\\n        ${WD(e)}\\n      }\\n    `;const s=e.shapeInfo.texShape,a=s[0],i=s[1];if(1===i&&1===a)return`\\n      float ${r}(int index) {\\n        return sampleTexture(${n}, halfCR);\\n      }\\n    `;const o=UD(n);return 1===i?t?`\\n      float ${r}(int index) {\\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));\\n        return sampleTexture(${n}, uv);\\n      }\\n    `:`\\n      float ${r}(int index) {\\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${a}.0);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `:1===a?t?`\\n      float ${r}(int index) {\\n        vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `:`\\n      float ${r}(int index) {\\n        vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `:t?`\\n    float ${r}(int index) {\\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});\\n      return sampleTexture(${n}, uv);\\n    }\\n  `:`\\n    float ${r}(int index) {\\n      vec2 uv = uvFromFlat(${a}, ${i}, index + ${o});\\n      return sampleTexture(${n}, uv);\\n    }\\n  `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(null!=a&&de(n,a)){if(t)return`\\n      float ${s}(int row, int col) {\\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `;const e=a[0];return`\\n    float ${s}(int row, int col) {\\n      vec2 uv = (vec2(col, row) + halfCR) / vec2(${a[1]}.0, ${e}.0);\\n      return sampleTexture(${r}, uv);\\n    }\\n  `}const{newShape:i,keptDims:o}=ve(n),u=i;if(u.length<n.length){const n=["row","col"];return`\\n      ${OD(jD(e,u),t)}\\n      float ${s}(int row, int col) {\\n        return ${s}(${qD(n,o)});\\n      }\\n    `}if(e.shapeInfo.isUniform)return`\\n      float ${s}(int row, int col) {\\n        int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\\n        ${WD(e)}\\n      }\\n    `;const l=a[0],c=a[1],h=UD(r);return 1===c?t?`\\n      float ${s}(int row, int col) {\\n        float index = dot(vec3(row, col, ${h}), vec3(${r}Shape[1], 1, 1));\\n        vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n    float ${s}(int row, int col) {\\n      float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\\n      vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\\n      return sampleTexture(${r}, uv);\\n    }\\n  `:1===l?t?`\\n      float ${s}(int row, int col) {\\n        float index = dot(vec3(row, col, ${h}), vec3(${r}Shape[1], 1, 1));\\n        vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n    float ${s}(int row, int col) {\\n      float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\\n      vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\\n      return sampleTexture(${r}, uv);\\n    }\\n  `:t?`\\n      float ${s}(int row, int col) {\\n        // Explicitly use integer operations as dot() only w
5057orks on floats.\\n        int index = row * ${r}Shape[1] + col + ${h};\\n        vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n  float ${s}(int row, int col) {\\n    // Explicitly use integer operations as dot() only works on floats.\\n    int index = row * ${n[1]} + col + ${h};\\n    vec2 uv = uvFromFlat(${l}, ${c}, index);\\n    return sampleTexture(${r}, uv);\\n  }\\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],i=n[2],{newShape:o,keptDims:u}=ve(n),l=o;if(l.length<n.length){const n=["row","col","depth"];return`\\n        ${OD(jD(e,l),t)}\\n        float ${s}(int row, int col, int depth) {\\n          return ${s}(${qD(n,u)});\\n        }\\n      `}if(e.shapeInfo.isUniform)return`\\n      float ${s}(int row, int col, int depth) {\\n        int index = round(dot(vec3(row, col, depth),\\n                          vec3(${a}, ${i}, 1)));\\n        ${WD(e)}\\n      }\\n    `;const c=e.shapeInfo.texShape,h=c[0],d=c[1],p=e.shapeInfo.flatOffset;if(d===a&&null==p)return t?`\\n      float ${s}(int row, int col, int depth) {\\n        int stride1 = ${r}Shape[2];\\n        float texR = float(row);\\n        float texC = dot(vec2(col, depth), vec2(stride1, 1));\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                   vec2(${r}TexShape[1], ${r}TexShape[0]);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n        float ${s}(int row, int col, int depth) {\\n          float texR = float(row);\\n          float texC = dot(vec2(col, depth), vec2(${i}, 1));\\n          vec2 uv = (vec2(texC, texR) + halfCR) /\\n                     vec2(${d}.0, ${h}.0);\\n          return sampleTexture(${r}, uv);\\n        }\\n      `;if(d===i&&null==p)return t?`\\n      float ${s}(int row, int col, int depth) {\\n        float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\\n        float texC = float(depth);\\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n    float ${s}(int row, int col, int depth) {\\n      float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\\n      float texC = float(depth);\\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${h}.0);\\n      return sampleTexture(${r}, uv);\\n    }\\n  `;const f=UD(r);return t?`\\n    float ${s}(int row, int col, int depth) {\\n      // Explicitly use integer operations as dot() only works on floats.\\n      int stride0 = ${r}Shape[1] * ${r}Shape[2];\\n      int stride1 = ${r}Shape[2];\\n      int index = row * stride0 + col * stride1 + depth + ${f};\\n      vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\\n      return sampleTexture(${r}, uv);\\n    }\\n    `:`\\n      float ${s}(int row, int col, int depth) {\\n        // Explicitly use integer operations as dot() only works on floats.\\n        int index = row * ${a} + col * ${i} + depth + ${f};\\n        vec2 uv = uvFromFlat(${h}, ${d}, index);\\n        return sampleTexture(${r}, uv);\\n      }\\n  `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],i=n[2]*a,o=n[1]*i,{newShape:u,keptDims:l}=ve(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\\n      ${OD(jD(e,u),t)}\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        return ${s}(${qD(n,l)});\\n      }\\n    `}if(e.shapeInfo.isUniform)return`\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        int index = round(dot(vec4(row, col, depth, depth2),\\n                          vec4(${o}, ${i}, ${a}, 1)));\\n        ${WD(e)}\\n      }\\n    `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],p=h[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(p===o&&null==c)return t?`\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        ${f}\\n        ${m}\\n        float texR = float(row);\\n        float texC =\\n            dot(vec3(col, depth, depth2),\\n                vec3(stride1, str
5057ide2, 1));\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                   vec2(${r}TexShape[1], ${r}TexShape[0]);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        float texR = float(row);\\n        float texC =\\n            dot(vec3(col, depth, depth2),\\n                vec3(${i}, ${a}, 1));\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                   vec2(${p}.0, ${d}.0);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `;if(p===a&&null==c)return t?`\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        float texR = dot(vec3(row, col, depth),\\n                         vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));\\n        float texC = float(depth2);\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                  vec2(${r}TexShape[1], ${r}TexShape[0]);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `:`\\n      float ${s}(int row, int col, int depth, int depth2) {\\n        float texR = dot(vec3(row, col, depth),\\n                         vec3(${n[1]*n[2]}, ${n[2]}, 1));\\n        float texC = float(depth2);\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                  vec2(${p}.0, ${d}.0);\\n        return sampleTexture(${r}, uv);\\n      }\\n    `;const y=UD(r);return t?`\\n    float ${s}(int row, int col, int depth, int depth2) {\\n      // Explicitly use integer operations as dot() only works on floats.\\n      ${f}\\n      ${m}\\n      ${g}\\n      int index = row * stride0 + col * stride1 +\\n          depth * stride2 + depth2;\\n      vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${y});\\n      return sampleTexture(${r}, uv);\\n    }\\n  `:`\\n    float ${s}(int row, int col, int depth, int depth2) {\\n      // Explicitly use integer operations as dot() only works on floats.\\n      int index = row * ${o} + col * ${i} +\\n          depth * ${a} + depth2;\\n      vec2 uv = uvFromFlat(${d}, ${p}, index + ${y});\\n      return sampleTexture(${r}, uv);\\n    }\\n  `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,i=t[2]*a,o=t[1]*i,{newShape:u,keptDims:l}=ve(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\\n      ${OD(jD(e,u))}\\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\\n        return ${r}(${qD(t,l)});\\n      }\\n    `}if(e.shapeInfo.isUniform)return`\\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\\n        float index = dot(\\n          vec4(row, col, depth, depth2),\\n          vec4(${o}, ${i}, ${a}, ${s})) +\\n          depth3;\\n        ${WD(e)}\\n      }\\n    `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],p=h[1];if(p===o&&null==c)return`\\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\\n        int texR = row;\\n        float texC = dot(vec4(col, depth, depth2, depth3),\\n                         vec4(${i}, ${a}, ${s}, 1));\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                   vec2(${p}.0, ${d}.0);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `;if(p===s&&null==c)return`\\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\\n        float texR = dot(\\n          vec4(row, col, depth, depth2),\\n          vec4(${t[1]*t[2]*t[3]},\\n               ${t[2]*t[3]}, ${t[3]}, 1));\\n        int texC = depth3;\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                  vec2(${p}.0, ${d}.0);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `;return`\\n    float ${r}(int row, int col, int depth, int depth2, int depth3) {\\n      // Explicitly use integer operations as dot() only works on floats.\\n      int index = row * ${o} + col * ${i} + depth * ${a} +\\n          depth2 * ${s} + depth3 + ${UD(n)};\\n      vec2 uv = uvFromFlat(${d}, ${p}, index);\\n      return sampleTexture(${n}, uv);\\n    }\\n  `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=ve(t);if(s.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\\n      ${OD(jD(e,s))}\\n      float ${r}(int row, int col, int depth,\\n                    int depth2, int depth3, int depth4) {\\n        return ${r}(${qD(t,a)});\\n      }\\n    `}const i=t[5],o=t[4]*i,u=t[3]*o,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\\n      float ${r}(int row, int col, int depth,\\n                  int depth2, int depth3, int depth4) {\\n        int index = round(dot(\\n          vec4(row, col, depth, depth2),\\n          vec4(${c}, ${l}, ${u}, ${o})) +\\n          dot(\\n            vec2(depth3, depth4),\\n            vec2(${i}, 1)));\\n        ${WD(e)}\\n      }\\n    `;const h=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],f=d[1];if(f===c&&null==h)return`\\n      float ${r}(int row, int col, int depth,\\n                    int depth2, int depth3, int depth4) {\\n        int texR = row;\\n        float texC = dot(vec4(col, depth, depth2, depth3),\\n          vec4(${l}, ${u}, ${o}, ${i})) +\\n               float(depth4);\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                   vec2(${f}.0, ${p}.0);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `;if(f===i&&null==h)return`\\n      float ${r}(int row, int col, int depth,\\n                    int depth2, int depth3, int depth4) {\\n        float texR = dot
5057(vec4(row, col, depth, depth2),\\n          vec4(${t[1]*t[2]*t[3]*t[4]},\\n               ${t[2]*t[3]*t[4]},\\n               ${t[3]*t[4]},\\n               ${t[4]})) + float(depth3);\\n        int texC = depth4;\\n        vec2 uv = (vec2(texC, texR) + halfCR) /\\n                  vec2(${f}.0, ${p}.0);\\n        return sampleTexture(${n}, uv);\\n      }\\n    `;return`\\n    float ${r}(int row, int col, int depth,\\n                  int depth2, int depth3, int depth4) {\\n      // Explicitly use integer operations as dot() only works on floats.\\n      int index = row * ${c} + col * ${l} + depth * ${u} +\\n          depth2 * ${o} + depth3 * ${i} + depth4 + ${UD(n)};\\n      vec2 uv = uvFromFlat(${p}, ${f}, index);\\n      return sampleTexture(${n}, uv);\\n    }\\n  `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function LD(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name;return`\\n    vec4 ${"get"+t.charAt(0).toUpperCase()+t.slice(1)}() {\\n      return ${$D().texture2D}(${t}, halfCR);\\n    }\\n  `}(e);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=$D();if(t)return`\\n    vec4 ${r}(int index) {\\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\\n      vec2 uv = packedUVfrom1D(\\n        packedTexShape[0], packedTexShape[1], index);\\n      return ${a.texture2D}(${n}, uv);\\n    }\\n  `;const i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`\\n    vec4 ${r}(int index) {\\n      vec2 uv = packedUVfrom1D(\\n        ${i[0]}, ${i[1]}, index);\\n      return ${a.texture2D}(${n}, uv);\\n    }\\n  `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,i=a[0],o=a[1],u=$D();if(null!=a&&de(n,a))return t?`\\n      vec4 ${s}(int row, int col) {\\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\\n\\n        return ${u.texture2D}(${r}, uv);\\n      }\\n    `:`\\n      vec4 ${s}(int row, int col) {\\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);\\n\\n        return ${u.texture2D}(${r}, uv);\\n      }\\n    `;if(t)return`\\n    vec4 ${s}(int row, int col) {\\n      ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\\n      int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\\n      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\\n      return ${u.texture2D}(${r}, uv);\\n    }\\n  `;const l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\\n    vec4 ${s}(int row, int col) {\\n      vec2 uv = packedUVfrom2D(${Math.ceil(n[1]/2)}, ${l[0]}, ${l[1]}, row, col);\\n      return ${u.texture2D}(${r}, uv);\\n    }\\n  `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){const r=[1,2],a=["b","row","col"];return`\\n        ${LD(jD(e,n.slice(1)),t)}\\n        vec4 ${s}(int b, int row, int col) {\\n          return ${s}(${qD(a,r)});\\n        }\\n      `}const o=$D();if(t)return`\\n    vec4 ${s}(int b, int row, int col) {\\n      ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\\n      int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\\n      int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\\n      vec2 uv = packedUVfrom3D(\\n        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\\n      return ${o.texture2D}(${r}, uv);\\n    }\\n  `;const u=i[0],l=i[1],c=Math.ceil(n[2]/2);return`\\n    vec4 ${s}(int b, int row, int col) {\\n      vec2 uv = packedUVfrom3D(\\n        ${u}, ${l}, ${c*Math.ceil(n[1]/2)}, ${c}, b, row, col);\\n      return ${o.texture2D}(${r}, uv);\\n    }\\n  `}(e,t);default:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=$D();if(t)return`\\n    vec4 ${r}(int b2, int b, int row, int col) {\\n      int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\\n      int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\\n      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\\n      texelsInBatch *= ${n}Shape[1];\\n      index = b2 * texelsInBatch + index;\\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\\n      int texR = index / packedTexShape[1];\\n      int texC = index - texR * packedTexShape[1];\\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);\\n    }\\n  `;const a=e.shapeInfo.logicalShape,i=a.length,o=e.shapeInfo.texShape,u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=u[0],c=u[1],h=Math.ceil(a[i-1]/2);let d=h*Math.ceil(a[i-2]/2),p="int b, int row, int col",f=`b * ${d} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<i-1;e++)p=`int b${e}, `+p,d*=a[i-e-1],f=`b${e} * ${d} + `+f;return`\\n    vec4 ${r}(${p}) {\\n      int index = ${f};\\n      int texR = index / ${c};\\n      int texC = index - texR * ${c};\\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\\n      return ${s.texture2D}(${n}, uv);\\n    }\\n  `}(e,t)}}const zD="\\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\\n  int texR = index / texNumC;\\n  int texC = index - texR * texNumC;\\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\\n}\\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\\n  int texelIndex = index / 2;\\n  int texR = texelIndex / texNumC;\\n  int texC = texelIndex - texR * texNumC;\\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\\n}\\n",PD="\\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\\n  int texNumC, int row, int col) {\\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\\n  int texR = texelIndex / texNumC;\\n  int texC = texelIndex - texR * texNumC;\\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\\n}\\n",BD="\\nvec2 packedUVfrom3D(int texNumR, int texNumC,\\n    int texelsInBatch, int texelsInLogicalRow, int b,\\n    int row, int col) {\\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\\n  int texR = index / texNumC;\\n  int texC = index - texR * texNumC;\\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\\n}\\n",VD="\\n  float getChannel(vec4 frag, vec2 innerDims) {\\n    vec2 modCoord = mod(innerDims, 2.);\\n    return modCoord.x == 0. ?\\n      (modCoord.y == 0. ? frag.r : frag.g) :\\n      (modCoord.y == 0. ? frag.b : frag.a);\\n  }\\n  float getChannel(vec4 frag, int dim) {\\n    float modCoord = mod(float(dim), 2.);\\n    return modCoord == 0. ? frag.r : frag.g;\\n  }\\n";function UD(e){return`offset${e}`}function WD(e){const t=e.name,n=le(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\\n    for (int i = 0; i < ${n}; i++) {\\n      if (i == index) {\\n        return ${t}[i];\\n      }\\n    }\\n  `}function GD(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}
vendor: 4,895 bytes, line 5057
5057function HD(e,t,n){const{newShape:r,keptDims:s}=ve(t),a=t.length,i=e&&3===a&&1===t[0],o=i?t.slice(1):r,u=!e&&a>1&&!de(t,n)&&r.length<a||i;return{useSqueezeShape:u,uniformShape:u?o:t,keptDims:s}}function jD(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function qD(e,t){return t.map(t=>e[t]).join(", ")}function KD(e,t,n){const r=[],s=[];let a,i,o,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===Xe().getNumber("WEBGL_VERSION")&&(u=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const s of t.variableNames){const a={name:s,uniform:e.getUniformLocation(n,s,c),offset:e.getUniformLocation(n,`offset${s}`,c)};t.enableShapeUniforms&&(a.shape=e.getUniformLocation(n,`${s}Shape`,c),a.texShape=e.getUniformLocation(n,`${s}TexShape`,c)),r.push(a)}if(t.enableShapeUniforms&&(a=e.getUniformLocation(n,"outShape",c),o=e.getUniformLocation(n,"outShapeStrides",c),i=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const r of t.customUniforms)s.push(e.getUniformLocation(n,r.name,c));return{variablesLocations:r,customUniformLocations:s,infLoc:u,nanLoc:l,outShapeLocation:a,outShapeStridesLocation:o,outTexShapeLocation:i}}function XD(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((e,n)=>{const r=e.logicalShape,s=t[n],a=s.shape;if(!de(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${a} must match`);if(e.isUniform&&s.isUniform)return;const i=e.texShape,o=s.isUniform?null:s.texData.texShape;if(!de(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)})}function YD(e){return Xe().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class JD{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=IF.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=$D();this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length),this.userCode=`\\n      ivec3 outCoordsFromFlatIndex(int index) {\\n        ${this.enableShapeUniforms?RD(["r","c","d"],e):AD(["r","c","d"],e)}\\n        return ivec3(r, c, d);\\n      }\\n\\n      void main() {\\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\\n\\n        vec4 result = vec4(0.);\\n\\n        for (int i=0; i<4; i++) {\\n          int flatIndex = index + i;\\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\\n          result[i] = getA(rc.x, rc.y, rc.z);\\n        }\\n\\n        ${t.output} = result;\\n      }\\n    `}}class ZD{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=IF.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=$D();this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length),this.userCode=`\\n      ivec3 outCoordsFromFlatIndex(int index) {\\n        ${this.enableShapeUniforms?RD(["r","c","d"],e):AD(["r","c","d"],e)}\\n        return ivec3(r, c, d);\\n      }\\n\\n      void main() {\\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\\n\\n        vec4 result = vec4(0.);\\n\\n        for (int i=0; i<4; i++) {\\n          int flatIndex = index + i;\\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\\n        }\\n\\n        ${t.output} = result;\\n      }\\n    `}}class QD{constructor(e){this.variableNames=["A"],this.outTexUsage=SF.DOWNLOAD;const t=$D();this.outputShape=e,this.userCode=`\\n      ${MD}\\n\\n      void main() {\\n        float x = getAAtOutCoords();\\n        ${t.output} = encode_float(x);\\n      }\\n    `}}class eO{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=SF.DOWNLOAD;const t=$D();this.outputShape=e,this.userCode=`\\n      ${MD}\\n\\n      void main() {\\n        ivec3 coords = getOutputCoords();\\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\\n        ${t.output} = encode_float(x);\\n      }\\n    `}}const tO={R:0,G:1,B:2,A:3};class nO{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=$D();this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)");let a="";for(let e=0;e<n.length;e++){const t=n[e];a+=`\\n          if(offset == ${e}) {\\n            result = values[${tO[t]}];\\n          }`}this.userCode=`\\n      ${this.enableShapeUniforms?"\\n  int getFlatIndex(ivec3 coords) {\\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\\n  }\\n":_D(e)}
5057\\n\\n      void main() {\\n        ivec3 coords = getOutputCoords();\\n        int flatIndex = getFlatIndex(coords);\\n        float result = 0.;\\n        int offset = imod(flatIndex, ${n.length});\\n\\n        flatIndex = idiv(flatIndex, ${n.length}, 1.);\\n\\n        int r = flatIndex / texShape[1];\\n        if (r < texShape[0]) {\\n          int c = imod(flatIndex, texShape[1]);\\n          vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\\n          vec4 values = ${r.texture2D}(A, uv);\\n          ${a}\\n        }\\n        ${r.output} = vec4(${s}, 0., 0., 0.);\\n      }\\n    `}}class rO{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=$D();this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let s=0;s<=1;s++){const a=2*t+s;r+=`\\n          localCoords = coords;\\n          if(localCoords[2] + ${s} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\\n          localCoords[2] += ${s};\\n          if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\\n            localCoords[1] += ${t};\\n\\n            flatIndex = getFlatIndex(localCoords);\\n            offset = imod(flatIndex, 4);\\n\\n            flatIndex = idiv(flatIndex, 4, 1.);\\n\\n            int r = flatIndex / texShape[1];\\n            int c = imod(flatIndex, texShape[1]);\\n            vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\\n            values = ${n.texture2D}(A, uv);\\n\\n            if (offset == 0) {\\n              result[${a}] = values[0];\\n            } else if (offset == 1) {\\n              result[${a}] = values[1];\\n            } else if (offset == 2) {\\n              result[${a}] = values[2];\\n            } else {\\n              result[${a}] = values[3];\\n            }\\n          }\\n        }\\n        `}this.userCode=`\\n        ${this.enableShapeUniforms?"\\n  int getFlatIndex(ivec3 coords) {\\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\\n  }\\n":_D(e)}\\n\\n        void main() {\\n          ivec3 coords = getOutputCoords();\\n\\n          vec4 result = vec4(0.);\\n          int flatIndex, r, c, offset;\\n          ivec3 localCoords;\\n          vec2 uv;\\n          vec4 values;\\n\\n          ${r}\\n\\n          ${n.output} = ${s};\\n        }\\n    `}}function sO(e){const t=$D();return OF(e,`${t.version}\\n    precision highp float;\\n    ${t.attribute} vec3 clipSpacePos;\\n    ${t.attribute} vec2 uv;\\n    ${t.varyingVs} vec2 resultUV;\\n\\n    void main() {\\n      gl_Position = vec4(clipSpacePos, 1);\\n      resultUV = uv;\\n    }`)}function aO(e){return WF(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function iO(e){return GF(e,new Uint16Array([0,1,2,2,1,3]))}function oO(e,t,n,r,s,a){qF(t,n);const i=jF(e),o=e.TEXTURE_2D;return AF(e,()=>e.bindTexture(o,i)),AF(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),AF(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),AF(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),AF(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),1===Xe().getNumber("WEBGL_VERSION")?AF(e,()=>e.texImage2D(o,0,r,t,n,0,s,a,null)):AF(e,()=>e.texStorage2D(o,1,r,t,n)),AF(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[n,t]}}function uO(e){return e.internalFormatFloat}function lO(e,t,n,r){const[s,a]=TF(t,n);return oO(e,s,a,uO(r),r.textureFormatFloat,e.FLOAT)}function cO(e){return e.internalFormatHalfFloat}function hO(e,t,n,r){const[s,a]=TF(t,n);return oO(e,s,a,cO(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function dO(e){return e.downloadTextureFormat}function pO(e,t,n,r){const[s,a]=TF(t,n);return oO(e,s,a,dO(r),e.RGBA,e.UNSIGNED_BYTE)}function fO(e){return e.internalFormatPackedFloat}function mO(e,t,n,r){const[s,a]=CF(t,n);return oO(e,s,a,fO(r),e.RGBA,e.FLOAT)}function gO(e){return e.internalFormatPackedHalfFloat}function yO(e,t,n,r){const[s,a]=CF(t,n);return oO(e,s,a,gO(r),e.RGBA,r.textureTypeHalfFloat)}function bO(e,t,n){return AF(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),XF(e,t,"clipSpacePos",n,3,20,0)&&XF(e,t,"uv",n,2,20,12)}function xO(e,t,n,r,s,a){let i,o,u;AF(e,()=>e.bindTexture(e.TEXTURE_2D,t)),s instanceof Uint8Array?(i=new Uint8Array(n*r*4),o=e.UNSIGNED_BYTE,u=e.RGBA):(i=new Float32Array(n*r*4),o=e.FLOAT,u=a.internalFormatPackedFloat),i.set(s),2===Xe().getNumber("WEBGL_VERSION")?AF(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,o,i)):AF(e,()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,o,i)),AF(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function wO(e,t,n){AF(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?2===Xe().getNumber("WEBGL_VERSION")?AF(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):AF(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):2===Xe().getNumber("WEBGL_VERSION")?AF(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):AF(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),AF(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function vO(e,t,n,r){const s=e.createBuffer();AF(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));const a=16*t*n;return AF(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),AF(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),AF(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function kO(e,t,n){const r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function IO(e,t,n,r){const[s,a]=TF(t,n),i=new Uint8Array(t*n*4);return AF(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function SO(e,t,n,r,s,a,i,o){const u=e,l=new Float32Array(function(e,t){const[n,r]=CF(e,t);return n*r*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function NO(e,t,n){const r=new Float32Array(t*n*4);return AF(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}class TO{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Xe().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,vF(t,e)):this.gl=kF(t),e=this.gl,2===Xe().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>AF(t,()=>t.createVertexArray()),this.bindVertexArray=e=>AF(t,()=>t.bindVertexArray(e)),this.deleteVertexArray=e=>AF(t,()=>t.deleteVertexArray(e)),this.getVertexArray=()=>AF(t,()=>t.getParameter(t.VERTEX_ARRAY_BINDING))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");
5057if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>AF(e,()=>t.createVertexArrayOES()),this.bindVertexArray=n=>AF(e,()=>t.bindVertexArrayOES(n)),this.deleteVertexArray=n=>AF(e,()=>t.deleteVertexArrayOES(n)),this.getVertexArray=()=>AF(e,()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Xe().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=DF(this.gl,e),vD(this.gl,t))this.textureHalfFloatExtension=DF(this.gl,t);else if(Xe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),vD(this.gl,r))this.colorBufferHalfFloatExtension=DF(this.gl,r);else if(Xe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",vD(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!vD(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=aO(this.gl),this.indexBuffer=iO(this.gl),this.framebuffer=KF(this.gl),this.textureConfig=$F(this.gl,this.textureHalfFloatExtension)}get debug(){return Xe().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;AF(e,()=>e.finish()),AF(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),AF(e,()=>e.deleteFramebuffer(this.framebuffer)),AF(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),AF(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),AF(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),lO(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),hO(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),pO(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),wO(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),xO(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),yO(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),mO(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(rD(this.gl,this.framebuffer),this.outputTexture=null),AF(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>IO(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,r,s,a){return SO(this.gl,e,0,0,0,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return kO(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=vO(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Xe().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,s=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(s,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=s}else Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>NO(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=sO(t));const n=BF(t);AF(t,()=>t.attachShader(n,this.vertexShader)),AF(t,()=>
5057t.attachShader(n,e)),VF(t,n);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&UF(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;AF(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),bO(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(AF(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&UF(this.gl,this.program),AF(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?ZF(this.gl,e,t):QF(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),AF(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),eD(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,s]=CF(t,n);this.setOutputMatrixTextureDriver(e,r,s)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&UF(this.gl,this.program),sD(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}AF(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),AF(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=DF(this.gl,2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await be(()=>this.disposed||this.isQueryAvailable(e,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=function(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map(e=>e.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Xe().platform&&(n=Xe().platform.setTimeoutCustom.bind(Xe().platform)),be(()=>(this.pollItems(),0===this.itemsToPoll.length),()=>0,null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),nD(this.gl,e,this.framebuffer),this.debug&&sD(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(nD(this.gl,this.outputTexture,this.framebuffer),this.debug&&sD(this.gl)):rD(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;nD(r,e,this.framebuffer),this.debug&&sD(r),this.outputTexture=e,AF(r,()=>r.viewport(0,0,t,n)),AF(r,()=>r.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),AF(this.gl,()=>this.gl.scissor(e,t,n,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:EO,bincountImpl:CO,bincountReduceImpl:$O,bitwiseAndImpl:AO,castImpl:RO,ceilImpl:_O,concatImpl:MO,equalImpl:FO,expImpl:DO,expm1Impl:OO,floorImpl:LO,gatherNdImpl:zO,gatherV2Impl:PO,greaterImpl:BO,greaterEqualImpl:VO,lessImpl:UO,lessEqualImpl:WO,linSpaceImpl:GO,logImpl:HO,maxImpl:jO,maximumImpl:qO,minimumImpl:KO,multiplyImpl:XO,negImpl:YO,notEqualImpl:JO,prodImpl:ZO,raggedGatherImpl:QO,raggedRangeImpl:eL,raggedTensorToTensorImpl:tL,rangeImpl:nL,rsqrtImpl:rL,scatterImpl:sL,sigmoidImpl:aL,simpleAbsImpl:iL,sliceImpl:oL,sparseFillEmptyRowsImpl:uL,sparseReshapeImpl:lL,sparseSegmentReductionImpl:cL,sqrtImpl:hL,staticRegexReplaceImpl:dL,stridedSliceImpl:pL,stringNGramsImpl:fL,stringSplitImpl:mL,stringToHashBucketFastImpl:gL,subImpl:yL,tileImpl:bL,topKImpl:xL,transposeImpl:wL,uniqueImpl:vL}=j;function kL(e,t){return["x","y","z","w","u","v"].slice(0,t).map(t=>`${e}.${t}`)}function IL(e,t){return 1===t?[e]:kL(e,t)}class SL{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=YD(this.outputShape.length),0===this.rank)this.userCode="\\n        void main() {\\n          setOutput(vec4(getA(), 0., 0., 0.));\\n        }\\n      ";else{const e=IL("rc",this.rank),t=GD(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),s=this.getOutput(e);this.userCode=`\\n        void main() {\\n          ${t} rc = getOutputCoords();\\n\\n          if(${n}) {\\n            setOutput(vec4(0));\\n          } else {\\n            ${r}\\n\\n            setOutput(vec4(${s}));\\n          }\\n        }\\n      `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t<this.rank;t++)s=`${e[e.length-1-t]},`+s;t.push(s)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\\n      int r = ${t[0]};\\n      int c = ${t[1]};\\n      int rp1 = r + 1;\\n      int cp1 = c + 1;\\n\\n      bool cEdge = cp1 >= ${n};\\n      bool rEdge = rp1 >= ${r};\\n    `}getOutput(e){const t=this.getSourceCoordsArr(e);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),\\n            cEdge ? 0. : getA(${t[1]}
5057),\\n            rEdge ? 0. : getA(${t[2]}),\\n            rEdge || cEdge ? 0. : getA(${t[3]})`}}class NL{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\\n        ${t}\\n        ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\\n          int flatIndex = getFlatIndex(thisRC);\\n\\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\\n\\n          result[${e}] =\\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\\n        ${e>0?"}":""}\\n      `}var r,s;this.userCode=`\\n      ${r=t,s=this.enableShapeUniforms,`\\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\\n      ${s?function(e,t,n="index"){const r=function(e,t){const n=e.length,r=e.map(e=>`${t}[${e}]`),s=new Array(n-1);s[n-2]=r[n-1];for(let e=n-3;e>=0;--e)s[e]=`(${s[e+1]} * ${r[e+1]})`;return s}(e.map((e,t)=>t),t);return r.map((t,s)=>`int ${e[s]} = ${n} / ${r[s]}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r[s]}`:`index -= ${e[s]} * ${r[s]}`};`).join("")}(["r","c","d"],"inputShape"):AD(["r","c","d"],r)}\\n      return ivec3(r, c, d);\\n    }\\n  `}\\n      ${this.enableShapeUniforms?"\\n  int getFlatIndex(ivec3 coords) {\\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\\n  }\\n":_D(e)}\\n\\n      void main() {\\n        ivec3 rc = getOutputCoords();\\n\\n        vec4 result = vec4(0.);\\n\\n        ivec3 thisRC;\\n        int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\\n        int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\\n\\n        ${n}\\n\\n        setOutput(result);\\n      }\\n    `}}class TL{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){const r=CL(t,n),s=$L(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);const a=EL(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[s].pop();return this.usedTextures[s].push(e),e}let i;return r===NF.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===NF.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===NF.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===NF.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===NF.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const s=CL(n,r),a=$L(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);const i=EL(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),o=Xe().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const u=this.usedTextures[a],l=u&&u.indexOf(e);if(null==l||l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[l]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach(e
vendor: 4,782 bytes, line 5057
5057=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(const e in this.usedTextures)this.usedTextures[e].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function EL(e,t,n,r,s){const a=function(e,t){switch(e){case NF.PACKED_2X2_FLOAT32:return fO(t);case NF.PACKED_2X2_FLOAT16:return gO(t);case NF.UNPACKED_FLOAT32:return uO(t);case NF.UNPACKED_FLOAT16:return cO(t);case NF.PACKED_4X1_UNSIGNED_BYTE:return dO(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let i;if(s){const[t,n]=CF(e[0],e[1]);i=t*n}else{const[t,n]=TF(e[0],e[1]);i=t*n}const o=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,a);return i*o}function CL(e,t){if(e===SF.UPLOAD)return NF.PACKED_2X2_FLOAT32;if(e===SF.RENDER||null==e)return function(e){return Xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?NF.PACKED_2X2_FLOAT32:NF.UNPACKED_FLOAT32:e?NF.PACKED_2X2_FLOAT16:NF.UNPACKED_FLOAT16}(t);if(e===SF.DOWNLOAD||e===SF.PIXELS)return NF.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function $L(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class AL{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length),this.userCode=`\\n      float unaryOperation(float x) {\\n        ${t}\\n      }\\n\\n      void main() {\\n        float x = getAAtOutCoords();\\n        float y = unaryOperation(x);\\n\\n        setOutput(y);\\n      }\\n    `}}const RL="if (isnan(x)) return x;",_L="return abs(x);",ML=RL+"\\n  return (x < 0.0) ? 0.0 : x;\\n",FL=RL+"\\n  return (x < 0.0) ? 0.0 : min(6.0, x);\\n",DL="return x;";class OL{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length),this.userCode=`\\n      vec4 unaryOperation(vec4 x) {\\n        ${t}\\n      }\\n\\n      void main() {\\n        vec4 x = getAAtOutCoords();\\n        vec4 y = unaryOperation(x);\\n\\n        setOutput(y);\\n      }\\n    `}}class LL{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length);const t=e.length,n=IL("rc",t),r=GD(t),s=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),a=n.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`\\n      void main() {\\n        ${r} rc = getOutputCoords();\\n        vec4 packedInput = getA(${s});\\n\\n        setOutput(getChannel(packedInput, ${i}));\\n      }\\n    `}}const zL=yp,PL={},BL=Xe().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class VL extends Y{nextDataId(){return VL.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Xe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof TO)t=e;else{const n=kF(Xe().getNumber("WEBGL_VERSION"),e);t=new TO(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=kF(Xe().getNumber("WEBGL_VERSION"));t=new TO(e),this.binaryCache=((n=Xe().getNumber("WEBGL_VERSION"))in PL||(PL[n]={}),PL[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new TL(this.gpgpu),this.numMBBeforeWarning=null==Xe().global.screen?1024:Xe().global.screen.height*Xe().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new X(this,ai())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,s,a){const i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[r,s]},o.texShape=[r,s];const u=cD(t),l=new nO(u,!1,a),c=this.runWebGLProgram(l,[i],n,[[r,s]]);return c.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,n){if((Xe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Xe().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:SF.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}
5057move(e,t,n,r,s){if(Xe().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:SF.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:i,isPacked:o}=t;if(null!=a){let t;t=o?new OL(i,DL):new AL(i,DL);const n=this.runWebGLProgram(t,[{dataId:e,shape:i,dtype:r}],r),s=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),s}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;return u&&(l=Xs()),c="complex64"===r?dm(this.readSync(s.real.dataId),this.readSync(s.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=Xs()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise(e=>t.push(e))}const t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=s){let t;t=o?new OL(r,DL):new AL(r,DL);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:a}],a),s=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),s}if(null!=n)return this.convertAndCacheOnCPU(e);if(Xe().getBool("DEBUG")&&!Xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Xe().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==a&&Xe().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...EF(r))}if(this.pendingRead.set(e,[]),"complex64"!==a&&await this.gpgpu.createAndWaitForFence(),"complex64"===a){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);l=dm(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=le(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;AF(e,()=>e.deleteBuffer(c))}const h=this.convertAndCacheOnCPU(e,l),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(e=>e(h)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&ai().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:s,slice:a,dtype:i,isPacked:o,texture:u}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=a){let n;n=o?new OL(s,DL):new AL(s,DL);const r=this.runWebGLProgram(n,[{dataId:e,shape:s,dtype:i}],i),a=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),a}if(null==u)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),c=ai().makeTensorFromTensorInfo(l),h=this.texData.get(l.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map(e=>Zs(e));return ko(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return ko(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!MF(n)){if(Xe().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: \'tf.env().set(\'WEBGL_RENDER_FLOAT32_ENABLED\', true);\'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),s=le(t);if(Xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),a=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...EF(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(n),a}const a=Xe().getBool("WEBGL_PACK")&&!0===r,i=a?cD(t):t,o=a?new eO(i):new QD(i),u=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const s=ea(this.activeTimers.map(e=>e.query)).filter(e=>null!=e),a=ea(this.activeTimers.map(e=>e.name)).filter(e=>null!=e);this.activeTimers=t,r&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>
vendor: 14,544 bytes, line 5057
5057{if(Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(s);i.kernelMs=re(e),i.getExtraProfileInfo=()=>e.map((e,t)=>({name:a[t],ms:e})).map(e=>`${e.name}: ${e.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Xs(),endMs:null}}endTimer(e){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Xs(),e)}async getQueryTime(e){if(Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:s,isPacked:a,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,u=this.dataRefCount.get(o);u>1?this.dataRefCount.set(o,u-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,s,a)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=BL){return Xe().getBool("WEBGL_CPU_FORWARD")&&e.every(e=>null==this.texData.get(e.dataId).texture&&le(e.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){xs("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return zL(e.shape,t)}packedUnaryOp(e,t,n){const r=new OL(e.shape,t),s=this.compileAndRun(r,[e],n);return ai().makeTensorFromTensorInfo(s)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=iL(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_L,e.dtype);const t=new AL(e.shape,_L),n=this.compileAndRun(t,[e]);return ai().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&$e(n[0])){const s=n.map(e=>Js(e));r=this.write(s,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return ai().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new LL(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new SL(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[uD(e.shape),...lD(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[uD(t),...lD(t)],a=new NL(s,n),i=[n],o=this.runWebGLProgram(a,[r],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:s,dtype:a}=n;null!=t&&ie(le(s)<=t[0]*t[1]*4,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");const i=cD(s);let o;o=r?new ZD(i):new JD(i);const u=[null!=t?t:EF(i)];return{dtype:a,shape:s,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,u,!0,t).dataId}}runWebGLProgram(e,t,n,r,s=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===IF.DENSE){const t=null!=a?a:EF(e.outputShape);o.texShape=t.map(e=>2*e)}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===le(i.shape))return o.values=ke(i.dtype,0),i;const u=[],l=t.map(t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&le(t.shape)<=Xe().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!pD(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),u.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}});this.uploadToGPU(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},h=function(e,t,n){let r="";t.concat(n).forEach(t=>{const s=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const a=t.texData.texShape,{useSqueezeShape:i,uniformShape:o,keptDims:u}=HD(e.packedInputs,t.shape,a);let l="",c="",h="";if(1===o.length&&e.packedInputs){const e=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=De(o);h=`${e[0]===a[1]}_${e[e.length-1]===a[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const d=t.shape.length,p=2===o.length&&de(t.shape,a),f=1===le(t.shape),m=tu(t.shape,n.shape),g=!e.packedInputs&&d===n.shape.length&&de(a,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;r+=`${d}_${g}_${i?u:""}_${o.length}_${f}_${m}_${p}_${l}_${c}_${h}_${y}_${s}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${s}`}});const s=e.userCode;let a=e.constructor.name;return a+="_"+r+"_"+s+`${Xe().getNumber("WEBGL_VERSION")}`,a}(e,l,c),d=this.getAndSaveBinary(h,()=>function(e,t,n,r){const s=n.map((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}}),a=s.map(e=>e.shapeInfo),i={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},o=DD(s,i,t),u=LF(e.gl,o),l=e.createProgram(u);return Xe().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:a,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(l),Object.assign({program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:a,outShapeInfo:i},KD(e,t,l)))}(this.gpgpu,e,l,c)),p=null!=this.activeTimers;let f;p&&(f=this.startTimer()),Xe().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,s){t.program.enableShapeUniforms||(XD(t.inShapeInfos,n),XD([t.outShapeInfo],[r]));const a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===Xe().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let r=0;r<n.length;++r){const s=n[r],{uniform:a,offset:i,shape:o,texShape:u}=t.variablesLocations[r];if(o){const{uniformShape:n}=HD(t.program.packedInputs,s.shape,s.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(o,new Int32Array(n));break;case 2:e.gl.uniform2iv(o,new Int32Array(n));break;case 3:e.gl.uniform3iv(o,new Int32Array(n));break;case 4:e.gl.uniform4iv(o,new Int32Array(n))}}if(u&&e.gl.uniform2i(u,s.texData.texShape[0],s.texData.texShape[1]),null!=a)if(s.isUniform)if(le(s.shape)<2)e.gl.uniform1f(a,s.uniformValues[0]);else{let t=s.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=s.texData.slice&&null!=i&&e.gl.uniform1i(i,s.texData.slice.flatOffset),e.setInputMatrixTexture(s.texData.texture.texture,a,r)}const o=t.outShapeLocation;if(o)switch(r.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=De(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&s)for(let n=0;n<t.program.customUniforms.length;++n){const r=t.program.customUniforms[n],a=t.customUniformLocations[n],i=s[n];if("float"===r.type)e.gl.uniform1fv(a,i);else if("vec2"===r.type)e.gl.uniform2fv(a,i);else if("vec3"===r.type)e.gl.uniform3fv(a,i);else if("vec4"===r.type)e.gl.uniform4fv(a,i);else if("int"===r.type)e.gl.uniform1iv(a,i);else if("ivec2"===r.type)e.gl.uniform2iv(a,i);else if("ivec3"===r.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==r.type)throw Error(`uniform type ${r.type} is not supported yet.`);e.gl.uniform4iv(a,i)}}e.executeProgram()}(this.gpgpu,d,l,c,r),u.forEach(e=>this.disposeIntermediateTensorInfo(e)),p&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=Xe().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Xs();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Xe().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===s){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,r,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Xe().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=ui(()=>{if(!Xe().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Xe().getBool("DEBUG");Xe().set("DEBUG",!1);const t=this.abs(Bo(1e-8)).dataSync()[0];if(Xe().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:s,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const u=null!=this.activeTimers;let l;u&&(l=Xs());let c=t.texShape;if(null==c&&(c=hD(n,o),t.texShape=c),null!=s){const e=cD(n);let a,i=c[1],h=c[0];const d=s instanceof Uint8Array||s instanceof Uint8ClampedArray;!o&&d||([i,h]=CF(c[0],c[1])),a=o?new rO(e,d):new nO(e,d);const p=d?[h,i]:c,f=this.makeTensorInfo(p,r),m=this.texData.get(f.dataId);m.usage=d?SF.PIXELS:SF.UPLOAD,m.texShape=p,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,s);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],r,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,Xe().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=Xs()-l)}else{const e=this.acquireTexture(c,i,r,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*Ee(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise(e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}});e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await Uf(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw PF(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:r,nanLoc:s,outShapeLocation:a,outShapeStridesLocation:i,outTexShapeLocation:o}=KD(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=s,e.outShapeLocation=a,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:s,width:a,channels:i}=e,o=ai().backend;if(!o.gpgpu.gl.isTexture(r))throw new Error("The texture is invali
5057d. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through \'new tf.MathBackendWebGL(customCanvas)\'.");const u=o.writeTexture(r,t,n,s,a,i);return ai().makeTensorFromDataId(u,t,n,o)}}VL.nextDataId=0;const UL="4.22.0";function WL(){Xe().set("WEBGL_FORCE_F16_TEXTURES",!0)}Ba()&&bi("webgl",()=>new VL,2);const GL={forceHalfFloat:WL},HL="\\n  if (isnan(a)) return a;\\n  if (isnan(b)) return b;\\n";class jL{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=ru(t,n),this.enableShapeUniforms=YD(this.outputShape.length),this.userCode=`\\n      float binaryOperation(float a, float b) {\\n        ${e}\\n      }\\n\\n      void main() {\\n        float a = getAAtOutCoords();\\n        float b = getBAtOutCoords();\\n        setOutput(binaryOperation(a, b));\\n      }\\n    `}}const qL="\\n  result.r = isNaN.r ? NAN : result.r;\\n  result.g = isNaN.g ? NAN : result.g;\\n  result.b = isNaN.b ? NAN : result.b;\\n  result.a = isNaN.a ? NAN : result.a;\\n";class KL{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ru(t,n);const s=this.outputShape.length;this.enableShapeUniforms=YD(s);let a="";if(r)if(0===s||1===le(this.outputShape))a="\\n          result.y = 0.;\\n          result.z = 0.;\\n          result.w = 0.;\\n        ";else if(a=`\\n          ${GD(s)} coords = getOutputCoords();\\n        `,1===s)this.enableShapeUniforms?a+="\\n            result.y = (coords + 1) >= outShape ? 0. : result.y;\\n            result.z = 0.;\\n            result.w = 0.;\\n          ":a+=`\\n            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\\n            result.z = 0.;\\n            result.w = 0.;\\n          `;else{const e=IL("coords",s);this.enableShapeUniforms?a+=`\\n            bool nextRowOutOfBounds =\\n              (${e[s-2]} + 1) >= outShape[${s} - 2];\\n            bool nextColOutOfBounds =\\n              (${e[s-1]} + 1) >= outShape[${s} - 1];\\n            result.y = nextColOutOfBounds ? 0. : result.y;\\n            result.z = nextRowOutOfBounds ? 0. : result.z;\\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\\n          `:a+=`\\n            bool nextRowOutOfBounds =\\n              (${e[s-2]} + 1) >= ${this.outputShape[s-2]};\\n            bool nextColOutOfBounds =\\n              (${e[s-1]} + 1) >= ${this.outputShape[s-1]};\\n            result.y = nextColOutOfBounds ? 0. : result.y;\\n            result.z = nextRowOutOfBounds ? 0. : result.z;\\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\\n          `}this.userCode=`\\n      vec4 binaryOperation(vec4 a, vec4 b) {\\n        ${e}\\n      }\\n\\n      void main() {\\n        vec4 a = getAAtOutCoords();\\n        vec4 b = getBAtOutCoords();\\n\\n        vec4 result = binaryOperation(a, b);\\n        ${a}\\n\\n        setOutput(result);\\n      }\\n    `}}function XL(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const YL={kernelName:yn,backendName:"webgl",kernelFunc:XL};function JL(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),i=n.texData.get(a.dataId),o=XL({inputs:{x:r},backend:n}),u=XL({inputs:{x:s},backend:n});return i.complexTensorInfos={real:o,imag:u},a}const ZL={kernelName:Et,backendName:"webgl",kernelFunc:JL},QL="return (a < 0.) ? b * a : a;",ez="\\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
5057\\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\\n",tz={kernelName:In,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,i=n.makeTensorInfo([],"float32",qs(a,"float32")),o=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new KL(ez,s.shape,i.shape):new jL(QL,s.shape,i.shape),u=n.runWebGLProgram(o,[s,i],"float32");return n.disposeIntermediateTensorInfo(i),u}},nz="return (a < 0.) ? b * a : a;",rz="\\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\\n",sz={kernelName:lr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new KL(rz,r.shape,s.shape):new jL(nz,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}},az="if (isnan(x)) return x;";function iz({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{const{x:i}=s,o=a,u=r||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,u);return o.makeTensorInfo(i.shape,u,t)}let l;return l=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new OL(i.shape,t):new AL(i.shape,e),o.runWebGLProgram(l,[i],u)}}function oz({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:i,backend:o})=>{const{a:u,b:l}=i,c=o;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,s]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map(t=>{const[n,r]=t,s={dataId:n.dataId,dtype:n.dtype,shape:u.shape},a={dataId:r.dataId,dtype:r.dtype,shape:l.shape},i=new jL(e,u.shape,l.shape);return c.runWebGLProgram(i,[s,a],ka(n.dtype,r.dtype))}),a=JL({inputs:{real:r,imag:s},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(s),a}const h=a||ka(u.dtype,l.dtype);if(("string"===u.dtype||"string"===l.dtype||c.shouldExecuteOnCPU([u,l]))&&null!=s){const e=c.texData.get(u.dataId).values,t=c.texData.get(l.dataId).values,n="string"===u.dtype?jm(e):e,r="string"===u.dtype?jm(t):t,[a,i]=s(u.shape,l.shape,n,r,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let d;return d=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new KL(t,u.shape,l.shape,n):new jL(e,u.shape,l.shape),c.runWebGLProgram(d,[u,l],h)}}function uz(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n":ML;if("elu"===e)return t?"\\n  vec4 result;\\n\\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\\n\\n  return result;\\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n":FL;if("prelu"===e)return t?rz:nz;if("leakyrelu"===e)return t?ez:QL;if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class lz{constructor(e,t,n,r=!1,s=!1,a=!1,i=null,o=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=YD(this.outputShape.length);const l=r?e[1]:e[2],c=Math.ceil(l/2),h=r?"i * 2, rc.y":"rc.y, i * 2",d=s?"rc.z, i * 2":"i * 2, rc.z",p=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\\n          vec4 b = getPreluActivationWeightsAtOutCoords();\\n          ${i}\\n        }`:u?`vec4 activation(vec4 a) {\\n          vec4 b = getLeakyreluAlphaAtOutCoords();\\n          ${i}\\n        }`:`vec4 activation(vec4 x) {\\n          ${i}\\n        }`,g="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`\\n      ${m}\\n      // Don\'t use uniform for sharedDimensionPacked for performance.\\n      const float sharedDimension = ${c}.0;\\n\\n      vec4 dot2x2ARowBCol(ivec3 rc) {\\n        vec4 result = vec4(0);\\n        int batchA = ${b};\\n        int batchB = ${x};\\n        for (int i = 0; i < ${c}; i++) {\\n          vec4 a = getMatrixA(batchA, ${h});\\n          vec4 b = getMatrixB(batchB, ${d});\\n\\n          // These swizzled products need to be separately added.\\n          // See: https://github.com/tensorflow/tfjs/issues/1735\\n          result += (${p[0]} * ${f[0]});\\n          result += (${p[1]} * ${f[1]});\\n        }\\n        return result;\\n      }\\n\\n      void main() {\\n        ivec3 rc = getOutputCoords();
5057\\n        vec4 result = dot2x2ARowBCol(rc);\\n\\n        ${y}\\n\\n        ${g}\\n\\n        setOutput(result);\\n      }\\n    `}}class cz{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ru(t,n),this.userCode=`\\n      float binaryOpComplex(\\n          float areal, float aimag, float breal, float bimag) {\\n        ${e}\\n      }\\n\\n      void main() {\\n        float areal = getARealAtOutCoords();\\n        float aimag = getAImagAtOutCoords();\\n        float breal = getBRealAtOutCoords();\\n        float bimag = getBImagAtOutCoords();\\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\\n      }\\n    `}}const hz="return a * b;";function dz(e){const{inputs:t,backend:n}=e,{a:r,b:s}=t,a=ka(r.dtype,s.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(s.dataId),a=new cz("return areal * breal - aimag * bimag;",r.shape,s.shape),i=new cz("return areal * bimag + aimag * breal;",r.shape,s.shape),o=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:s.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:s.shape}],u=n.runWebGLProgram(a,o,"float32"),l=n.runWebGLProgram(i,o,"float32"),c=JL({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,s])){const e=n.texData.get(r.dataId),t=n.texData.get(s.dataId),[i,o]=XO(r.shape,s.shape,e.values,t.values,a),u=n.makeTensorInfo(o,a);return n.texData.get(u.dataId).values=i,u}let i;return i=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new KL(hz,r.shape,s.shape):new jL(hz,r.shape,s.shape),n.runWebGLProgram(i,[r,s],a)}const pz={kernelName:Jn,backendName:"webgl",kernelFunc:dz};function fz(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,i=n,o=le(s.shape),u=xe(a,o),l=le(u);ie(o===l,()=>`The new shape (${u}) has ${l} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);const c=i.texData.get(s.dataId);return!c.isPacked||pD(s.shape,u)||null!==c.texture&&pD(c.shape,u)?(i.incRef(s.dataId),{dataId:s.dataId,shape:u,dtype:s.dtype}):function(e,t,n){const r=[uD(e.shape),...lD(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[uD(t),...lD(t)],i=new NL(a,r),o=[r],u=n.runWebGLProgram(i,[s],e.dtype,o,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(s,u,i)}const mz={kernelName:br,backendName:"webgl",kernelFunc:fz};class gz{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];const i=4*Math.floor(n/4),o=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${pe(e)?e.toPrecision(2):e}, ones);`}let l="";s%n>0&&(l=`\\n        if (inIdx < 0 || inIdx >= ${s}) {\\n          return 0.0;\\n        }\\n      `),this.userCode=`\\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\\n\\n      float getValue(int batch, int inIdx) {\\n        ${l}\\n        return getX(batch, inIdx);\\n      }\\n\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int outIdx = coords[1];\\n        int inOffset = outIdx * ${n};\\n\\n        float sumValue = 0.0;\\n\\n        for (int i = 0; i < ${i}; i += 4) {\\n          int inIdx = inOffset + i;\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2),\\n            getValue(batch, inIdx + 3)\\n          );\\n\\n          ${u}\\n        }\\n\\n        int inIdx = inOffset + ${i};\\n        if (${1===o}) {\\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\\n\\n          ${u}\\n        } else if (${2===o}) {\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1), 0.0, 0.0);\\n\\n          ${u}\\n        } else if (${3===o}) {\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2), 0.0);\\n\\n          ${u}\\n        }\\n        setOutput(sumValue);\\n      }\\n    `}}class yz{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let h=`\\n      if (${"sum"===t}) {\\n        sumValue += dot(values, ones);\\n      } else if (${"prod"===t}) {\\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\\n        prodValue *= tmp[0] * tmp[1];\\n      } else {\\n        minMaxValue = ${o}(values, minMaxValue);\\n        if (${"min"===t} || ${"max"===t}) {\\n          minMaxValue = ${o}(values, minMaxValue);\\n          bvec4 isNaN = isnan(values);\\n          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\\n            minMaxValue = vec4(NAN);\\n          }\\n        }\\n      }\\n    `,d="vec4";"all"===t?(i="1.0",h="\\n        bool reducedAllValue = all(values);\\n        float floatedReducedAllValue = float(reducedAllValue);\\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\\n      ",d="bvec4"):"any"===t&&(i="0.0",h="\\n        bool reducedAnyValue = any(values);\\n        float floatedReducedAnyValue = float(reducedAnyValue);\\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\\n      ",d="bvec4");let p="";s%n>0&&(p=`\\n        if (inIdx < 0 || inIdx >= ${s}) {\\n          return initializationValue;\\n        }\\n      `),this.userCode=`\\n      const float initializationValue = ${i};\\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\\n\\n      float getValue(int batch, int inIdx) {\\n        ${p}\\n        return getX(batch, inIdx);\\n      }\\n\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int outIdx = coords[1];\\n        int inOffset = outIdx * ${n};\\n\\n        vec4 minMaxValue = vec4(${i});\\n        float prodValue = 1.0;\\n        float sumValue = 0.0;\\n        float allValue = 1.0;\\n        float anyValue = 0.0;\\n\\n        for (int i = 0; i < ${l}; i += 4) {\\n          int inIdx = inOffset + i;\\n          ${d} values = ${d}(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2),\\n            getValue(batch, inIdx + 3)\\n          );\\n\\n          ${h}\\n        }\\n\\n        int inIdx = inOffset + ${l};\\n        if (${1===c}) {\\n          ${d} values = ${d}(\\n            getValue(batch, inIdx),\\n            initializationValue,\\n            initializationValue,\\n            initializationValue\\n          );\\n\\n          ${h}\\n        } else if (${2===c}) {\\n          ${d} values = ${d}(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            initializationValue,\\n            initializationValue\\n          );\\n\\n          ${h}\\n        } else if (${3===c}) {\\n          ${d} values = ${d}(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2),\\n            initializationValue\\n          );\\n\\n          ${h}\\n        }\\n        setOutput(${u});\\n      }\\n    `}}function bz(e,t,n,r){const s=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=Jf(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let a=e;for(let i=0;i<s.length;i++){const{inSize:o,windowSize:u,outSize:l}=s[i];let c,h;c="mean"===n?0===i?new gz({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l}
vendor: 5,837 bytes, line 5057
5057,o):new gz({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l}):new yz({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l},n),h=a,a=r.runWebGLProgram(c,[a],t),h.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(h)}return a}class xz{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;const r=GD(this.rank),s=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t<e.length;t++)r[e[t]]=n[t];return r.join()}(t);this.userCode=`\\n    void main() {\\n      ${r} resRC = getOutputCoords();\\n      setOutput(getA(${s}));\\n    }\\n    `}}class wz{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=GD(this.rank),s=kL("rc",this.rank),a=new Array(this.rank);for(let e=0;e<t.length;e++)a[t[e]]=s[e];const i=`vec2(${a.slice(-2).join()})`,o=`++${s[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`\\n    void main() {\\n      ${r} rc = getOutputCoords();\\n      vec4 result = vec4(0.);\\n      result[0] = ${u};\\n      if(${o}) {\\n        result[1] = ${u};\\n      }\\n      --${s[this.rank-1]};\\n      if(++${s[this.rank-2]} < ${n[this.rank-2]}) {\\n        result[2] = ${u};\\n        if(${o}) {\\n          result[3] = ${u};\\n        }\\n      }\\n      setOutput(result);\\n    }\\n    `}}function vz(e,t,n){const r=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new wz(e.shape,t):new xz(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function kz(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;return function(e,t,n,r){const s=t,a=e.shape.length,i=we(s,e.shape);let o=i;const u=nh(o,a),l=null!=u;let c=e;l&&(c=vz(e,u,r),o=sh(o.length,a)),th("sum",o,a);const[h,d]=Qc(c.shape,o);let p=h;n&&(p=eh(h,i));const f=le(d),m=fz({inputs:{x:c},attrs:{shape:[le(e.shape)/f,f]},backend:r}),g=bz(m,Ia(e.dtype),"sum",r),y=fz({inputs:{x:g},attrs:{shape:p},backend:r});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),l&&r.disposeIntermediateTensorInfo(c),y}(s,a,i,n)}const Iz={kernelName:Pr,backendName:"webgl",kernelFunc:kz};function Sz(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,i=n,o=s.shape.length,u=new Array(o);for(let e=0;e<u.length;e++)u[e]=s.shape[a[e]];let l;if(i.shouldExecuteOnCPU([s])){const e=i.texData.get(s.dataId).values,t=wL(e,s.shape,s.dtype,a,u);l=i.makeTensorInfo(u,s.dtype),i.texData.get(l.dataId).values=t}else l=vz(s,a,i);return l}const Nz={kernelName:os,backendName:"webgl",kernelFunc:Sz};function Tz({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:u=null}){const l=e.shape.length,c=t.shape.length,h=n?e.shape[l-2]:e.shape[l-1],d=r?t.shape[c-1]:t.shape[c-2],p=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=le(m),b=le(g),x=ru(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([p,f]);ie(h===d,()=>`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);const w=n?[y,h,p]:[y,p,h],v=r?[b,f,d]:[b,d,f],k=fz({inputs:{x:e},backend:s,attrs:{shape:w}}),I=fz({inputs:{x:t},backend:s,attrs:{shape:v}}),S=[k,I],N=Math.max(y,b),T=n?k.shape[1]:k.shape[2],E=null!=a,C=null!=i,$="leakyrelu"===u,A=null!=u?uz(u,!0):null;let R;if((1===p||1===f)&&T>1e3&&!1===(E||C||$||null!=A)){let e=k,t=I;n&&(e=Sz({inputs:{x:k},backend:s,attrs:{perm:[0,2,1]}}),S.push(e)),r&&(t=Sz({inputs:{x:I},backend:s,attrs:{perm:[0,2,1]}}),S.push(t));const a=1===f;let i=e;1!==f&&(i=fz({inputs:{x:e},backend:s,attrs:{shape:[N,T,1]}}),S.push(i));const o=1===f?2:1;let u=t;a&&(u=fz({inputs:{x:t},backend:s,attrs:{shape:[N,1,T]}}),S.push(u));const l=dz({inputs:{a:i,b:u},backend:s});R=kz({inputs:{x:l},backend:s,attrs:{axis:o,keepDims:!0}}),S.push(l)}else{const u=ka(e.dtype,t.dtype),l=new lz(w,v,[N,p,f],n,r,E,A,C,$),c=[k,I];if(null!=a&&c.push(a),C&&c.push(i),$){const e=s.makeTensorInfo([],"float32",qs(o,"float32"));c.push(e),S.push(e)}R=s.runWebGLProgram(l,c,u)}const _=fz({inputs:{x:R},backend:s,attrs:{shape:x}});S.push(R);for(const e of S)s.disposeIntermediateTensorInfo(e);return _}const Ez={kernelName:gs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:h}=r;return Tz({a:s,b:a,transposeA:u,transposeB:l,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},Cz="return abs(x);",$z={kernelName:et,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&"complex64"!==r.dtype){const e=n.texData.get(r.dataId),t=iL(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let s;return s=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new OL(r.shape,Cz):new AL(r.shape,Cz),n.runWebGLProgram(s,[r],r.dtype)}},Az=iz({opSnippet:RL+"\\n  if (abs(x) > 1.) {\\n    return NAN;\\n  }\\n  return acos(x);\\n"}),Rz={kernelName:tt,backendName:"webgl",kernelFunc:Az},_z=iz({opSnippet:RL+"\\n  if (x < 1.0) return NAN;\\nreturn log(x + sqrt(x * x - 1.0));"}),Mz={kernelName:nt,backendName:"webgl",kernelFunc:_z},Fz="return a + b;",Dz=oz({opSnippet:Fz,packedOpSnippet:Fz,supportsComplex:!0,cpuKernelImpl:EO}),Oz={kernelName:rt,backendName:"webgl",kernelFunc:Dz};class Lz{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((e,t)=>`T${t}`);const n=[];
5057this.variableNames.forEach(e=>{n.push(`float v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>`v${e}`).join(" + ");this.userCode=`\\n      void main() {\\n        ${n.join("\\n        ")}\\n\\n        float result = ${r};\\n        setOutput(result);\\n      }\\n    `}}class zz{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((e,t)=>`T${t}`);const n=[];this.variableNames.forEach(e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>`v${e}`).join(" + ");this.userCode=`\\n      void main() {\\n        ${n.join("\\n        ")}\\n\\n        vec4 result = ${r};\\n        setOutput(result);\\n      }\\n    `}}const Pz={kernelName:st,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,s=n;if(1===s.length)return XL({inputs:{x:s[0]},backend:r});if(s.length>Xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(s.length/2),n=e({inputs:s.slice(0,t),backend:r}),a=e({inputs:s.slice(t),backend:r});return e({inputs:[n,a],backend:r})}const a=s.map(e=>e.dtype).reduce((e,t)=>ka(e,t)),i=s.map(e=>e.shape),o=Xe().getBool("WEBGL_PACK")?new zz(s[0].shape,i):new Lz(s[0].shape,i);return r.runWebGLProgram(o,s,a)}},Bz={kernelName:at,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=nh(l,o);let h=s;null!=c&&(h=Sz({inputs:{x:s},backend:n,attrs:{perm:c}}),l=sh(l.length,o)),th("all",l,o);const[d,p]=Qc(h.shape,l),f=fz({inputs:{x:h},backend:n,attrs:{shape:[-1,le(p)]}}),m=bz(f,f.dtype,"all",n);let g;return g=fz(i?{inputs:{x:m},backend:n,attrs:{shape:eh(d,u)}}:{inputs:{x:m},backend:n,attrs:{shape:d}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},Vz={kernelName:it,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=nh(l,o);let h=s;null!=c&&(h=Sz({inputs:{x:s},backend:n,attrs:{perm:c}}),l=sh(l.length,o)),th("any",l,o);const[d,p]=Qc(h.shape,l),f=fz({inputs:{x:h},backend:n,attrs:{shape:[-1,le(p)]}}),m=bz(f,f.dtype,"any",n);let g;return g=fz(i?{inputs:{x:m},backend:n,attrs:{shape:eh(d,u)}}:{inputs:{x:m},backend:n,attrs:{shape:d}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};class Uz{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int outIdx = coords[1];\\n        int inOffset = outIdx * ${r};\\n\\n        int bestIndex = inOffset;\\n        float bestValue = getA(batch, bestIndex);\\n\\n        for (int i = 0; i < ${r}; i++) {\\n          int inIdx = ${o};\\n          float candidate = getA(batch, inIdx);\\n          if (candidate ${i} bestValue) {\\n            bestValue = candidate;\\n            bestIndex = inIdx;\\n          }\\n        }\\n        setOutput(float(bestIndex));\\n      }\\n    `}}class Wz{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,ie(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,u=GD(o),l=IL("coords",o);let c,h;if(1===a){h=o+1;const e=GD(h);c=`\\n        ${e} sourceLocR = ${e}(${l.join()}, 0);\\n        ++${l[o-1]};\\n        ${e} sourceLocG = ${e}(${l.join()}, 0);\\n        ++${l[o-2]};\\n        ${e} sourceLocA = ${e}(${l.join()}, 0);\\n        --${l[o-1]};\\n        ${e} sourceLocB = ${e}(${l.join()}, 0);\\n        --${l[o-2]};`}else h=o,c=`\\n        ${u}
5057 sourceLocR = coords;\\n        ++${l[o-1]};\\n        ${u} sourceLocG = coords;\\n        ++${l[o-2]};\\n        ${u} sourceLocA = coords;\\n        --${l[o-1]};\\n        ${u} sourceLocB = coords;\\n        --${l[o-2]};`;const d=["x","y","z","w","u","v"].slice(0,h),p="."+d[h-1],f=d.map(e=>"int "+e),m=IL("sourceLocR",h-1).concat("inIdx.r"),g=IL("sourceLocG",h-1).concat("inIdx.g"),y=IL("sourceLocB",h-1).concat("inIdx.b"),b=IL("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":`\\n          inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\\n                             getBestIndicesAChannel(${g.join()}),\\n                             getBestIndicesAChannel(${y.join()}),\\n                             getBestIndicesAChannel(${b.join()})));`,v=`vec4(\\n            getAChannel(${m.join()}),\\n            hasNextCol ? getAChannel(${g.join()}) : 0.,\\n            hasNextRow ? getAChannel(${y.join()}) : 0.,\\n            hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,k=r?"":`\\n      float getBestIndicesAChannel(${f.join()}) {\\n        return getChannel(getBestIndicesA(${d.join()}),\\n                                          vec2(${d.slice(-2).join()}));\\n      }`;this.userCode=`\\n      float getAChannel(${f.join()}) {\\n        return getChannel(getA(${d.join()}),\\n                               vec2(${d.slice(-2).join()}));\\n      }\\n      ${k}\\n      void main() {\\n        ${u} coords = getOutputCoords();\\n        bool hasNextCol = ${l[o-1]} < ${i[o-1]-1};\\n        bool hasNextRow = ${l[o-2]} < ${i[o-2]-1};\\n        ${c}\\n        ivec4 srcIdx = ivec4(sourceLocR${p}, sourceLocG${p},\\n          sourceLocB${p}, sourceLocA${p}) * ${t};\\n        ivec4 inIdx = srcIdx;\\n        vec4 bestIndex = vec4(inIdx);\\n        vec4 bestValue = ${v};\\n\\n        for (int i = 0; i < ${t}; i++) {\\n          inIdx = srcIdx;\\n          ${w}\\n          vec4 candidate = ${v};\\n          bvec4 nan = isnan(candidate);\\n          bvec4 replace = bvec4(\\n            vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\\n\\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\\n                           replace.y  ? candidate.y : bestValue.y,\\n                           replace.z  ? candidate.z : bestValue.z,\\n                           replace.w  ? candidate.w : bestValue.w);\\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\\n          srcIdx++;\\n        }\\n        setOutput(bestIndex);\\n      }\\n    `}}function Gz(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];null!=r&&(s=r.shape[0],a=r.shape[1]);const i=Jf(a),o={windowSize:i,inSize:a,batchSize:s,outSize:Math.ceil(a/i)},u=new Uz(o,n,null==r),l=[t];null!=r&&l.push(r);const c=e.runWebGLProgram(u,l,"int32");if(1===c.shape[1])return c;const h=Gz(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function Hz(e,t,n,r=null){const s=null!=r?r.shape:t.shape,a=Jf(s[s.length-1]),i=new Wz(s,a,n,null==r),o=null==r?[t]:[t,r],u=e.runWebGLProgram(i,o,"int32");if(u.shape.length===t.shape.length){const r=Hz(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function jz(e,t,n,r){const s=[n];if(th("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!Xe().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],a=e.texData.get(t.dataId);let i=t;null!==a&&a.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,u]=Qc(i.shape,s),l=le(u),c=fz({inputs:{x:i},backend:e,attrs:{shape:[-1,l]}});n.push(c);const h=Gz(e,c,r);n.push(h);const d=fz({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach(t=>e.disposeIntermediateTensorInfo(t)),d}return Hz(e,t,r)}const qz={kernelName:ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=we(a,s.shape);const o=nh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=Sz({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=sh(i.length,u.shape.length)),th("argMax",[i[0]],u.shape.length);const c=jz(n,u,i[0],"max");return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}},Kz={kernelName:ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=we(a,s.shape);const o=nh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=Sz({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=sh(i.length,u.shape.length)),th("argMin",[i[0]],u.shape.length);const c=jz(n,u,i[0],"min");
vendor: 18,504 bytes, line 5057
5057return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}},Xz=iz({opSnippet:RL+"\\n  if (abs(x) > 1.) {\\n    return NAN;\\n  }\\n  return asin(x);\\n"}),Yz={kernelName:lt,backendName:"webgl",kernelFunc:Xz},Jz=iz({opSnippet:RL+"return log(x + sqrt(x * x + 1.0));"}),Zz={kernelName:ct,backendName:"webgl",kernelFunc:Jz},Qz=iz({opSnippet:RL+"\\n  return atan(x);\\n"}),eP={kernelName:ht,backendName:"webgl",kernelFunc:Qz},tP=oz({opSnippet:HL+"\\n  return atan(a, b);\\n",packedOpSnippet:"\\n  vec4 result = atan(a, b);\\n  bvec4 isNaNA = isnan(a);\\n  bvec4 isNaNB = isnan(b);\\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\\n  "+qL+"\\n  return result;\\n"}),nP={kernelName:pt,backendName:"webgl",kernelFunc:tP},rP=iz({opSnippet:RL+"\\n  if ((x < -1.0) || (x > 1.0)) return NAN;\\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),sP={kernelName:dt,backendName:"webgl",kernelFunc:rP};class aP{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.top,p=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\\n        const ivec2 strides = ivec2(${i}, ${o});\\n        const ivec2 pads = ivec2(${d}, ${p});\\n\\n        void main() {\\n          ivec4 coords = getOutputCoords();\\n          int batch = coords[0];\\n          int d = coords[3];\\n\\n          ivec2 xRCCorner = coords.yz * strides - pads;\\n          int xRCorner = xRCCorner.x;\\n          int xCCorner = xRCCorner.y;\\n\\n          // max/min x(?, ?, d) to get y(yR, yC, d).\\n          // ? = to be determined\\n          float minMaxValue = 0.0;\\n          float minMaxValueFound = 0.0;\\n          int minMaxPosition = 0;\\n          float avgValue = 0.0;\\n\\n          for (int wR = 0; wR < ${c};\\n              wR += ${u}) {\\n            int xR = xRCorner + wR;\\n\\n            if (xR < 0 || xR >= ${e.inHeight}) {\\n              continue;\\n            }\\n\\n            for (int wC = 0; wC < ${h};\\n                wC += ${l}) {\\n              int xC = xCCorner + wC;\\n\\n              if (xC < 0 || xC >= ${e.inWidth}) {\\n                continue;\\n              }\\n\\n              float value = getX(batch, xR, xC, d);\\n\\n              // If a min / max value has already been found, use it. If not,\\n              // use the current value.\\n              float currMinMaxValue = mix(\\n                  value, minMaxValue, minMaxValueFound);\\n              if (value ${t} currMinMaxValue) {\\n                minMaxValue = value;\\n                minMaxValueFound = 1.0;\\n                minMaxPosition = ${r?s?m:g:`wR * ${h} + wC`};\\n              }\\n            }\\n          }\\n          setOutput(float(minMaxPosition));\\n        }\\n      `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const x=4*Math.floor(a/4),w=a%4,v=`\\n      if (${f}) {\\n        avgValue += dot(values, ones);\\n      } else {\\n        minMaxValue = max(values, minMaxValue);\\n      }\\n    `;this.userCode=`\\n      const ivec2 strides = ivec2(${i}, ${o});\\n      const ivec2 pads = ivec2(${d}, ${p});\\n      const float initializationValue = ${y};\\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\\n\\n      float count = 0.0;\\n\\n      float getValue(int batch, int xR, int xC, int d) {\\n        if (xC < 0 || xC >= ${e.inWidth}) {\\n          return initializationValue;\\n        }\\n        count += 1.0;\\n        return getX(batch, xR, xC, d);\\n      }\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int d = coords[3];\\n\\n        ivec2 xRCCorner = coords.yz * strides - pads;\\n        int xRCorner = xRCCorner.x;\\n        int xCCorner = xRCCorner.y;\\n\\n        // max/min x(?, ?, d) to get y(yR, yC, d).\\n        // ? = to be determined\\n        vec4 minMaxValue = vec4(${y});\\n        float avgValue = 0.0;\\n        count = 0.0;\\n\\n        for (int wR = 0; wR < ${c};\\n            wR += ${u}) {\\n          int xR = xRCorner + wR;\\n\\n          if (xR < 0 || xR >= ${e.inHeight}) {\\n            continue;\\n          }\\n\\n          for (int wC = 0; wC < ${x}; wC += 4) {\\n            int xC = xCCorner + wC * ${l};\\n\\n            vec4 values = vec4(\\n              getValue(batch, xR, xC, d),\\n              getValue(batch, xR, xC + ${l}, d),\\n              getValue(batch, xR, xC + 2 * ${l}, d),\\n              getValue(batch, xR, xC + 3 * ${l}, d)\\n            );\\n\\n            ${v}\\n          }\\n\\n          int xC = xCCorner + ${x};\\n          if (${1===w}) {\\n            vec4 values = vec4(\\n              getValue(batch, xR, xC, d),\\n              initializationValue,\\n              initializationValue,\\n              initializationValue\\n            );\\n\\n            ${v}\\n          } else if (${2===w}) {\\n            vec4 values = vec4(\\n              getValue(batch, xR, xC, d),\\n              getValue(batch, xR, xC + ${l}, d),\\n              initializationValue,\\n              initializationValue\\n            );\\n\\n            ${v}\\n          } else if (${3===w}) {\\n            vec4 values = vec4(\\n              getValue(batch, xR, xC, d),\\n              getValue(batch, xR, xC + ${l}, d),\\n              getValue(batch, xR, xC + 2 * ${l}, d),\\n              initializationValue\\n            );\\n\\n            ${v}\\n          }\\n        }\\n        setOutput(${b});\\n      }\\n    `}}class iP{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,o=e.strideHeight,u=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,d=e.effectiveFilterDepth,p=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\\n        const ivec3 strides =\\n            ivec3(${i}, ${o}, ${u});\\n        const ivec3 pads = ivec3(${m}, ${g}, ${y});\\n\\n        void main() {\\n          ivec5 coords = getOutputCoords();\\n          int batch = coords.x;\\n          int ch = coords.u;\\n\\n          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\\n          int xDCorner = xCorner.x;\\n          int xRCorner = xCorner.y;\\n          int xCCorner = xCorner.z;\\n\\n          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\\n          // ? = to be determined\\n          float minMaxValue = 0.0;\\n          float minMaxValueFound = 0.0;\\n          int minMaxPosition = 0;\\n\\n          for (int wD = 0; wD < ${d};\\n              wD += ${l}) {\\n            int xD = xDCorner + wD;\\n\\n            if (xD < 0 || xD >= ${e.inDepth}) {\\n              continue;\\n            }\\n\\n            for (int wR = 0; wR < ${p};\\n                wR += ${c}) {\\n              int xR = xRCorner + wR;\\n\\n              if (xR < 0 || xR >= ${e.inHeight}) {\\n                continue;\\n              }\\n\\n              for (int wC = 0; wC < ${f};\\n                  wC += ${h}) {\\n                int xC = xCCorner + wC;\\n\\n                if (xC < 0 || xC >= ${e.inWidth}) {\\n                  continue;\\n                }\\n\\n                float value = getX(batch, xD, xR, xC, ch);\\n\\n                // If a min / max value has already been found, use it. If not,\\n                // use the current value.\\n                float currMinMaxValue = mix(\\n                    value, minMaxValue, minMaxValueFound);\\n                if (value ${t} currMinMaxValue) {\\n                  minMaxValue = value;\\n                  minMaxValueFound = 1.0;\\n                  minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${p} * ${f} +\\n                      wR * ${f} + wC`};\\n                }\\n              }\\n            }\\n          }\\n          setOutput(float(minMaxPosition));\\n        }\\n      `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / max(count, 1.0)");const v=4*Math.floor(a/4),k=a%4,I=`\\n      if (${b}) {\\n        avgValue += dot(values, ones);\\n      } else {\\n        minMaxValue = max(values, minMaxValue);\\n      }\\n    `;this.userCode=`\\n      const ivec3 strides =\\n        ivec3(${i}, ${o}, ${u});\\n      const ivec3 pads = ivec3(${m}, ${g}, ${y});\\n      const float initializationValue = ${x};\\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\\n\\n      float count = 0.0;\\n\\n      float getValue(int batch, int xD, int xR, int xC, int ch) {\\n        if (xC < 0 || xC >= ${e.inWidth}) {\\n          return initializationValue;\\n        }\\n        count += 1.0;\\n        return getX(batch, xD, xR, xC, ch);\\n      }\\n\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int ch = coords.u;\\n\\n        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\\n        int xDCorner = xCorner.x;\\n        int xRCorner = xCorner.y;\\n        int xCCorner = xCorner.z;\\n\\n        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\\n        // ? = to be determined\\n        vec4 minMaxValue = vec4(${x});\\n        float avgValue = 0.0;\\n        count = 0.0;\\n\\n        for (int wD = 0; wD < ${d};\\n            wD += ${l}) {\\n          int xD = xDCorner + wD;\\n\\n          if (xD < 0 || xD >= ${e.inDepth}) {\\n            continue;\\n          }\\n\\n          for (int wR = 0; wR < ${p};\\n            wR += ${c}) {\\n            int xR = xRCorner + wR;\\n\\n            if (xR < 0 || xR >= ${e.inHeight}) {\\n              continue;\\n            }\\n\\n            for (int wC = 0; wC < ${v}; wC += 4) {\\n              int xC = xCCorner + wC * ${h};\\n\\n              vec4 values = vec4(\\n                getValue(batch, xD, xR, xC, ch),\\n                getValue(batch, xD, xR, xC + ${h}, ch),\\n                getValue(batch, xD, xR, xC + 2 * ${h}, ch),\\n                getValue(batch, xD, xR, xC + 3 * ${h}, ch)\\n              );\\n\\n              ${I}\\n            }\\n\\n            int xC = xCCorner + ${v};\\n            if (${1===k}) {\\n              vec4 values = vec4(\\n                getValue(batch, xD, xR, xC, ch),\\n                initializationValue,\\n                initializationValue,\\n                initializationValue\\n              );\\n\\n              ${I}\\n            } else if (${2===k}) {\\n              vec4 values = vec4(\\n                getValue(batch, xD, xR, xC, ch),\\n                getValue(batch, xD, xR, xC + ${h}, ch),\\n                initializationValue,\\n                initializationValue\\n              );\\n\\n              ${I}\\n            } else if (${3===k}) {\\n              vec4 values = vec4(\\n                getValue(batch, xD, xR, xC, ch),\\n                getValue(batch, xD, xR, xC + ${h}, ch),\\n                getValue(batch, xD, xR, xC + 2 * ${h}, ch),\\n                initializationValue\\n              );\\n\\n              ${I}\\n            }\\n          }\\n        }\\n        setOutput(${w});\\n      }\\n    `}}const oP={kernelName:ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;ED(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(ec(i,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations \'1\'`);const l=Gl(s.shape,a,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&de(l.inShape,l.outShape))return XL({inputs:{x:s},backend:n});const c=new aP(l,"avg",!1);return n.runWebGLProgram(c,[s],"float32")}},uP={kernelName:gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r,c=Hl(s.shape,a,i,[1,1,1],o,u,l),h=new iP(c,"avg",!1);return n.runWebGLProgram(h,[s],"float32")}};class lP{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=o-1-e.padInfo.top,c=u-1-e.padInfo.left,h=1/(t*n);this.userCode=`\\n      const ivec2 pads = ivec2(${l}, ${c});\\n      const float avgMultiplier = float(${h});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n\\n        ivec2 dyRCCorner = coords.yz - pads;\\n        int dyRCorner = dyRCCorner.x;\\n        int dyCCorner = dyRCCorner.y;\\n\\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n        for (int wR = 0; wR < ${o};\\n            wR += ${a}) {\\n          float dyR = float(dyRCorner + wR) / ${r}.0;\\n\\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\\n            continue;\\n          }\\n          int idyR = int(dyR);\\n\\n          for (int wC = 0; wC < ${u};\\n            wC+= ${i}) {\\n            float dyC = float(dyCCorner + wC) / ${s}.0;\\n\\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                fract(dyC) > 0.0) {\\n              continue;\\n            }\\n            int idyC = int(dyC);\\n\\n            float dyValue = getDy(b, idyR, idyC, d);\\n\\n            dotProd += dyValue * avgMultiplier;\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class cP{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=d-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`\\n      const ivec3 pads = ivec3(${p}, ${f}, ${m});\\n      const float avgMultiplier = float(${g});\\n\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int ch = coords.u;\\n\\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\\n        int dyDCorner = dyCorner.x;\\n        int dyRCorner = dyCorner.y;\\n        int dyCCorner = dyCorner.z;\\n\\n        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\\n        // dx(xD, xR, xC, ch).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n\\n        for (int wD = 0; wD < ${c};\\n            wD += ${o}) {\\n          float dyD = float(dyDCorner + wD) / ${s}.0;\\n\\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\\n            continue;\\n          }\\n          int idyD = int(dyD);\\n\\n          for (int wR = 0; wR < ${h};\\n              wR += ${u}) {\\n            float dyR = float(dyRCorner + wR) / ${a}.0;\\n\\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\\n                fract(dyR) > 0.0) {\\n              continue;\\n            }\\n            int idyR = int(dyR);\\n\\n            for (int wC = 0; wC < ${d};\\n                wC += ${l}) {\\n              float dyC = float(dyCCorner + wC) / ${i}.0;\\n\\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                  fract(dyC) > 0.0) {\\n                continue;\\n              }\\n              int idyC = int(dyC);\\n\\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\\n\\n              dotProd += dyValue * avgMultiplier;\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}const hP={kernelName:yt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,h=Hl(i.shape,o,u,[1,1,1],l,c),d=new cP(h);return n.runWebGLProgram(d,[s],i.dtype)}},dP={kernelName:mt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;ED([s,a],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=Gl(i.shape,o,u,1,l),h=new lP(c);return n.runWebGLProgram(h,[s],i.dtype)}},pP={kernelName:bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;return Tz({a:s,b:a,transposeA:i,transposeB:o,backend:n})}};class fP{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ru(e,t),ru(e,n);let i="0.0";null!=r&&(ru(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=s&&(ru(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\\n      void main() {\\n        float x = getXAtOutCoords();\\n        float mean = getMeanAtOutCoords();\\n        float variance = getVarianceAtOutCoords();\\n        float offset = ${i};\\n        float scale = ${o};\\n        float inv = scale * inversesqrt(variance + float(${a}));\\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\\n      }\\n    `}}class mP{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ru(e,t),ru(e,n);let i="vec4(0.0)";null!=r&&(ru(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=s&&(ru(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\\n      void main() {\\n        vec4 offset = ${i};\\n        vec4 scale = ${o};\\n\\n        vec4 x = getXAtOutCoords();\\n        vec4 mean = getMeanAtOutCoords();\\n        vec4 variance = getVarianceAtOutCoords();\\n\\n        vec4 inv = scale * inversesqrt(variance + vec4(${a}));\\n\\n        setOutput((x - mean) * inv + offset);\\n      }\\n    `}}
5057const gP={kernelName:dn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:s,variance:a,offset:i,scale:o}=e;ie(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),ie(null==i||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),ie(null==o||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=n;null==u&&(u=.001);const l=[r,s,a];let c=null;null!=i&&(c=i.shape,l.push(i));let h=null;null!=o&&(h=o.shape,l.push(o));const d=Xe().getBool("WEBGL_PACK_NORMALIZATION")?new mP(r.shape,s.shape,a.shape,c,h,u):new fP(r.shape,s.shape,a.shape,c,h,u);return t.runWebGLProgram(d,l,l[0].dtype)}};class yP{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=GD(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return bP.slice(0,e).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;r=`\\n        ${t} sourceLoc;\\n        ${t} coords = getOutputCoords();\\n        ${e.map((e,t)=>`sourceLoc.${bP[t]} = start[${t}] + coords.${bP[t]};`).join("\\n")}\\n      `,this.userCode=`\\n      void main() {\\n        ${r}\\n        setOutput(getSource(${n}));\\n      }\\n    `}}const bP=["x","y","z","w","u","v"];class xP{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=GD(this.rank),n=IL("coords",this.rank),r=IL("sourceLoc",this.rank),s=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,i=`\\n      result.x = ${a};\\n      if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\\n        ++${r[this.rank-1]};\\n        result.y = ${a};\\n        --${r[this.rank-1]};\\n      }\\n    `,o=1===this.rank?"":`\\n      --${n[this.rank-1]};\\n      if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\\n        ++${r[this.rank-2]};\\n        result.z = ${a};\\n        if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\\n          ++${r[this.rank-1]};\\n          result.w = ${a};\\n        }\\n      }\\n    `,u=this.rank<=4?`sourceLoc = coords +\\n            ${t}(${e.map((e,t)=>`start[${t}]`).join()});`:e.map((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`).join("\\n");this.userCode=`\\n      void main() {\\n        ${t} coords = getOutputCoords();\\n        ${t} sourceLoc;\\n        ${u}\\n        vec4 result = vec4(0.);\\n        ${i}\\n        ${o}\\n        setOutput(result);\\n      }\\n    `}}function wP(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r,[o,u]=dl(s,a,i);if(Zu(s,o,u),0===le(u))return n.makeTensorInfo(u,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||"string"===s.dtype){const e=n.texData.get(s.dataId),t=oL(e.values,o,u,s.shape,s.dtype);return n.makeTensorInfo(u,s.dtype,t)}const{isPacked:l}=n.texData.get(s.dataId),c=cl(s.shape,o,u);if(l||!c){const e=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xP(u):new yP(u),t=[o];return n.runWebGLProgram(e,[s],s.dtype,t)}return n.uploadToGPU(s.dataId),function(e,t,n,r){const s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),i=r.texData.get(a.dataId);Object.assign(i,s),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=hl(t,De(e.shape));s.slice&&(o+=s.slice.flatOffset),i.slice={flatOffset:o,origDataId:s.slice&&s.slice.origDataId||e.dataId};const u=r.dataRefCount.get(i.slice.origDataId)||1;return r.dataRefCount.set(i.slice.origDataId,u+1),a}(s,o,u,n)}const vP={kernelName:_r,backendName:"webgl",kernelFunc:wP},kP={kernelName:xt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;ie(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const o=a.reduce((e,t)=>e*t),u=Qf(s.shape,a,o),l=em(u.length,a.length),c=tm(s.shape,a,o),h=nm(i,a.length),d=rm(c,i,a.length),p=[],f=fz({inputs:{x:s},backend:n,attrs:{shape:u}}),m=Sz({inputs:{x:f},backend:n,attrs:{perm:l}}),g=fz({inputs:{x:m},backend:n,attrs:{shape:c}}),y=wP({inputs:{x:g},backend:n,attrs:{begin:h,size:d}});
vendor: 5,252 bytes, line 5057
5057return p.push(f),p.push(m),p.push(g),p.forEach(e=>n.disposeIntermediateTensorInfo(e)),y}},IP={kernelName:wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=n.readSync(s.dataId),u=n.readSync(a.dataId),l=CO(o,u,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,l)}},SP={kernelName:vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:r,b:s}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=Xe().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([r,s])||1===i){const e=n.texData.get(r.dataId).values,t=n.texData.get(s.dataId).values,[a,i]=AO(r.shape,s.shape,e,t,r.dtype),o=n.makeTensorInfo(i,r.dtype);return n.texData.get(o.dataId).values=a,o}let o;return o=a?new KL("\\n  int r = int(a.r) & int(b.r);\\n  int g = int(a.g) & int(b.g);\\n  int rb = int(a.b) & int(b.b);\\n  int ra = int(a.a) & int(b.a);\\n  return vec4(r, g, rb, ra);\\n",r.shape,s.shape,!1):new jL("\\n  return float(int(a.r) & int(b.r));\\n",r.shape,s.shape),n.runWebGLProgram(o,[r,s],r.dtype)}},NP={kernelName:It,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),i=n.readSync(s.dataId),o=ru(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},TP=oz({opSnippet:"return float(a != b);",cpuKernelImpl:JO,dtype:"bool"}),EP={kernelName:Qn,backendName:"webgl",kernelFunc:TP};function CP(e){const{inputs:t,backend:n}=e,{input:r}=t;return XL({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const $P={kernelName:mr,backendName:"webgl",kernelFunc:CP},AP={kernelName:St,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:s}=t,{x:a}=n,{dtype:i}=s;if("complex64"===i){if("complex64"===a.dtype)return XL({inputs:{x:a},backend:r});const t=Hh(a.shape),n=e({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),s=JL({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),s}if("complex64"===a.dtype){const t=CP({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:i}});return r.disposeIntermediateTensorInfo(t),n}if(!Te(a.dtype,i)){const e=XL({inputs:{x:a},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(r.shouldExecuteOnCPU([a])){const e=r.texData.get(a.dataId).values,[t,n,s]=RO(e,a.shape,a.dtype,i);return r.makeTensorInfo(t,n,s)}if("int32"===i)return function(e,t){const n=new AL(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(a,r);if("bool"===i){const e=r.makeTensorInfo([],"bool",ke("bool",1)),t=TP({inputs:{a,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},RP="return ceil(x);",_P=iz({opSnippet:RP,packedOpSnippet:RP,cpuKernelImpl:_O}),MP={kernelName:Nt,backendName:"webgl",kernelFunc:_P};class FP{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\\n\\n      void main() {\\n        float value = getAAtOutCoords();\\n        if (isnan(value)) {\\n          setOutput(value);\\n          return;\\n        }\\n\\n        setOutput(clamp(value, minVal, maxVal));\\n      }\\n    "}}class DP{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\\n      void main() {\\n        vec4 value = getAAtOutCoords();\\n\\n        if (any(isnan(value))) {\\n          setOutput(value);\\n          return;\\n        }\\n\\n        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\\n      }\\n    "}}const OP={kernelName:Tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:i}=r;let o;o=Xe().getBool("WEBGL_PACK_CLIP")?new DP(s.shape):new FP(s.shape);const u=[[a],[i]];return n.runWebGLProgram(o,[s],s.dtype,u)}};class LP{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\\n      void main() {\\n        float re = abs(getRealAtOutCoords());\\n        float im = abs(getImagAtOutCoords());\\n        float mx = max(re, im);\\n\\n        // sadly the length function in glsl is not underflow-safe\\n        // (at least not on Intel GPUs). So the safe solution is\\n        // to ensure underflow-safety in all cases.\\n        setOutput(\\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\\n        );\\n      }\\n    "}}function zP(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const PP={kernelName:Ct,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new LP(r.shape),i=[zP(r,s.complexTensorInfos.real),zP(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class BP{constructor(e){this.outputShape=[],this.outputShape=Gf(e,1),this.variableNames=e.map((e,t)=>`T${t}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}
5057) setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int yR = coords.x;\\n        int yC = coords.y;\\n\\n        ${n.join("\\n        ")}\\n      }\\n    `}}class VP{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Gf(e,t);const n=this.outputShape,r=n.length,s=GD(r),a=IL("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((e,t)=>`T${t}`);const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n<o.length;n++)o[n]=o[n-1]+e[n][t];const u=i[t],l=i.slice(-2),c=i.join();let h=`if (${u} < ${o[0]}) {\\n        return getChannel(\\n            getT0(${c}), vec2(${l.join()}));\\n        }`;for(let e=1;e<o.length;e++){const t=o[e-1];h+=`\\n        if (${u} < ${o[e]}  && ${u} >= ${o[e-1]}) {\\n          return getChannel(\\n            getT${e}(${UP(i,u,t)}),\\n            vec2(${UP(l,u,t)}));\\n        }`}const d=o.length,p=o[o.length-1];h+=`\\n        return getChannel(\\n          getT${d}(${UP(i,u,p)}),\\n          vec2(${UP(l,u,p)}));`,this.userCode=`\\n      float getValue(${i.map(e=>"int "+e)}) {\\n        ${h}\\n      }\\n\\n      void main() {\\n        ${s} coords = getOutputCoords();\\n        vec4 result = vec4(getValue(${a}), 0., 0., 0.);\\n\\n        ${a[r-1]} = ${a[r-1]} + 1;\\n        if (${a[r-1]} < ${n[r-1]}) {\\n          result.g = getValue(${a});\\n        }\\n\\n        ${a[r-2]} = ${a[r-2]} + 1;\\n        if (${a[r-2]} < ${n[r-2]}) {\\n          result.a = getValue(${a});\\n        }\\n\\n        ${a[r-1]} = ${a[r-1]} - 1;\\n        if (${a[r-2]} < ${n[r-2]} &&\\n            ${a[r-1]} < ${n[r-1]}) {\\n          result.b = getValue(${a});\\n        }\\n        setOutput(result);\\n      }\\n    `}}function UP(e,t,n){const r=e.indexOf(t);return e.map((e,t)=>t===r?`${e} - ${n}`:e).join()}function WP(e){const{inputs:t,backend:n}=e,{input:r}=t;return XL({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const GP={kernelName:xn,backendName:"webgl",kernelFunc:WP};function HP(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map(e=>CP({inputs:{input:e},backend:n})),s=e.map(e=>WP({inputs:{input:e},backend:n})),a=HP(r,t,n),i=HP(s,t,n),o=JL({inputs:{real:a,imag:i},backend:n});return r.forEach(e=>
5057n.disposeIntermediateTensorInfo(e)),s.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let s=n.shouldExecuteOnCPU(e);if("string"===r&&(s=!0),s){const s=e.map(e=>{const r=le(e.shape.slice(t));return fz({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})}),a=s.map(e=>({vals:n.readSync(e.dataId),shape:e.shape})),i=Gf(s.map(e=>e.shape),1),o=1===s[0].shape[0],u=MO(a,i,r,o),l=Gf(e.map(e=>e.shape),t),c=n.makeTensorInfo(l,r,u);return s.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}const a=e.filter(e=>le(e.shape)>0),i=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(1===a.length){const t=i?new AL(e[0].shape,DL):new OL(e[0].shape,DL);return n.runWebGLProgram(t,e,r)}const o=Xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(a.length>o){const e=[];for(let r=0;r<a.length;r+=o){const s=a.slice(r,r+o);e.push(HP(s,t,n))}const r=HP(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(i){const e=new VP(a.map(e=>e.shape),t);return n.runWebGLProgram(e,a,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=Gf(e.map(e=>e.shape),t);return{tensors2D:e.map(e=>fz({inputs:{x:e},attrs:{shape:[-1,le(e.shape.slice(t))]},backend:n})),outShape:r}}(a,t,n),c=new BP(u.map(e=>e.shape)),h=n.runWebGLProgram(c,u,r);u.forEach(e=>n.disposeIntermediateTensorInfo(e));const d=fz({inputs:{x:h},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(h),d}function jP(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=we(s,t[0].shape)[0];Wf(t.map(e=>e.shape),a);const i=Gf(t.map(e=>e.shape),a);if(0===le(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter(e=>le(e.shape)>0);return 1===o.length?XL({inputs:{x:o[0]},backend:n}):HP(o,a,n)}const qP={kernelName:$t,backendName:"webgl",kernelFunc:jP};class KP{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,p=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=r?`float activation(float a) {\\n          float b = getPreluActivationWeightsAtOutCoords();\\n          ${n}\\n        }`:s?`float activation(float a) {\\n          float b = getLeakyreluAlphaAtOutCoords();\\n          ${n}\\n        }`:`\\n          float activation(float x) {\\n            ${n}\\n          }\\n        `,w="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\\n      ${x}\\n\\n      const ivec2 strides = ivec2(${o}, ${u});\\n      const ivec2 pads = ivec2(${a}, ${i});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int d2 = coords[${b}];\\n\\n        ivec2 xRCCorner =\\n            ivec2(coords[${g}], coords[${y}]) * strides - pads;\\n        int xRCorner = xRCCorner.x;\\n        int xCCorner = xRCCorner.y;\\n\\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n        for (int wR = 0; wR < ${h}; wR++) {\\n          int xR = xRCorner + wR * ${l};\\n\\n          if (xR < 0 || xR >= ${e.inHeight}) {\\n            continue;\\n          }\\n\\n          for (int wC = 0; wC < ${d}; wC++) {\\n            int xC = xCCorner + wC * ${c};\\n\\n            if (xC < 0 || xC >= ${e.inWidth}) {\\n              continue;\\n            }\\n\\n            for (int d1 = 0; d1 < ${p}; d1 += 4) {\\n              vec4 wValues = vec4(\\n                getW(wR, wC, d1, d2),\\n                getW(wR, wC, d1 + 1, d2),\\n                getW(wR, wC, d1 + 2, d2),\\n                getW(wR, wC, d1 + 3, d2)\\n              );\\n\\n              if (${m}) {\\n                vec4 xValues = vec4(\\n                  getX(batch, xR, xC, d1),\\n                  getX(batch, xR, xC, d1 + 1),\\n                  getX(batch, xR, xC, d1 + 2),\\n                  getX(batch, xR, xC, d1 + 3)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              } else {\\n                vec4 xValues = vec4(\\n                  getX(batch, d1, xR, xC),\\n                  getX(batch, d1 + 1, xR, xC),\\n                  getX(batch, d1 + 2, xR, xC),\\n                  getX(batch, d1 + 3, xR, xC)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              }\\n            }\\n\\n            if (${1===f}) {\\n\\n              if (${m}) {\\n                dotProd +=\\n                    getX(batch, xR, xC, ${p}) *\\n                    getW(wR, wC, ${p}, d2);\\n              } else {\\n                dotProd +=\\n                    getX(batch, ${p}, xR, xC) *\\n                    getW(wR, wC, ${p}, d2);\\n              }\\n\\n            } else if (${2===f}) {\\n              vec2 wValues = vec2(\\n                getW(wR, wC, ${p}, d2),\\n                getW(wR, wC, ${p} + 1, d2)\\n              );\\n\\n              if (${m}) {\\n                vec2 xValues = vec2(\\n                  getX(batch, xR, xC, ${p}),\\n                  getX(batch, xR, xC, ${p} + 1)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              } else {\\n                vec2 xValues = vec2(\\n                  getX(batch, ${p}, xR, xC),\\n                  getX(batch, ${p} + 1, xR, xC)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              }\\n\\n            } else if (${3===f}) {\\n              vec3 wValues = vec3(\\n                getW(wR, wC, ${p}, d2),\\n                getW(wR, wC, ${p} + 1, d2),\\n                getW(wR, wC, ${p} + 2, d2)\\n              );\\n\\n              if (${m}) {\\n                vec3 xValues = vec3(\\n                  getX(batch, xR, xC, ${p}),\\n                  getX(batch, xR, xC, ${p} + 1),\\n                  getX(batch, xR, xC, ${p} + 2)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              } else {\\n                vec3 xValues = vec3(\\n                  getX(batch, ${p}, xR, xC),\\n                  getX(batch, ${p} + 1, xR, xC),\\n                  getX(batch, ${p} + 2, xR, xC)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              }\\n\\n            }\\n          }\\n        }\\n\\n        float result = dotProd;\\n        ${v}\\n        ${w}\\n        setOutput(result);\\n      }\\n    `}}class XP{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,d=e.filterWidth,p=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\\n      const ivec3 strides = ivec3(${s}, ${a}, ${i});\\n      const ivec3 pads = ivec3(${t}, ${n}, ${r});\\n\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int d2 = coords.u;\\n\\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\\n        int xFCorner = xFRCCorner.x;\\n        int xRCorner = xFRCCorner.y;\\n        int xCCorner = xFRCCorner.z;\\n\\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\\n        // values in that axis.\\n        float dotProd = 0.0;\\n        for (int wF = 0; wF < ${c}; wF++) {\\n          int xF = xFCorner + wF * ${o};\\n\\n          if (xF < 0 || xF >= ${e.inDepth}) {\\n            continue;\\n          }\\n\\n          for (int wR = 0; wR < ${h}; wR++) {\\n            int xR = xRCorner + wR * ${u};\\n\\n            if (xR < 0 || xR >= ${e.inHeight}) {\\n              continue;\\n            }\\n\\n            for (int wC = 0; wC < ${d}; wC++) {\\n              int xC = xCCorner + wC * ${l};\\n\\n              if (xC < 0 || xC >= ${e.inWidth}) {\\n                continue;\\n              }\\n\\n              for (int d1 = 0; d1 < ${p}; d1 += 4) {\\n                vec4 xValues = vec4(\\n                  getX(batch, xF, xR, xC, d1),\\n                  getX(batch, xF, xR, xC, d1 + 1),\\n                  getX(batch, xF, xR, xC, d1 + 2),\\n                  getX(batch, xF, xR, xC, d1 + 3)\\n                );\\n                vec4 wValues = vec4(\\n                  getW(wF, wR, wC, d1, d2),\\n                  getW(wF, wR, wC, d1 + 1, d2),\\n                  getW(wF, wR, wC, d1 + 2, d2),\\n                  getW(wF, wR, wC, d1 + 3, d2)\\n                );\\n\\n                dotProd += dot(xValues, wValues);\\n              }\\n\\n              if (${1===f}) {\\n                dotProd +=\\n                  getX(batch, xF, xR, xC, ${p}) *\\n                  getW(wF, wR, wC, ${p}, d2);\\n              } else if (${2===f}) {\\n                vec2 xValues = vec2(\\n                  getX(batch, xF, xR, xC, ${p}),\\n                  getX(batch, xF, xR, xC, ${p} + 1)\\n                );\\n                vec2 wValues = vec2(\\n                  getW(wF, wR, wC, ${p}, d2),\\n                  getW(wF, wR, wC, ${p} + 1, d2)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              } else if (${3===f}) {\\n                vec3 xValues = vec3(\\n                  getX(batch, xF, xR, xC, ${p}),\\n                  getX(batch, xF, xR, xC, ${p} + 1),\\n                  getX(batch, xF, xR, xC, ${p} + 2)\\n                );\\n                vec3 wValues = vec3(\\n                  getW(wF, wR, wC, ${p}, d2),\\n                  getW(wF, wR, wC, ${p} + 1, d2),\\n                  getW(wF, wR, wC, ${p} + 2, d2)\\n                );\\n                dotProd += dot(xValues, wValues);\\n              }\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class YP{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=YD(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l;let h="\\n       int xR; int xC; int xCOffset;\\n       vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<l;e++)h+=`\\n           vec4 xTexelC${2*e};\\n           int xTexelC${2*e}Ready;\\n           vec4 xTexelC${2*e+1};\\n           int xTexelC${2*e+1}Ready;\\n           vec4 xC${e};`;h+=`\\n     for (int r = 0; r < ${u}; r++) {\\n      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\\n       `;
vendor: 7,955 bytes, line 5057
5057for(let e=0;e<l;e++)h+=`\\n           xTexelC${2*e} = vec4(0.0);\\n           xTexelC${2*e}Ready = 0;\\n           xTexelC${2*e+1} = vec4(0.0);\\n           xTexelC${2*e+1}Ready = 0;\\n           xC${e} = vec4(0.0);`;h+="\\n         xR = xRCorner + r * dilations[0];\\n         if (xR >=0 && xR < inDims[0]) {\\n       ";for(let t=0;t<(c+1)/2;t++){const n=2*t;if(h+=`\\n           xC = xCCorner + ${n*o};\\n           `,1===i){if(n<l&&(a%2==1?(h+=`\\n                 xCOffset = xC + 1;\\n                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\\n                   xTexelC${n} = getX(batch, xR, xCOffset, d1);\\n\\n                   // Need to manually clear unused channels in case\\n                   // we\'re reading from recycled texture.\\n                   if (xCOffset + 1 >= inDims[1]) {\\n                     xTexelC${n}.zw = vec2(0.0);\\n                   }\\n                   xTexelC${n}Ready = 1;\\n                 }\\n               `,h+=1===o&&n>0?`\\n                 xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\\n                 `:`\\n                   xCOffset = xC + 1 - 2;\\n\\n                   if (xCOffset >= 0 && xCOffset < inDims[1]) {\\n                     previous = getX(batch, xR, xCOffset, d1);\\n\\n                     // Need to manually clear unused channels in case\\n                     // we\'re reading from recycled texture.\\n                     if (xCOffset + 1 >= inDims[1]) {\\n                       previous.zw = vec2(0.0);\\n                     }\\n\\n                     xC${n} = vec4(previous.zw, xTexelC${n}.xy);\\n                   } else {\\n                     xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\\n                   }\\n                   `):h+=`\\n                 if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\\n                   xTexelC${n} = getX(batch, xR, xC, d1);\\n                   if (xC + 1 >= inDims[1]) {\\n                     xTexelC${n}.zw = vec2(0.0);\\n                   }\\n                   xTexelC${n}Ready = 1;\\n                 }\\n\\n                 xC${n} = xTexelC${n};\\n                 `,n+1<l)){const e=a%2==0?te(o):o;o%2==0&&a%2==1||o%2!=0&&a%2!=1?(h+=`\\n                   xCOffset = xC + imod(pads[1], 2) + ${e};\\n\\n                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\\n                     xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\\n\\n                     // Need to manually clear unused channels in case\\n                     // we\'re reading from recycled texture.\\n                     if (xCOffset + 1 >= inDims[1]) {\\n                       xTexelC${n+1}.zw = vec2(0.0);\\n                     }\\n                     xTexelC${n+1}Ready = 1;\\n                   }\\n                   `,h+=o>1?`\\n                     xCOffset -= 2;\\n                     if (xCOffset >= 0 && xCOffset < inDims[1]) {\\n                      previous = getX(batch, xR, xCOffset, d1);\\n                      xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\\n                     } else {\\n                      xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\\n                     }\\n                     `:`\\n                     xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\\n                     `):h+=1===e?`\\n                     xC${n+1} = xTexelC${n};\\n                     `:`\\n                     xCOffset = xC + ${e};\\n\\n                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\\n                       xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\\n                       if (xCOffset + 1 >= inDims[1]) {\\n                         xTexelC${n+1}.zw = vec2(0.0);\\n                       }\\n                       xTexelC${n+1}Ready = 1;\\n                     }\\n\\n                     xC${n+1} = xTexelC${n+1};\\n                     `}}else n<l&&(a%2==1?(h+=`\\n                 xCOffset = xC + 1 - strides[1];\\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\\n                   xTexelC${n} = getX(batch, xR, xCOffset, d1);\\n                   // Need to manually clear unused channels in case\\n                   // we\'re reading from recycled texture.\\n                   if (xCOffset + 1 >= inDims[1]) {\\n                     xTexelC${n}.zw = vec2(0.0);\\n                   }\\n                   xTexelC${n}Ready = 1;\\n                 }\\n\\n                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\\n                   xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\\n                   // Need to manually clear unused channels in case\\n                   // we\'re reading from recycled texture.\\n                   if (xC + 2 >= inDims[1]) {\\n                     xTexelC${n+1}.zw = vec2(0.0);\\n                   }\\n                   xTexelC${n+1}Ready = 1;\\n                 }\\n\\n                 xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\\n               `,n+1<l&&(h+=`\\n                   final = vec4(0.0);\\n                   xCOffset = xC + 1 + strides[1];\\n                   if(xCOffset >= 0 && xCOffset < inDims[1]) {\\n                     final = getX(batch, xR, xCOffset, d1);\\n                   }\\n                   xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\\n                 `)):(h+=`\\n                 if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\\n                   xTexelC${n} = getX(batch, xR, xC, d1);\\n                   if (xC + 1 >= inDims[1]) {\\n                     xTexelC${n}.zw = vec2(0.0);\\n                   }\\n                   xTexelC${n}Ready = 1;\\n                 }\\n\\n                 xCOffset = xC + strides[1];\\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\\n                   xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\\n                   if (xCOffset + 1 >= inDims[1]) {\\n                     xTexelC${n+1}.zw = vec2(0.);\\n                   }\\n                   xTexelC${n+1}Ready = 1;\\n                 }\\n\\n                 xC${n} = vec4(\\n                   xTexelC${n}.xy, xTexelC${n+1}.xy);\\n               `,n+1<l&&(h+=`\\n                   xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\\n                 `)));n<l&&(h+=`\\n             wTexel = getW(r, ${n}, d1, d2);\\n             dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\\n             if(d1 + 1 < ${e.inChannels}) {\\n               dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\\n             }\\n           `,n+1<l&&(h+=`\\n               wTexel = getW(r, ${n+1}, d1, d2);\\n               dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\\n               if(d1 + 1 < ${e.inChannels}) {\\n                 dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\\n               }\\n             `))}h+="\\n     }\\n   ",h+="\\n     }\\n   ",h+="\\n     }\\n   ";let d="",p="";n&&(d=r?`vec4 activation(vec4 a) {\\n           vec4 b = getPreluActivationWeightsAtOutCoords();\\n           ${n}\\n         }`:s?`vec4 activation(vec4 a) {\\n           vec4 b = getLeakyreluAlphaAtOutCoords();\\n           ${n}\\n         }`:`vec4 activation(vec4 x) {\\n           ${n}\\n         }`,p="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\\n       ${d}\\n\\n       void main() {\\n         ivec4 coords = getOutputCoords();\\n         int batch = coords.x;\\n         ivec2 xRCCorner = coords.yz * strides - pads;\\n         int d2 = coords.w;\\n         int xRCorner = xRCCorner.x;\\n         int xCCorner = xRCCorner.y;\\n\\n         //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\\n         vec4 dotProd = vec4(0.000000000000001);\\n\\n         ${h}
5057\\n\\n         vec4 result = dotProd - vec4(0.000000000000001);\\n         ${f}\\n         ${p}\\n         setOutput(result);\\n       }\\n     `}}class JP{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=YD(this.outputShape.length);const{dataFormat:n}=t,r=$D(),s="channelsLast"===n,a=s?1:2,i=s?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let u="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)u+=`\\n          blockIndex = rc.z + ${t};\\n          pos = rc.y + ${e};\\n\\n          ${o}\\n            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\\n            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\\n\\n            if(d0 < inputShape[${a}] && d0 >= 0) {\\n              // Use custom imod instead mod. On Intel GPU, mod may generate\\n              // unexpected value.\\n              // https://github.com/tensorflow/tfjs/issues/5447\\n              offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\\n              d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\\n                  inChannels);\\n\\n              if(d1 < inputShape[${i}] && d1 >= 0) {\\n\\n                ch = imod(pos, inChannels);\\n\\n                if (${s}) {\\n                  innerDims = vec2(d1, ch);\\n                  result[${2*e+t}] = getChannel(\\n                    getA(rc.x, d0, int(innerDims.x),\\n                    int(innerDims.y)), innerDims);\\n                } else {\\n                  innerDims = vec2(d0, d1);\\n                  result[${2*e+t}] = getChannel(\\n                    getA(rc.x, ch, int(innerDims.x),\\n                    int(innerDims.y)), innerDims);\\n                }\\n              }\\n            }\\n          }\\n        `;this.userCode=`\\n      void main() {\\n        ivec3 rc = getOutputCoords();\\n\\n        vec4 result = vec4(0);\\n\\n        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\\n        vec2 innerDims;\\n\\n        ${u}\\n\\n        ${r.output} = result;\\n      }\\n    `}}function ZP(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function QP({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const u=e.shape,l=r.texData.get(e.dataId),c=n.inChannels,h=u[0]*u[1]*u[2],d=n.outChannels,p="channelsLast"===n.dataFormat,f=!1;let m;const g=[];if(null!=a){const e=ZP(a.shape,p);null!=e&&(a=fz({inputs:{x:a},backend:r,attrs:{shape:e}}),g.push(a))}if(null!=s){const e=ZP(s.shape,p);null!=e&&(s=fz({inputs:{x:s},backend:r,attrs:{shape:e}}),g.push(s))}if((1!==h&&1!==d||!(c>1e3))&&l.isPacked&&p&&null!=l.texture&&u[2]%2!=0&&de(l.shape.slice(-3),u.slice(-3))){const c=u[0]*u[1]*(u[2]+1),h={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},d=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,ie(pD(l.shape,h.shape),()=>`packed reshape ${l.shape} to ${h.shape} isn\'t free`);const p=fz({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(p);const y=Tz({a:h,b:p,backend:r,transposeA:!1,transposeB:f,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),b=r.texData.get(y.dataId);ie(b.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=d,b.shape=n.outShape,m=XL({inputs:{x:y},backend:r}),m.shape=n.outShape,g.push(y)}else{const u=n.outHeight*n.outWidth,l=fz({inputs:{x:e},backend:r,attrs:{shape:p?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=fz({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=Tz({a:p?l:c,b:p?c:l,transposeA:!p,transposeB:f,backend:r,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i});m=fz({inputs:{x:h},backend:r,attrs:{shape:n.outShape}}),g.push(l),g.push(c),g.push(h)}for(const e of g)r.disposeIntermediateTensorInfo(e);return m}function eB({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:h,outHeight:d,dataFormat:p}=n,f="channelsLast"===p,m=u*l*c,g=d*h,y=[n.batchSize,m,g],b=[];if(null!=a){const e=ZP(a.shape,f);null!=e&&(a=fz({inputs:{x:a},backend:r,attrs:{shape:e}}
vendor: 7,205 bytes, line 5057
5057),b.push(a))}if(null!=s){const e=ZP(s.shape,f);null!=e&&(s=fz({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}const x=fz({inputs:{x:t},backend:r,attrs:{shape:[1,m,le(t.shape)/m]}});b.push(x);const w=new JP(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],k=r.runWebGLProgram(w,[e],"float32",v),I=fz({inputs:{x:k},backend:r,attrs:{shape:y}});b.push(k),b.push(I);const S=null!=s,N=null!=a,T="leakyrelu"===o,E=o?uz(o,!0):null,C=new lz(f?I.shape:x.shape,f?x.shape:I.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,S,E,N,T),$=f?[I,x]:[x,I];if(s&&$.push(s),N&&$.push(a),T){const e=r.makeTensorInfo([],"float32",qs(i,"float32"));$.push(e),b.push(e)}const A=r.runWebGLProgram(C,$,"float32"),R=fz({inputs:{x:A},backend:r,attrs:{shape:n.outShape}});b.push(A);for(const e of b)r.disposeIntermediateTensorInfo(e);return R}const tB={kernelName:At,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r,h=nc(u),d=jl(s.shape,a.shape,i,l,o,c,!1,h);let p;if(1!==d.filterHeight||1!==d.filterWidth||1!==d.dilationHeight||1!==d.dilationWidth||1!==d.strideHeight||1!==d.strideWidth||"SAME"!==d.padInfo.type&&"VALID"!==d.padInfo.type)if(d.strideWidth<=2&&"channelsLast"===h&&Xe().getBool("WEBGL_EXP_CONV")){const e=new YP(d),t=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];p=n.runWebGLProgram(e,[s,a],"float32",t)}else if(Xe().getBool("WEBGL_CONV_IM2COL"))p=eB({x:s,filter:a,convInfo:d,backend:n});else{const e=new KP(d);p=n.runWebGLProgram(e,[s,a],"float32")}else p=QP({x:s,filter:a,convInfo:d,backend:n});const f=fz({inputs:{x:p},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(p),f}};class nB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int wR = coords.x;\\n        int wC = coords.y;\\n        int d1 = coords.z;\\n        int d2 = coords.w;\\n\\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n\\n        for (int b = 0; b < ${e.batchSize}; b++) {\\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\\n            int xR = wR + yR * ${t} - ${r};\\n\\n            if (xR < 0 || xR >= ${e.inHeight}) {\\n              continue;\\n            }\\n\\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\\n              int xC = wC + yC * ${n} - ${s};\\n\\n              if (xC < 0 || xC >= ${e.inWidth}) {\\n                continue;\\n              }\\n\\n              ${a?"float dyValue = getDy(b, yR, yC, d2);\\n              float xValue = getX(b, xR, xC, d1);\\n              dotProd += (xValue * dyValue);":"float dyValue = getDy(b, d2, yR, yC);\\n              float xValue = getX(b, d1, xR, xC);\\n              dotProd += (xValue * dyValue);"}\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class rB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode=`\\n      const ivec2 pads = ivec2(${i}, ${o});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int d1 = coords[${c}];\\n\\n        ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\\n        int dyRCorner = dyCorner.x;\\n        int dyCCorner = dyCorner.y;\\n\\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n        for (int wR = 0; wR < ${t}; wR++) {\\n          float dyR = float(dyRCorner + wR) / ${r}.0;\\n\\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\\n            continue;\\n          }\\n          int idyR = int(dyR);\\n\\n          int wRPerm = ${t} - 1 - wR;\\n\\n          for (int wC = 0; wC < ${n}; wC++) {\\n            float dyC = float(dyCCorner + wC) / ${s}.0;\\n\\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                fract(dyC) > 0.0) {\\n              continue;\\n            }\\n            int idyC = int(dyC);\\n\\n            int wCPerm = ${n} - 1 - wC;\\n\\n            for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\\n\\n              if (${a}) {\\n                float xValue = getDy(batch, idyR, idyC, d2);\\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\\n                dotProd += xValue * wValue;\\n              } else {\\n                float xValue = getDy(batch, d2, idyR, idyC);\\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\\n                dotProd += xValue * wValue;\\n              }\\n\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class sB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int wF = coords.x;\\n        int wR = coords.y;\\n        int wC = coords.z;\\n        int d1 = coords.w;\\n        int d2 = coords.u;\\n\\n        float dotProd = 0.0;\\n\\n        for (int b = 0; b < ${e.batchSize}; b++) {\\n          for (int yF = 0; yF < ${e.outDepth}; yF++) {\\n            int xF = wF + yF * ${t} - ${s};\\n\\n            if (xF < 0 || xF >= ${e.inDepth}) {\\n              continue;\\n            }\\n\\n            for (int yR = 0; yR < ${e.outHeight}; yR++) {\\n              int xR = wR + yR * ${n} - ${a};\\n\\n              if (xR < 0 || xR >= ${e.inHeight}) {\\n                continue;\\n              }\\n\\n              for (int yC = 0; yC < ${e.outWidth}; yC++) {\\n                int xC = wC + yC * ${r} - ${i};\\n\\n                if (xC < 0 || xC >= ${e.inWidth}) {\\n                  continue;\\n                }\\n\\n                float dyValue = getDy(b, yF, yR, yC, d2);\\n                float xValue = getX(b, xF, xR, xC, d1);\\n                dotProd += (xValue * dyValue);\\n              }\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class aB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,u=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`\\n      const ivec3 pads = ivec3(${o}, ${u}, ${l});\\n\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int d1 = coords.u;
5057\\n\\n\\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\\n        int dyFCorner = dyCorner.x;\\n        int dyRCorner = dyCorner.y;\\n        int dyCCorner = dyCorner.z;\\n\\n        float dotProd = 0.0;\\n        for (int wF = 0; wF < ${t}; wF++) {\\n          float dyF = float(dyFCorner + wF) / ${s}.0;\\n\\n          if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\\n            continue;\\n          }\\n          int idyF = int(dyF);\\n\\n          int wFPerm = ${t} - 1 - wF;\\n\\n          for (int wR = 0; wR < ${n}; wR++) {\\n            float dyR = float(dyRCorner + wR) / ${a}.0;\\n\\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\\n              fract(dyR) > 0.0) {\\n              continue;\\n            }\\n            int idyR = int(dyR);\\n\\n            int wRPerm = ${n} - 1 - wR;\\n\\n            for (int wC = 0; wC < ${r}; wC++) {\\n              float dyC = float(dyCCorner + wC) / ${i}.0;\\n\\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                  fract(dyC) > 0.0) {\\n                continue;\\n              }\\n              int idyC = int(dyC);\\n\\n              int wCPerm = ${r} - 1 - wC;\\n\\n              for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\\n                dotProd += xValue * wValue;\\n              }\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}const iB={kernelName:Rt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r,h=nc(u),d=jl(s.shape,c,i,1,o,l,!1,h),p=new nB(d);return n.runWebGLProgram(p,[s,a],"float32")}};class oB{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=YD(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,r=t-1-e.padInfo.top,s=n-1-e.padInfo.left;this.userCode=`\\n      const ivec2 pads = ivec2(${r}, ${s});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int d1 = coords[3];\\n\\n        ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\\n        int dyRCorner = dyCorner.x;\\n        int dyCCorner = dyCorner.y;\\n\\n        vec4 result = vec4(0.);\\n        for (int wR = 0; wR < ${t}; wR++) {\\n          float dyR = float(dyRCorner + wR) / strides[0];\\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\\n            continue;\\n          }\\n          int idyR = int(dyR);\\n          int wRPerm = ${t} - 1 - wR;\\n\\n          for (int wC = 0; wC < ${n}; wC++) {\\n            int wCPerm = ${n} - 1 - wC;\\n\\n            float dyC = float(dyCCorner + wC) / strides[1];\\n            bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\\n              && (fract(dyC) == 0.0);\\n            int idyC = int(dyC);\\n\\n            float dyC2 = float(dyCCorner + wC + 1) / strides[1];\\n            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\\n              && (fract(dyC2) == 0.0);\\n            int idyC2 = int(dyC2);\\n\\n            if (idyCVal && idyCVal2) {\\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\\n                vec4 dySample = getDy(batch, idyR, idyC, d2);\\n                vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\\n                  dySample : getDy(batch, idyR, idyC2, d2);\\n\\n                vec2 dyValue = mod(float(idyC), 2.) == 0. ?\\n                  dySample.xy : dySample.zw;\\n                result.xy += vec2(dot(dyValue, wValue.xy),\\n                  dot(dyValue, wValue.zw));\\n\\n                dyValue = mod(float(idyC2), 2.) == 0. ?\\n                  dySample2.xy : dySample2.zw;\\n                result.zw += vec2(dot(dyValue, wValue.xy),\\n                  dot(dyValue, wValue.zw));\\n              }\\n            } else if (idyCVal) {\\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\\n                vec4 dySample = getDy(batch, idyR, idyC, d2);\\n                vec2 dyValue = mod(float(idyC), 2.) == 0. ?\\n                  dySample.xy : dySample.zw;\\n                result.xy += vec2(dot(dyValue, wValue.xy),\\n                  dot(dyValue, wValue.zw));\\n              }\\n            } else if (idyCVal2) {\\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\\n                vec4 dySample = getDy(batch, idyR, idyC2, d2);\\n                vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\\n                  dySample.xy : dySample.zw;\\n                result.zw += vec2(dot(dyValue, wValue.xy),\\n                  dot(dyValue, wValue.zw));\\n              }\\n            }\\n          }\\n        }\\n        setOutput(result);\\n      }\\n    `}}const uB={kernelName:_t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r,h=nc(l),d=jl(i,a.shape,o,1,u,c,!1,h);if(Xe().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===h){const e=[[d.strideHeight,d.strideWidth]],t=new oB(d);return n.runWebGLProgram(t,[s,a],"float32",e)}{const e=new rB(d);return n.runWebGLProgram(e,[s,a],"float32")}}},lB={kernelName:Mt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r,l=ql(s.shape,a.shape,i,u,o),c=new XP(l);return n.runWebGLProgram(c,[s,a],"float32")}},cB={kernelName:Ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,filterShape:u}=r,l=ql(s.shape,u,i,1,o),c=new sB(l);return n.runWebGLProgram(c,[s,a],"float32")}},hB={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:i,strides:o,inputShape:u}=r,l=ql(u,a.shape,o,1,i),c=new aB(l);return n.runWebGLProgram(c,[s,a],"float32")}},dB=iz({opSnippet:az+"\\n  return cos(x);\\n",packedOpSnippet:`\\n  vec4 result = cos(x);\\n  bvec4 isNaN = isnan(x);\\n  ${qL}\\n  return result;\\n`}),pB={kernelName:Ot,backendName:"webgl",kernelFunc:dB},fB=iz({opSnippet:"\\n  float e2x = exp(-x);\\n  return (e2x + 1.0 / e2x) / 2.0;\\n"}),mB={kernelName:Lt,backendName:"webgl",kernelFunc:fB};
vendor: 17,448 bytes, line 5057
5057class gB{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,o,u]=e,[l]=t,[c,h]=n;this.outputShape=[l,c,h,u];const d="bilinear"===r?1:0,[p,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${p} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${p}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\\n      const float height_ratio = float(${m});\\n      const float width_ratio = float(${b});\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int y = coords[1];\\n        int x = coords[2];\\n        int d = coords[3];\\n\\n        // get box vals\\n        float y1 = getBoxes(b,0);\\n        float x1 = getBoxes(b,1);\\n        float y2 = getBoxes(b,2);\\n        float x2 = getBoxes(b,3);\\n\\n        // get image in batch index\\n        int bInd = round(getBoxInd(b));\\n        if(bInd < 0 || bInd >= ${a}) {\\n          return;\\n        }\\n\\n        float height_scale = ${g};\\n        float width_scale = ${x};\\n\\n        float in_y = ${y};\\n        if( in_y < 0.0 || in_y > ${p} ) {\\n          setOutput(float(${s}));\\n          return;\\n        }\\n        float in_x = ${w};\\n        if( in_x < 0.0 || in_x > ${f} ) {\\n          setOutput(float(${s}));\\n          return;\\n        }\\n\\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\\n        if(${d} == 1) {\\n          // Compute the four integer indices.\\n          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\\n          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\\n\\n          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\\n          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\\n          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\\n          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\\n\\n          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\\n\\n          float top = topLeft + (topRight - topLeft) * fracCR.x;\\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\\n          float newValue = top + (bottom - top) * fracCR.y;\\n          setOutput(newValue);\\n        } else {\\n          // Compute the coordinators of nearest neighbor point.\\n          ivec2 sourceNearestCR = ivec2(floor(\\n            sourceFracIndexCR + vec2(0.5,0.5)));\\n          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\\n          setOutput(newValue);\\n        }\\n      }\\n    `}}const yB={kernelName:Bt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,c=new gB(s.shape,a.shape,o,u,l);return n.runWebGLProgram(c,[s,a,i],"float32")}};var bB;!function(e){e.Prod="*",e.Sum="+"}(bB||(bB={}));class xB{constructor(e,t,n,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const s=this.outputShape.length,a=this.op===bB.Prod?"1.0":"0.0",i=n?a:`getX(${wB(s,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let u="",l="";n?(u=r?"end != "+(o-1):"end != 0",l=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${o}`:"end >= pow2",l=r?"end + pow2":"end - pow2"),this.userCode=`\\n      void main() {\\n        ${GD(s)} coords = getOutputCoords();\\n        int end = ${vB(s,"coords",this.op)};\\n        float val = ${i};\\n        int pow2 = int(pow(2.0, index));\\n        if (${u}) {\\n          int idx = ${l};\\n          ${vB(s,"coords",this.op)} = idx;\\n          val ${this.op}= getX(${wB(s,"coords",this.op)});\\n        }\\n        setOutput(val);\\n      }\\n    `}}function wB(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function vB(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function kB(e,t,n,r,s,a){const i=t.shape.length,o=nh([r],i);let u=t;null!=o&&(u=Sz({inputs:{x:t},backend:n,attrs:{perm:o}}));const l=sh(1,i)[0];if(l!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${r}`);const c=u.shape[l];let h=XL({inputs:{x:u},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const r=new xB(e,u.shape,!1,a),s=[[t]],i=h;h=n.runWebGLProgram(r,[h],h.dtype,s),n.disposeIntermediateTensorInfo(i)}if(s){const t=new xB(e,u.shape,s,a),r=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(r)}if(null!=o){const e=Sz({inputs:{x:h},backend:n,attrs:{perm:rh(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),e}return h}const IB={kernelName:zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;return kB(bB.Prod,s,n,a,i,o)}},SB={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;return kB(bB.Sum,s,n,a,i,o)}},NB={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i,binaryOutput:o}=r;if(1===s.shape.length){const e=n.readSync(s.dataId),t=n.readSync(a.dataId),r=CO(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,r)}if(2===s.shape.length){const e=n.bufferSync(s),t=n.bufferSync(a),r=$O(e,t,i,o);return n.makeTensorInfo(r.shape,a.dtype,r.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}};class TB{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\\n    void main() {\\n      ivec4 coords = getOutputCoords();\\n      int b = coords[0];\\n      int h = ${this.getHeightCoordString()};\\n      int w = ${this.getWidthCoordString()};\\n      int d = ${this.getDepthCoordString()};\\n\\n      int in_h = h / ${t};\\n      int offset_h = imod(h, ${t});\\n      int in_w = w / ${t};\\n      int offset_w = imod(w, ${t});\\n      int offset_d = (offset_h * ${t} + offset_w) *\\n        ${this.getOutputDepthSize()};\\n      int in_d = d + offset_d;\\n\\n      float result = ${this.getInputSamplingString()};\\n      setOutput(result);\\n    }\\n  `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const EB={kernelName:Ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:i}=r,o=s.shape[0],u=("NHWC"===i?s.shape[1]:s.shape[2])*a,l=("NHWC"===i?s.shape[2]:s.shape[3])*a,c=("NHWC"===i?s.shape[3]:s.shape[1])/(a*a),h=new TB("NHWC"===i?[o,u,l,c]:[o,c,u,l],a,i);return n.runWebGLProgram(h,[s],s.dtype)}};class CB{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=YD(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let u="",l="";n&&(u=r?`float activation(float a) {\\n          float b = getPreluActivationWeightsAtOutCoords();\\n          ${n}\\n        }`:s?`float activation(float a) {\\n          float b = getLeakyreluAlphaAtOutCoords();\\n          ${n}\\n        }`:`\\n          float activation(float x) {\\n            ${n}\\n          }\\n        `,l="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\\n      ${u}\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords.x;\\n        ivec2 xRCCorner = coords.yz * strides - pads;\\n        int d2 = coords.w;\\n        int d1 = d2 / ${o};\\n        int q = d2 - d1 * ${o};\\n\\n        int xRCorner = xRCCorner.x;\\n        int xCCorner = xRCCorner.y;\\n\\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\\n        for (int wR = 0; wR < ${a}; wR++) {\\n          int xR = xRCorner + wR * dilations[0];\\n\\n          if (xR < 0 || xR >= inDims[0]) {\\n            continue;\\n          }\\n\\n          for (int wC = 0; wC < ${i}; wC++) {\\n            int xC = xCCorner + wC * dilations[1];\\n\\n            if (xC < 0 || xC >= inDims[1]) {\\n              continue;\\n            }\\n\\n            float xVal = getX(batch, xR, xC, d1);\\n            float wVal = getW(wR, wC, d1, q);\\n            dotProd += xVal * wVal;\\n          }\\n        }\\n\\n        float result = dotProd;\\n        ${c}\\n        ${l}\\n        setOutput(result);\\n      }\\n    `}}class $B{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=YD(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,h=c;let d="\\n      int xR; int xC; int xCOffset;\\n      vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)d+=`\\n          vec4 xTexelC${2*e};\\n          int xTexelC${2*e}Ready;\\n          vec4 xTexelC${2*e+1};\\n          int xTexelC${2*e+1}Ready;\\n          vec4 xC${e};`;d+=`\\n    for (int r = 0; r < ${l}; r++) {\\n      `;for(let e=0;e<c;e++)d+=`\\n          xTexelC${2*e} = vec4(0.0);\\n          xTexelC${2*e}Ready = 0;\\n          xTexelC${2*e+1} = vec4(0.0);\\n          xTexelC${2*e+1}Ready = 0;\\n          xC${e} = vec4(0.0);`;d+="\\n        xR = xRCorner + r * dilations[0];\\n        if (xR >=0 && xR < inDims[0]) {\\n      ";for(let e=0;e<(h+1)/2;e++){const t=2*e;if(d+=`\\n          xC = xCCorner + ${t*u};\\n          `,1===o){if(t<c&&(i%2==1?(d+=`\\n                xCOffset = xC + 1;\\n                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\\n                  xTexelC${t} = getX(batch, xR, xCOffset, d1);\\n\\n                  // Need to manually clear unused channels in case\\n                  // we\'re reading from recycled texture.\\n                  if (xCOffset + 1 >= inDims[1]) {\\n                    xTexelC${t}.zw = vec2(0.0);\\n                  }\\n                  xTexelC${t}Ready = 1;\\n                }\\n              `,d+=1===u&&t>0?`\\n                xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\\n                `:`\\n                  xCOffset = xC + 1 - 2;\\n\\n                  if (xCOffset >= 0 && xCOffset < inDims[1]) {\\n                    previous = getX(batch, xR, xCOffset, d1);\\n\\n                    // Need to manually clear unused channels in case\\n                    // we\'re reading from recycled texture.\\n                    if (xCOffset + 1 >= inDims[1]) {\\n                      previous.zw = vec2(0.0);\\n                    }\\n\\n                    xC${t} = vec4(previous.zw, xTexelC${t}.xy);\\n                  } else {\\n                    xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\\n                  }\\n                  `):d+=`\\n                if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\\n                  xTexelC${t} = getX(batch, xR, xC, d1);\\n                  if (xC + 1 >= inDims[1]) {\\n                    xTexelC${t}.zw = vec2(0.0);\\n                  }\\n                  xTexelC${t}Ready = 1;\\n                }\\n\\n                xC${t} = xTexelC${t};\\n                `,t+1<c)){const e=i%2==0?te(u):u;u%2==0&&i%2==1||u%2!=0&&i%2!=1?(d+=`\\n                  xCOffset = xC + imod(pads[1], 2) + ${e};\\n\\n                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\\n                    xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\\n\\n                    // Need to manually clear unused channels in case\\n                    // we\'re reading from recycled texture.\\n                    if (xCOffset + 1 >= inDims[1]) {\\n                      xTexelC${t+1}.zw = vec2(0.0);\\n                    }\\n                    xTexelC${t+1}Ready = 1;\\n                  }\\n                  `,d+=u>1?`\\n                    xCOffset -= 2;\\n                    if (xCOffset >= 0 && xCOffset < inDims[1]) {\\n                     previous = getX(batch, xR, xCOffset, d1);\\n                     xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\\n                    } else {\\n                     xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\\n                    }\\n                    `:`\\n                    xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\\n                    `):d+=1===e?`\\n                    xC${t+1} = xTexelC${t};\\n                    `:`\\n                    xCOffset = xC + ${e};\\n\\n                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\\n                      xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\\n                      if (xCOffset + 1 >= inDims[1]) {\\n                        xTexelC${t+1}.zw = vec2(0.0);\\n                      }\\n                      xTexelC${t+1}Ready = 1;\\n                    }\\n\\n                    xC${t+1} = xTexelC${t+1};\\n                    `}}else t<c&&(i%2==1?(d+=`\\n                xCOffset = xC + 1 - strides[1];\\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\\n                  xTexelC${t} = getX(batch, xR, xCOffset, d1);\\n                  // Need to manually clear unused channels in case\\n                  // we\'re reading from recycled texture.\\n                  if (xCOffset + 1 >= inDims[1]) {\\n                    xTexelC${t}.zw = vec2(0.0);\\n                  }\\n                  xTexelC${t}Ready = 1;\\n                }\\n\\n                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\\n                  xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\\n                  // Need to manually clear unused channels in case\\n                  // we\'re reading from recycled texture.\\n                  if (xC + 2 >= inDims[1]) {\\n                    xTexelC${t+1}.zw = vec2(0.0);\\n                  }\\n                  xTexelC${t+1}Ready = 1;\\n                }\\n\\n                xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\\n              `,t+1<c&&(d+=`\\n                  final = vec4(0.0);\\n                  xCOffset = xC + 1 + strides[1];\\n                  if(xCOffset >= 0 && xCOffset < inDims[1]) {\\n                    final = getX(batch, xR, xCOffset, d1);\\n                  }\\n                  xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\\n                `)):(d+=`\\n                if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\\n                  xTexelC${t} = getX(batch, xR, xC, d1);\\n                  if (xC + 1 >= inDims[1]) {\\n                    xTexelC${t}.zw = vec2(0.0);\\n                  }\\n                  xTexelC${t}Ready = 1;\\n                }\\n\\n                xCOffset = xC + strides[1];\\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\\n                  xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\\n                  if (xCOffset + 1 >= inDims[1]) {\\n                    xTexelC${t+1}.zw = vec2(0.);\\n                  }\\n                  xTexelC${t+1}Ready = 1;\\n                }\\n\\n                xC${t} = vec4(\\n                  xTexelC${t}.xy, xTexelC${t+1}.xy);\\n              `,t+1<c&&(d+=`\\n                  xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\\n                `)));t<c&&(d+=`\\n            wTexel = getW(r, ${t}, d1, q);\\n            dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\\n          `,t+1<c&&(d+=`\\n              wTexel = getW(r, ${t+1}, d1, q);\\n              dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\\n            `))}d+="\\n    }\\n  ",d+="\\n      }\\n    ";let p="",f="";n&&(p=r?`vec4 activation(vec4 a) {\\n          vec4 b = getPreluActivationWeightsAtOutCoords();\\n          ${n}\\n        }`:s?`vec4 activation(vec4 a) {\\n          vec4 b = getLeakyreluAlphaAtOutCoords();\\n          ${n}\\n        }`:`vec4 activation(vec4 x) {\\n          ${n}\\n        }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\\n      ${p}
5057\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords.x;\\n        ivec2 xRCCorner = coords.yz * strides - pads;\\n        int d2 = coords.w;\\n        int d1 = d2 / ${a};\\n        int q = d2 - d1 * ${a};\\n        int xRCorner = xRCCorner.x;\\n        int xCCorner = xRCCorner.y;\\n\\n        //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\\n        vec4 dotProd = vec4(0.000000000000001);\\n\\n        ${d}\\n\\n        vec4 result = dotProd - vec4(0.000000000000001);\\n        ${m}\\n        ${f}\\n        setOutput(result);\\n      }\\n    `}}const AB={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;let c=u;null==c&&(c=[1,1]),ie(ec(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations \'${c}\'`);const h=jl(s.shape,a.shape,i,c,o,l,!0);let d;d=Xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?new $B(h):new CB(h);const p=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return n.runWebGLProgram(d,[s,a],"float32",p)}};class RB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int wR = coords.x;\\n        int wC = coords.y;\\n        int d1 = coords.z;\\n        int dm = coords.w;\\n        int d2 = d1 * ${a} + dm;\\n\\n        float dotProd = 0.0;\\n\\n        // TO DO: Vec4 over the batch size\\n        for (int b = 0; b < ${e.batchSize}; b++) {\\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\\n            int xR = wR + yR * ${t} - ${r};\\n\\n            if (xR < 0 || xR >= ${e.inHeight}) {\\n              continue;\\n            }\\n\\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\\n              int xC = wC + yC * ${n} - ${s};\\n\\n              if (xC < 0 || xC >= ${e.inWidth}) {\\n                continue;\\n              }\\n\\n              float dyValue = getDy(b, yR, yC, d2);\\n              float xValue = getX(b, xR, xC, d1);\\n              dotProd += (xValue * dyValue);\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class _B{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\\n      const ivec2 pads = ivec2(${a}, ${i});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int d1 = coords[3];\\n        ivec2 dyCorner = coords.yz - pads;\\n        int dyRCorner = dyCorner.x;\\n        int dyCCorner = dyCorner.y;\\n\\n        float dotProd = 0.0;\\n\\n        for (int wR = 0; wR < ${t}; wR++) {\\n          float dyR = float(dyRCorner + wR) / ${r}.0;\\n\\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\\n            continue;\\n          }\\n          int idyR = int(dyR);\\n\\n          int wRPerm = ${t} - 1 - wR;\\n\\n          for (int wC = 0; wC < ${n}; wC++) {\\n            float dyC = float(dyCCorner + wC) / ${s}.0;\\n\\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                fract(dyC) > 0.0) {\\n              continue;\\n            }\\n            int idyC = int(dyC);\\n\\n            int wCPerm = ${n} - 1 - wC;\\n\\n            // TO DO: Vec4 over the channelMul\\n            for (int dm = 0; dm < ${o}; dm++) {\\n              int d2 = d1 * ${o} + dm;\\n              float xValue = getDy(batch, idyR, idyC, d2);\\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\\n              dotProd += xValue * wValue;\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}const MB={kernelName:Gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r,h=jl(s.shape,c,i,o,u,l,!0),d=new RB(h);return n.runWebGLProgram(d,[s,a],"float32")}},FB={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r,h=jl(c,a.shape,i,o,u,l,!0),d=new _B(h);return n.runWebGLProgram(d,[s,a],"float32")}};class DB{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\\n      void main() {\\n          ivec2 coords = getOutputCoords();\\n          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\\n          setOutput(val);\\n      }\\n    "}}const OB={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=le(r.shape),i=fz({inputs:{x:r},backend:n,attrs:{shape:[a]}}),o=new DB(a),u=n.runWebGLProgram(o,[i],i.dtype),l=fz({inputs:{x:u},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),l}};class LB{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:u,dilationWidth:l}=e,{top:c,left:h}=r;this.userCode=`\\n      const ivec2 strides = ivec2(${s}, ${a});\\n      const ivec2 pads = ivec2(${c}, ${h});\\n      const float neg_infinity = -3.4e38;\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int d1 = coords.w;\\n        ivec2 outTopLeftCorner =\\n            coords.yz * strides - pads;\\n        int hBeg = outTopLeftCorner.x;\\n        int wBeg = outTopLeftCorner.y;\\n\\n        float curVal = neg_infinity;\\n        for (int h = 0; h < ${i}; h++) {\\n          int hIn = hBeg + h * ${u};\\n\\n          if (hIn >= 0 && hIn < ${t}) {\\n            for (int w = 0; w < ${o}; w++) {\\n              int wIn = wBeg + w * ${l};\\n\\n              if (wIn >= 0 && wIn < ${n}) {\\n                float xVal = getX(batch, hIn, wIn, d1);\\n                float wVal = getW(h, w, d1);\\n\\n                float val = xVal + wVal;\\n                if (val > curVal) {\\n                  curVal = val;\\n                }\\n              }\\n            }\\n          }\\n        }\\n\\n        float result = curVal;\\n        setOutput(result);\\n      }\\n    `}}const zB={kernelName:qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r,l=Wl(s.shape,a.shape,i,o,"NHWC",u);let c;const h=new LB(l);c=n.runWebGLProgram(h,[s,a],"float32");const d=fz({inputs:{x:c},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(c),d}},PB={kernelName:Zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:i,summedDims:o,idDims:u}=Sm(s,a.length);Tm(i.length,u,a);const{path:l,steps:c}=Em(o,u),h=c.length;let d=null,p=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:r}=Nm(p,u[t]);let s;Cm(e)?s=a[t]:(s=Sz({inputs:{x:a[t]},backend:n,attrs:{perm:e}}
vendor: 16,214 bytes, line 5057
5057),f.push(s));const i=s.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);de(s.shape,i)||(s=fz({inputs:{x:s},backend:n,attrs:{shape:i}}),f.push(s)),null===d?d=s:(d=dz({inputs:{a:s,b:d},backend:n}),f.push(d))}e<h-1&&(l[e]>=0&&(d=kz({inputs:{x:d},backend:n,attrs:{axis:l[e]-(i.length-p),keepDims:!1}}),f.push(d)),p--)}for(const e of f)e!==d&&n.disposeIntermediateTensorInfo(e);return d}},BB=iz({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\\n  vec4 result;\\n\\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\\n\\n  return result;\\n"}),VB={kernelName:Qt,backendName:"webgl",kernelFunc:BB},UB={kernelName:en,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new KL("\\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\\n",r.shape,s.shape):new jL("return (b >= 0.0) ? a : a * (b + 1.0);",r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)}},WB=oz({opSnippet:"return float(a == b);",packedOpSnippet:"\\n  return vec4(equal(a, b));\\n",dtype:"bool",cpuKernelImpl:FO}),GB={kernelName:nn,backendName:"webgl",kernelFunc:WB},HB=iz({opSnippet:`\\n  // Error function is calculated approximately with elementary function.\\n  // See "Handbook of Mathematical Functions with Formulas,\\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\\n  float p = ${im};\\n  float a1 = ${om};\\n  float a2 = ${um};\\n  float a3 = ${lm};\\n  float a4 = ${cm};\\n  float a5 = ${hm};\\n\\n  float sign = sign(x);\\n  x = abs(x);\\n  float t = 1.0 / (1.0 + p * x);\\n  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\\n`}),jB={kernelName:tn,backendName:"webgl",kernelFunc:HB},qB=iz({opSnippet:az+"\\n  return exp(x);\\n",packedOpSnippet:"\\n  vec4 result = exp(x);\\n  bvec4 isNaN = isnan(x);\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n",cpuKernelImpl:DO,dtype:"float32"}),KB={kernelName:rn,backendName:"webgl",kernelFunc:qB};function XB(e){const{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let u=s;return s<0&&(ie(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+s+1),o.splice(u,0,1),fz({inputs:{x:a},backend:r,attrs:{shape:o}})}const YB={kernelName:sn,backendName:"webgl",kernelFunc:XB},JB="return exp(x) - 1.0;",ZB=iz({opSnippet:JB,packedOpSnippet:JB,cpuKernelImpl:OO}),QB={kernelName:an,backendName:"webgl",kernelFunc:ZB};class eV{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\\n      const float exponentMultiplier = ${s};\\n\\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\\n        ${i}\\n      }\\n\\n      float mulMatDFT(int batch, int index) {\\n        float indexRatio = float(index) / float(${r});\\n        float exponentMultiplierTimesIndexRatio =\\n            exponentMultiplier * indexRatio;\\n\\n        float result = 0.0;\\n\\n        for (int i = 0; i < ${r}; i++) {\\n          // x = (-2|2 * PI / N) * index * i;\\n          float x = exponentMultiplierTimesIndexRatio * float(i);\\n          float expR = cos(x);\\n          float expI = sin(x);\\n          float real = getReal(batch, i);\\n          float imag = getImag(batch, i);\\n\\n          result +=\\n              unaryOpComplex(real, expR, imag, expI) / ${a};\\n        }\\n\\n        return result;\\n      }\\n\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        setOutput(mulMatDFT(coords[0], coords[1]));\\n      }\\n    `}}function tV(e,t,n){const r=n.texData.get(e.dataId),s=le(e.shape),a=e.shape[e.shape.length-1],i=fz({inputs:{x:e},backend:n,attrs:{shape:[s/a,a]}}),o=i.shape,u=new eV("real",o,t),l=new eV("imag",o,t),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:o},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(u,c,"float32"),d=n.runWebGLProgram(l,c,"float32"),p=JL({inputs:{real:h,imag:d},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d);const f=fz({inputs:{x:p},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(p),f}const nV={kernelName:on,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return tV(r,!1,n)}};class rV{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\\n      void main() {\\n        // Input can be obtained from uniform value.\\n        setOutput(value);\\n      }\\n    "}}function sV(e){const{backend:t,attrs:n}=e,{shape:r,value:s}=n;let{dtype:a}=n;if(a=a||_e(s),"string"===a){const e=Ie(a,le(r));return e.fill(s),t.makeTensorInfo(r,a,e)}{const e=new rV(r,s),n=[[s]];return t.runWebGLProgram(e,[],a,n)}}const aV={kernelName:un,backendName:"webgl",kernelFunc:sV};class iV{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\\n        void main() {\\n          ivec4 coords = getOutputCoords();\\n          int x = coords[2];\\n\\n          int coordX = ${t} - x - 1;\\n          float outputValue;\\n          if(coordX >= 0 && coordX < ${t}) {\\n            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\\n          } else {\\n            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\\n          }\\n          setOutput(outputValue);\\n        }\\n    `}}const oV={kernelName:ln,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,s=new iV(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},uV="return floor(x);",lV=iz({opSnippet:uV,packedOpSnippet:uV,cpuKernelImpl:LO}),cV={kernelName:cn,backendName:"webgl",kernelFunc:lV},hV=oz({opSnippet:"\\n  float s = sign(a) * sign(b);\\n  int ia = round(a);\\n  int ib = round(b);\\n  if (ib != 0) {\\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\\n    return float(idiv(ia, ib, s));\\n  } else {\\n    return NAN;\\n  }\\n",packedOpSnippet:"\\n  ivec4 ia = round(a);\\n  ivec4 ib = round(b);\\n  bvec4 cond = notEqual(ib, ivec4(0));\\n  ivec4 result = ivec4(0);\\n  vec4 s = sign(a) * sign(b);\\n\\n  // Windows (D3D) wants guaranteed non-zero int division at compile-time.\\n  if (cond[0]) {\\n    result[0] = idiv(ia[0], ib[0], s[0]);\\n  }\\n  if (cond[1]) {\\n    result[1] = idiv(ia[1], ib[1], s[1]);\\n  }\\n  if (cond[2]) {\\n    result[2] = idiv(ia[2], ib[2], s[2]);\\n  }\\n  if (cond[3]) {\\n    result[3] = idiv(ia[3], ib[3], s[3]);\\n  }\\n  return vec4(result);\\n",dtype:"int32"}),dV={kernelName:hn,backendName:"webgl",kernelFunc:hV};class pV{constructor(e){this.variableNames=["A"];const t=$D(),[n,r]=e;this.outputShape=e,this.userCode=`\\n      void main() {\\n        ivec3 coords = getOutputCoords();\\n        int texR = coords[0];\\n        int texC = coords[1];\\n        int depth = coords[2];\\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\\n\\n        vec4 values = ${t.texture2D}(A, uv);\\n        float value;\\n        if (depth == 0) {\\n          value = values.r;\\n        } else if (depth == 1) {\\n          value = values.g;\\n        } else if (depth == 2) {\\n          value = values.b;\\n        } else if (depth == 3) {\\n          value = values.a;\\n        }\\n\\n        setOutput(floor(value * 255.0 + 0.5));\\n      }\\n    `}}class fV{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=$D(),[n,r]=e;this.outputShape=e,this.userCode=`\\n      void main() {\\n        ivec3 coords = getOutputCoords();\\n        int texR = coords[0];\\n        int texC = coords[1];\\n        int depth = coords[2];\\n\\n        vec4 result = vec4(0.);\\n\\n        for(int row=0; row<=1; row++) {\\n          for(int col=0; col<=1; col++) {\\n            texC = coords[1] + row;\\n            depth = coords[2] + col;\\n\\n            vec2 uv = (vec2(texC, texR) + halfCR) /\\n                       vec2(${r}.0, ${n}.0);\\n            vec4 values = ${t.texture2D}(A, uv);\\n            float value;\\n            if (depth == 0) {\\n              value = values.r;\\n            } else if (depth == 1) {\\n              value = values.g;\\n            } else if (depth == 2) {\\n              value = values.b;\\n            } else if (depth == 3) {\\n              value = values.a;\\n            }\\n\\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\\n          }\\n        }\\n\\n        ${t.output} = result;\\n      }\\n    `}}const mV={kernelName:fs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:s}=t;const{numChannels:a}=r,i="undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&s instanceof HTMLImageElement,[u,l]=i?[s.videoWidth,s.videoHeight]:[s.width,s.height],c=[l,u],h=[l,u,a];if(o||i){const e=Xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=gV&&e===yV||(yV=e,gV=document.createElement("canvas").getContext("2d",{willReadFrequently:yV})),gV.canvas.width=u,gV.canvas.height=l,gV.drawImage(s,0,0,u,l),s=gV.canvas}const d=n.makeTensorInfo(c,"int32");n.texData.get(d.dataId).usage=SF.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),s);const p=Xe().getBool("WEBGL_PACK")?new fV(h):new pV(h),f=n.runWebGLProgram(p,[d],"int32");return n.disposeData(d.dataId),f}};let gV,yV=Xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const bV={kernelName:ys,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=r,m=nc(c),g=jl(s.shape,a.shape,u,h,l,d,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===p,k=()=>{const e=[s,a],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=fz({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",qs(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Xe().getBool("WEBGL_EXP_CONV")){const e=p?uz(p,!0):null,t=new YP(g,x,e,w,v),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],s=k();y=n.runWebGLProgram(t,s,"float32",r)}else if(Xe().getBool("WEBGL_CONV_IM2COL"))y=eB({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:p,preluActivationWeights:o,leakyreluAlpha:f});else{const e=p?uz(p,!1):null,t=new KP(g,x,e,w,v),r=k();y=n.runWebGLProgram(t,r,"float32")}else y=QP({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:p,preluActivationWeights:o,leakyreluAlpha:f});const I=fz({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(e=>n.disposeIntermediateTensorInfo(e)),I}},xV={kernelName:bs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=r,f=[];let m=c;null==m&&(m=[1,1]),ie(ec(u,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations \'${m}\'`);const g=jl(s.shape,a.shape,u,m,l,h,!0),y=Xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=d?uz(d,y):null,x=[s,a],w=null!=i,v=null!=o,k="leakyrelu"===d;if(w&&x.push(i),v&&x.push(o),k){const e=n.makeTensorInfo([],"float32",qs(p,"float32"));x.push(e),f.push(e)}let I;I=y?new $B(g,w,b,v,k):new CB(g,w,b,v,k);const S=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],N=n.runWebGLProgram(I,x,"float32",S);return f.forEach(e=>n.disposeIntermediateTensorInfo(e)),N}};class wV{constructor(e,t,n,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=n;const s=GD(n.length);let a="\\n    int index;";for(let e=0;e<this.sliceDim;e++)a+=`\\n          index = round(getIndices(coords[0], ${e}));\\n          out_of_bounds = out_of_bounds || index < 0;\\n          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[e]};\\n          flattenIndex += index * ${this.strides[e]};`;this.userCode=`\\n         void main() {\\n          ${s} coords = getOutputCoords();\\n          int flattenIndex = 0;\\n          bool out_of_bounds = false;\\n\\n          ${a}\\n\\n          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\\n        }\\n      `}}const vV={kernelName:fn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,i=a[a.length-1],o=le(r.shape),[u,l,c,h]=ju(r,s),d=fz({inputs:{x:s},backend:n,attrs:{shape:[l,i]}}),p=fz({inputs:{x:r},backend:n,attrs:{shape:[le(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,s])||"string"===r.dtype){const e=n.readSync(s.dataId),t=n.bufferSync(r),a=zO(e,t,r.dtype,l,i,c,h,r.shape,o);return n.makeTensorInfo(u,r.dtype,a.values)}const f=new wV(i,h,[l,c],r.shape),m=n.runWebGLProgram(f,[p,d],p.dtype),g=fz({inputs:{x:m},backend:n,attrs:{shape:u}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),g}};class kV{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=GD(this.rank),r=function(e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;r<e.length;r++)2===r?n.push("index"):n.push(`${t[r]}`);return n.join()}(e);this.userCode=`\\n      void main() {\\n        ${n} resRC = getOutputCoords();\\n        int index = int(getIndices(resRC.x, resRC.z));\\n        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\\n        setOutput(inBounds * getA(${r}));\\n      }\\n    `}}function IV(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:i,batchDims:o}=r,u=we(i,s.shape)[0];if(Xe().get("DEBUG")){const e=n.readSync(a.dataId),t=s.shape[u];for(let n=0;n<e.length;++n){const r=e[n];ie(r<=t-1&&r>=0,()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`)}}const l=Hm(s,a,u,o),c=le(a.shape),h=[],d=fz({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),p=fz({inputs:{x:a},backend:n,attrs:{shape:[l.batchSize,c/l.batchSize]}});h.push(d),h.push(p);const f=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([s,a])||"string"===s.dtype){const e=n.bufferSync(p),t=n.bufferSync(d),r=PO(t,e,f);return h.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(l.outputShape,r.dtype,r.values)}const m=new kV(d.shape,f),g=n.runWebGLProgram(m,[d,p],d.dtype);h.push(g);const y=fz({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return h.forEach(e=>n.disposeIntermediateTensorInfo(e)),y}const SV={kernelName:pn,backendName:"webgl",kernelFunc:IV},NV=oz({opSnippet:"return float(a > b);",packedOpSnippet:"\\n  return vec4(greaterThan(a, b));\\n",cpuKernelImpl:BO,dtype:"bool"}),TV={kernelName:mn,backendName:"webgl",kernelFunc:NV},EV=oz({opSnippet:"return float(a >= b);",packedOpSnippet:"\\n  return vec4(greaterThanEqual(a, b));\\n",dtype:"bool",cpuKernelImpl:VO}),CV={kernelName:gn,backendName:"webgl",kernelFunc:EV},$V={kernelName:bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}
5057=e,{input:r}=t;return tV(r,!0,n)}},AV=iz({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),RV={kernelName:wn,backendName:"webgl",kernelFunc:AV},_V=iz({opSnippet:"return float(isinf(x));",dtype:"bool"}),MV={kernelName:vn,backendName:"webgl",kernelFunc:_V},FV=iz({opSnippet:"return float(isnan(x));",dtype:"bool"}),DV={kernelName:kn,backendName:"webgl",kernelFunc:FV},OV=oz({opSnippet:"return float(a < b);",packedOpSnippet:"\\n  return vec4(lessThan(a, b));\\n",cpuKernelImpl:UO,dtype:"bool"}),LV={kernelName:Sn,backendName:"webgl",kernelFunc:OV},zV=oz({opSnippet:"return float(a <= b);",packedOpSnippet:"\\n  return vec4(lessThanEqual(a, b));\\n",cpuKernelImpl:WO,dtype:"bool"}),PV={kernelName:Nn,backendName:"webgl",kernelFunc:zV},BV={kernelName:Tn,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,i=GO(r,s,a);return t.makeTensorInfo([i.length],"float32",i)}},VV=iz({opSnippet:az+"\\n  return x < 0.0 ? 0./0. : log(x);\\n",packedOpSnippet:"\\n  vec4 result = log(x);\\n  bvec4 isNaN = isnan(x);\\n  result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\\n  result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\\n  result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\\n  result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\\n  return result;\\n",cpuKernelImpl:HO}),UV={kernelName:En,backendName:"webgl",kernelFunc:VV},WV=iz({opSnippet:az+"\\n  return log(1.0 + x);\\n"}),GV={kernelName:Cn,backendName:"webgl",kernelFunc:WV},HV=oz({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\\n  return vec4(\\n    vec4(greaterThanEqual(a, vec4(1.0))) *\\n    vec4(greaterThanEqual(b, vec4(1.0))));\\n",dtype:"bool"}),jV={kernelName:$n,backendName:"webgl",kernelFunc:HV},qV=iz({opSnippet:"return float(!(x >= 1.0));"}),KV={kernelName:An,backendName:"webgl",kernelFunc:qV},XV=oz({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\\n  return min(\\n    vec4(greaterThanEqual(a, vec4(1.0))) +\\n    vec4(greaterThanEqual(b, vec4(1.0))),\\n    vec4(1.0));\\n",dtype:"bool"}),YV={kernelName:Rn,backendName:"webgl",kernelFunc:XV};class JV{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${u})`:1===s?`1.0/(${u})`:`exp(log(${u}) * float(-${s}));`,this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int r = coords[1];\\n        int c = coords[2];\\n        int d = coords[3];\\n        float x = getX(b, r, c, d);\\n        float sum = 0.0;\\n        for (int j = -${a}; j <= ${a}; j++) {\\n          int idx = d + j;\\n          if (idx >= 0 && idx <=  ${i}) {\\n            float z = getX(b, r, c, idx);\\n            sum += z * z;\\n          }\\n        }\\n        float val = x * ${o};\\n        setOutput(val);\\n      }\\n    `}}class ZV{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${u})`:1===s?`1.0/(${u})`:`exp(log(${u}) * float(-${s}));`,this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords.x;\\n        int r = coords.y;\\n        int c = coords.z;\\n        int d = coords.w;\\n\\n        bool hasNextCol = d < ${this.outputShape[3]};\\n        bool hasNextRow = c < ${this.outputShape[2]};\\n\\n        vec4 sum = vec4(0.);\\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\\n\\n        vec4 xAtOutputCoords = vec4(\\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\\n          hasNextCol ?\\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\\n          hasNextRow ?\\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\\n        );\\n\\n        int firstChannel = d - ${a};\\n        vec2 cache = vec2(0.);\\n        if(firstChannel >= 0){\\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\\n            if(hasNextRow){\\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\\n            }\\n        }
5057\\n\\n        ivec2 depth = ivec2(d, d + 1);\\n        for (int j = - ${a}; j <= ${a}; j++) {\\n          ivec2 idx = depth + j;\\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\\n\\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\\n\\n          if(depthInRange || depthPlusOneInRange){\\n            vec4 z = vec4(0.);\\n            vec4 xFragAtCurrentDepth;\\n            z.xz = cache.xy;\\n            if(depthPlusOneInRange && hasNextCol){\\n              xFragAtCurrentDepth = idx.y != d ?\\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\\n              if(hasNextRow){\\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\\n              }\\n            }\\n            cache.xy = z.yw;\\n            sum += z * z;\\n          }\\n        }\\n        vec4 result = xAtOutputCoords * ${o};\\n        setOutput(result);\\n      }\\n    `}}const QV={kernelName:Dn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:u}=r,l=Xe().getBool("WEBGL_PACK_NORMALIZATION")?new ZV(s.shape,a,i,o,u):new JV(s.shape,a,i,o,u);return n.runWebGLProgram(l,[s],s.dtype)}};class eU{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int r = coords[1];\\n        int c = coords[2];\\n\\n        float result = 0.0;\\n        for (int d = 0; d < ${this.depth}; ++d) {\\n          int depthBegin = int(max(0.0, float(d - ${t})));\\n          int depthEnd = int(min(float(${this.depth}),\\n              float(d + ${t} + 1)));\\n\\n          const int MIN_DEPTH_BEGIN = 0;\\n          const int MAX_DEPTH_END = ${this.depth};\\n\\n          float norm = 0.0;\\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\\n            if (k < depthBegin){\\n              continue;\\n            }\\n            else if (k >= depthBegin && k < depthEnd) {\\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\\n            }\\n            else {\\n              break;\\n            }\\n          }\\n\\n          norm = float(${r}) * norm + float(${n});\\n\\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\\n            if (k < depthBegin){\\n              continue;\\n            }\\n            else if (k >= depthBegin && k < depthEnd){\\n              float dyi = -2.0 * float(${r})\\n                * float(${s})\\n                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\\n                / norm;\\n              if (k == d) {\\n                dyi += pow(norm, -1.0 * ${s});\\n              }\\n              if (k == coords[3]) {\\n                dyi *= getDy(b, r, c, d);\\n                result += dyi;\\n              }\\n            }\\n            else {\\n              break;\\n            }\\n          }\\n      }\\n      setOutput(result);\\n      }\\n    `}}const tU={kernelName:On,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r,h=new eU(s.shape,o,u,l,c);return n.runWebGLProgram(h,[s,a,i],s.dtype)}};function nU(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=nh(l,o),h=null!=c,d=n.shouldExecuteOnCPU([s]);let p=s;if(h){if(d){const e=n.texData.get(p.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=s.shape[c[e]];const r=wL(e,s.shape,s.dtype,c,t);p=n.makeTensorInfo(t,s.dtype),n.texData.get(p.dataId).values=r}else p=vz(s,c,n);l=sh(l.length,o)}th("max",l,o);const[f,m]=Qc(p.shape,l);let g,y=f;if(i&&(y=eh(f,u)),d){const e=n.texData.get(p.dataId).values,t=jO(e,le(m),y,s.dtype);g=n.makeTensorInfo(y,s.dtype),n.texData.get(g.dataId).values=t}else g=function(e,t,n,r){const s=le(t),a=fz({inputs:{x:e},attrs:{shape:[le(e.shape)/s,s]},backend:r}),i=bz(a,e.dtype,"max",r),o=fz({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}(p,m,y,n);return h&&n.disposeIntermediateTensorInfo(p),g}const rU={kernelName:zn,backendName:"webgl",kernelFunc:nU},sU=oz({opSnippet:HL+"\\n  return max(a, b);\\n",packedOpSnippet:"\\n  vec4 result = vec4(max(a, b));\\n  bvec4 isNaNA = isnan(a);\\n  bvec4 isNaNB = isnan(b);\\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\\n  "+qL+"\\n  return result;\\n",cpuKernelImpl:qO}),aU={kernelName:Pn,backendName:"webgl",kernelFunc:sU},iU={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;ED(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(ec(i,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations \'1\'`);const l=Gl(s.shape,a,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&de(l.inShape,l.outShape))return XL({input
vendor: 5,229 bytes, line 5057
5057s:{x:s},backend:n});const c=new aP(l,"max",!1);return n.runWebGLProgram(c,[s],s.dtype)}},oU={kernelName:Un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dataFormat:u,dimRoundingMode:l}=r,c=Hl(s.shape,a,i,[1,1,1],o,l,u),h=new iP(c,"max",!1);return n.runWebGLProgram(h,[s],s.dtype)}};class uU{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,o=a-1-e.padInfo.left,u=s*a-1;this.userCode=`\\n      const ivec2 pads = ivec2(${i}, ${o});\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n\\n        ivec2 dyRCCorner = coords.yz - pads;\\n        int dyRCorner = dyRCCorner.x;\\n        int dyCCorner = dyRCCorner.y;\\n\\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n        for (int wR = 0; wR < ${s};\\n          wR += ${r}) {\\n          float dyR = float(dyRCorner + wR) / ${t}.0;\\n\\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\\n            continue;\\n          }\\n          int idyR = int(dyR);\\n\\n          for (int wC = 0; wC < ${a}; wC++) {\\n            float dyC = float(dyCCorner + wC) / ${n}.0;\\n\\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                fract(dyC) > 0.0) {\\n              continue;\\n            }\\n            int idyC = int(dyC);\\n\\n            float dyValue = getDy(b, idyR, idyC, d);\\n            int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));\\n\\n            // Get the current value, check it against the value from the\\n            // position matrix.\\n            int curPosValue = wR * ${a} + wC;\\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\\n\\n            dotProd += dyValue * mask;\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}class lU{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=u-1-e.padInfo.top,d=l-1-e.padInfo.left,p=o*u*l-1;this.userCode=`\\n      const ivec3 pads = ivec3(${c}, ${h}, ${d});\\n\\n      void main() {\\n        ivec5 coords = getOutputCoords();\\n        int batch = coords.x;\\n        int ch = coords.u;\\n\\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\\n        int dyDCorner = dyCorner.x;\\n        int dyRCorner = dyCorner.y;\\n        int dyCCorner = dyCorner.z;\\n\\n        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\\n        // dx(xD, xR, xC, ch).\\n        // ? = to be determined. : = across all values in that axis.\\n        float dotProd = 0.0;\\n\\n        for (int wD = 0; wD < ${o};\\n           wD += ${s}) {\\n          float dyD = float(dyDCorner + wD) / ${t}.0;\\n\\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\\n            continue;\\n          }\\n          int idyD = int(dyD);\\n\\n          for (int wR = 0; wR < ${u};\\n              wR += ${a}) {\\n            float dyR = float(dyRCorner + wR) / ${n}.0;\\n\\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\\n                fract(dyR) > 0.0) {\\n              continue;\\n            }\\n            int idyR = int(dyR);\\n\\n            for (int wC = 0; wC < ${l};\\n                wC += ${i}) {\\n              float dyC = float(dyCCorner + wC) / ${r}.0;\\n\\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\\n                  fract(dyC) > 0.0) {\\n                continue;\\n              }\\n              int idyC = int(dyC);\\n\\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\\n              int maxPosValue = ${p} -\\n                  int(getMaxPos(batch, idyD, idyR, idyC, ch));\\n\\n              // Get the current value, check it against the value from the\\n              // position matrix.\\n              int curPosValue =\\n                  wD * ${u} * ${l} +\\n                  wR * ${l} + wC;\\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\\n\\n              dotProd += dyValue * mask;\\n            }\\n          }\\n        }\\n        setOutput(dotProd);\\n      }\\n    `}}const cU={kernelName:Wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,h=Hl(i.shape,o,u,[1,1,1],l,c),d=new iP(h,"max",!0),p=n.runWebGLProgram(d,[i],i.dtype),f=new lU(h),m=n.runWebGLProgram(f,[s,p],i.dtype);return n.disposeIntermediateTensorInfo(p),m}},hU={kernelName:Vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;ED([a,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:h}=r,d=Gl(o.shape,u,l,1,c,h),p=new aP(d,"max",!0),f=n.runWebGLProgram(p,[o
5057],o.dtype),m=new uU(d),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}},dU={kernelName:Gn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,u=n;ie(4===r.shape.length,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);const l=[1,1];ie(ec(a,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations \'${l}\'`);const c=Gl(r.shape,s,a,l,i),[h,d]=function(e,t,n,r){let s=new aP(n,"max",!1);const a=r.runWebGLProgram(s,[e],"float32");return s=new aP(n,"max",!0,!0,t),[a,r.runWebGLProgram(s,[e],"float32")]}(r,o,c,u);return[h,d]}},pU={kernelName:Hn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:s,axis:a}=t,i=n,o=r.shape.length,u=we(a,r.shape);let l=u;const c=nh(l,o),h=null!=c,d=i.shouldExecuteOnCPU([r]),p=[];let f=r;if(h){if(d){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const n=wL(e,r.shape,r.dtype,c,t);f=i.makeTensorInfo(t,r.dtype),i.texData.get(f.dataId).values=n}else f=vz(r,c,i);p.push(f),l=sh(l.length,o)}th("sum",l,o);const[m,g]=Qc(f.shape,l);let y=m;s&&(y=eh(m,u));const b=function(e,t,n,r){const s=le(t),a=fz({inputs:{x:e},attrs:{shape:[le(e.shape)/s,s]},backend:r}),i=bz(a,"float32","mean",r),o=fz({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}(f,g,y,i);for(const e of p)i.disposeIntermediateTensorInfo(e);return b}},fU={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=nh(l,o);let h=s;null!=c&&(h=Sz({inputs:{x:s},backend:n,attrs:{perm:c}}),l=sh(l.length,s.shape.length)),th("min",l,o);const[d,p]=Qc(h.shape,l),f=fz({inputs:{x:h},backend:n,attrs:{shape:[-1,le(p)]}}),m=bz(f,f.dtype,"min",n);let g;return g=fz(i?{inputs:{x:m},backend:n,attrs:{shape:eh(d,u)}}:{inputs:{x:m},backend:n,attrs:{shape:d}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},mU=oz({opSnippet:HL+"\\n  return min(a, b);\\n",packedOpSnippet:"\\n  vec4 result = vec4(min(a, b));\\n  bvec4 isNaNA = isnan(a);\\n  bvec4 isNaNB = isnan(b);\\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\\n  "+qL+"\\n  return result;\\n",cpuKernelImpl:KO}),gU={kernelName:qn,backendName:"webgl",kernelFunc:mU};class yU{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,s=GD(r),a=t.map(e=>e[0]).join(","),i=t.map((t,n)=>t[0]+e[n]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===n?0:1;this.userCode=1!==r?`\\n      ${s} start = ${s}(${a});\\n      ${s} end = ${s}(${i});\\n\\n      void main() {\\n        ${s} outC = getOutputCoords();\\n        for (int i = 0; i < ${r}; i++) {\\n          if (outC[i] < start[i]) {\\n            outC[i] = start[i] * 2 - outC[i] - ${u};\\n          } else if(outC[i] >= end[i]) {\\n            outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};\\n          }\\n        }\\n        ${s} coords = outC - start;\\n        setOutput(getX(${o}));\\n      }\\n    `:`\\n        int start = ${a};\\n        int end = ${i};\\n\\n        void main() {\\n          int outC = getOutputCoords();\\n          if (outC < start) {\\n            outC = start * 2 - outC - ${u};\\n          } else if(outC >= end) {\\n            outC = (end - 1) * 2 - outC + ${u};\\n          }\\n          setOutput(getX(outC - start));\\n        }\\n      `}}class bU{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,s=GD(r),a=t.map(e=>e[0]).join(","),i=t.map((t,n)=>t[0]+e[n]).join(","),o=IL("rc",r),u=IL("source",r),l=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,h="reflect"===n?0:1;let d="";if(1===r){const e=`\\n        ${s} source = rc;\\n        if (source < start) {\\n          source = start * 2 - source - ${h};\\n        } else if (source >
5057= end) {\\n          source = (end - 1) * 2 - source + ${h};\\n        }\\n        source -= start;\\n      `;d=`\\n        ${s} rc = outputLoc;\\n        ${e}\\n        result[0] = getChannel(getX(${u.join()}), ${c});\\n        ${o[r-1]} += 1;\\n        if(${l}) {\\n          ${e}\\n          result[1] = getChannel(getX(${u.join()}), ${c});\\n        }\\n      `}else{const e=`\\n        ${s} source = rc;\\n        ${s} lt = ${s}(lessThan(source, start));\\n        ${s} gte = ${s}(greaterThanEqual(source, end));\\n        ${s} orig = 1 - (lt + gte);\\n        source = orig * source +\\n                lt * (start * 2 - source - ${h}) +\\n                gte * ((end - 1) * 2 - source + ${h});\\n        source -= start;\\n      `;d=`\\n        ${s} rc = outputLoc;\\n        ${e}\\n        result[0] = getChannel(getX(${u.join()}), ${c});\\n        ${o[r-1]} += 1;\\n        if(${l}) {\\n          ${e}\\n          result[1] = getChannel(getX(${u.join()}), ${c});\\n        }\\n        rc = outputLoc;\\n        ${o[r-2]} += 1;\\n        if(${o[r-2]} < ${this.outputShape[r-2]}) {\\n          ${e}\\n          result[2] = getChannel(getX(${u.join()}), ${c});\\n          ${o[r-1]} += 1;\\n          if(${l}) {\\n            ${e}\\n            result[3] = getChannel(getX(${u.join()}), ${c});\\n          }\\n        }\\n      `}this.userCode=`\\n      const ${s} start = ${s}(${a});\\n      const ${s} end = ${s}(${i});\\n\\n      void main() {\\n        ${s} outputLoc = getOutputCoords();\\n        vec4 result = vec4(0.);\\n        ${d}\\n        setOutput(result);\\n      }\\n    `}}const xU={kernelName:Kn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:s,mode:a}=n,i=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new bU(r.shape,s,a):new yU(r.shape,s,a);return t.runWebGLProgram(i,[r],r.dtype)}},wU=oz({opSnippet:"if (b == 0.0) return NAN;\\n  return mod(a, b);",packedOpSnippet:"\\n  vec4 result = mod(a, b);\\n  bvec4 isNaN = equal(b, vec4(0.0));\\n  "+qL+"\\n  return result;\\n"}),vU={kernelName:Xn,backendName:"webgl",kernelFunc:wU};class kU{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int batch = coords[0];\\n\\n        float r = random(seed);\\n        float cdf = 0.0;\\n\\n        for (int i = 0; i < ${t-1}; i++) {\\n          cdf += getProbs(batch, i);\\n\\n          if (r < cdf) {\\n            setOutput(float(i));\\n            return;\\n          }\\n        }\\n\\n        // If no other event happened, last event happened.\\n        setOutput(float(${t-1}));\\n      }\\n    `}}const IU=oz({opSnippet:"\\nif (a == b) {\\n  return 1.0;\\n};\\nreturn a / b;",packedOpSnippet:"\\n  // vec4 one = vec4(equal(a, b));\\n  // return one + (vec4(1.0) - one) * a / b;\\n  vec4 result = a / b;\\n  if(a.x == b.x) {\\n    result.x = 1.;\\n  }\\n  if(a.y == b.y) {\\n    result.y = 1.;\\n  }\\n  if(a.z == b.z) {\\n    result.z = 1.;\\n  }\\n  if(a.w == b.w) {\\n    result.w = 1.;\\n  }\\n\\n  return result;\\n",checkOutOfBounds:!0}),SU={kernelName:Jt,backendName:"webgl",kernelFunc:IU},NU="return a - b;",TU=oz({opSnippet:NU,packedOpSnippet:NU,supportsComplex:!0,cpuKernelImpl:yL}),EU={kernelName:ts,backendName:"webgl",kernelFunc:TU};function CU(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=we([a],s.shape),o=nU({inputs:{x:s},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),u=eh(o.shape,i),l=fz({inputs:{x:o},backend:n,attrs:{shape:u}}),c=TU({inputs:{a:s,b:l},backend:n}),h=qB({inputs:{x:c},backend:n}),d=kz({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),p=fz({inputs:{x:d},backend:n,attrs:{shape:u}}),f=IU({inputs:{a:h,b:p},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),f}const $U={kernelName:Ur,backendName:"webgl",kernelFunc:CU},AU={kernelName:Yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}
vendor: 4,416 bytes, line 5057
5057=r,u=o?s:CU({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=u.shape[0],c=u.shape[1],h=new kU(l,c,a),d=[[i]],p=n.runWebGLProgram(h,[u],"int32",d);return o||n.disposeIntermediateTensorInfo(u),p}},RU=RL+"\\n  return -x;\\n",_U={kernelName:Zn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.texData.get(r.dataId),[t,s]=YO(e.values,r.shape,r.dtype);return n.makeTensorInfo(s,r.dtype,t)}let s;return s=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new OL(r.shape,"\\n  vec4 result = -x;\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n"):new AL(r.shape,RU),n.runWebGLProgram(s,[r],r.dtype)}},MU=Jp,FU={kernelName:er,backendName:"webgl",kernelFunc:function(e){xs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=r,l=n.readSync(s.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=MU(l,c,i,o,u);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},DU=Zp,OU={kernelName:tr,backendName:"webgl",kernelFunc:function(e){xs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),{selectedIndices:d,validOutputs:p}=DU(c,h,i,o,u,l);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([p]))]}},LU=Qp,zU={kernelName:nr,backendName:"webgl",kernelFunc:function(e){xs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),d=i,p=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=LU(c,h,d,p,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class PU{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int index = round(getIndices(coords.x));\\n        setOutput(mix(float(${r}), float(${n}),\\n                      float(index == coords.y)));\\n      }\\n    `}}const BU={kernelName:sr,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{dtype:a,depth:i,onValue:o,offValue:u}=r,l=le(s.shape),c=new PU(l,i,o,u),h=fz({inputs:{x:s},backend:n,attrs:{shape:[l]}}),d=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const p=fz({inputs:{x:d},backend:n,attrs:{shape:[...s.shape,i]}});return n.disposeIntermediateTensorInfo(d),p}};function VU(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=CP({inputs:{input:r},backend:n}),t=VU({inputs:{x:e},backend:n}),s=WP({inputs:{input:r},backend:n}),a=VU({inputs:{x:s},backend:n}),i=JL({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}return sV({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const UU={kernelName:ds,backendName:"webgl",kernelFunc:VU},WU={kernelName:rr,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:s}=n;if("string"===s.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===s.dtype){const t=CP({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r}),a=WP({inputs:{input:s},backend:r}),i=VU({inputs:{x:a},backend:r}),o=JL({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}return sV({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:r})}},GU={kernelName:ar,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(1===t.length)return XB({inputs:{input:t[0]},backend:n,attrs:{dim:s}});const a=t[0].shape,i=t[0].dtype;
5057t.forEach(e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],u=jP({inputs:t.map(e=>{const t=XB({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t}),backend:n,attrs:{axis:s}});return o.forEach(e=>n.disposeIntermediateTensorInfo(e)),u}};class HU{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,s=GD(r),a=t.map(e=>e[0]).join(","),i=t.map((t,n)=>t[0]+e[n]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\\n      ${s} start = ${s}(${a});\\n      ${s} end = ${s}(${i});\\n\\n      void main() {\\n        ${s} outC = getOutputCoords();\\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\\n          setOutput(value);\\n        } else {\\n          ${s} coords = outC - start;\\n          setOutput(getX(${o}));\\n        }\\n      }\\n    `:`\\n        int start = ${a};\\n        int end = ${i};\\n\\n        void main() {\\n          int outC = getOutputCoords();\\n          if (outC < start || outC >= end) {\\n            setOutput(value);\\n          } else {\\n            setOutput(getX(outC - start));\\n          }\\n        }\\n      `}}class jU{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,s=GD(r),a=t.map(e=>e[0]).join(","),i=t.map((t,n)=>t[0]+e[n]).join(","),o=IL("rc",r),u=IL("source",r),l=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,h=[`${s} rc = outputLoc;`,`${o[r-1]} += 1;\\n       if(${l}) {\\n      `,1===r?"":`}\\n       rc = outputLoc;\\n       ${o[r-2]} += 1;\\n       if(${o[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":`  ${o[r-1]} += 1;\\n         if(${l}) {`],d=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let p="";for(let e=0,t=1===r?2:4;e<t;e++)p+=`\\n        ${h[e]}\\n        if (${d}) {\\n          result[${e}] = float(value);\\n        } else {\\n          ${s} source = rc - start;\\n          result[${e}] = getChannel(getX(${u.join()}), ${c});\\n        }\\n      `;p+=1===r?"} ":"}}",this.userCode=`\\n      const ${s} start = ${s}(${a});\\n      const ${s} end = ${s}(${i});\\n\\n      void main() {\\n        ${s} outputLoc = getOutputCoords();\\n        vec4 result = vec4(0.);\\n        ${p}\\n        setOutput(result);\\n      }\\n    `}}const qU=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;if(0===le(s.shape)){const e=a.map((e,t)=>e[0]+s.shape[t]+e[1]);return sV({backend:n,attrs:{shape:e,value:i,dtype:s.dtype}})}const o=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jU(s.shape,a,i):new HU(s.shape,a,i),u=[[i]];return n.runWebGLProgram(o,[s],s.dtype,u)},KU={kernelName:ir,backendName:"webgl",kernelFunc:qU},XU=oz({opSnippet:"\\n  if(a < 0.0 && floor(b) < b){\\n    return NAN;\\n  }\\n  if (b == 0.0) {\\n    return 1.0;\\n  }\\n  return (round(mod(b, 2.0)) != 1) ?\\n      pow(abs(a), b) : sign(a) * pow(abs(a), b);\\n",packedOpSnippet:"\\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\\n  vec4 result = multiplier * pow(abs(a), b);\\n\\n  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\\n  bvec4 isExpZero = equal(b, vec4(0.0));\\n  result.r = isExpZero.r ? 1.0 : result.r;\\n  result.g = isExpZero.g ? 1.0 : result.g;\\n  result.b = isExpZero.b ? 1.0 : result.b;\\n  result.a = isExpZero.a ? 1.0 : result.a;\\n\\n  bvec4 isNaN1 = lessThan(a, vec4(0.0));\\n  bvec4 isNaN2 = lessThan(floor(b), b);\\n  bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\\n  "+qL+"\\n  return result;\\n"}),YU={kernelName:ur,backendName:"webgl",kernelFunc:XU},JU={kernelName:cr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=[],l=we(a,s.shape);let c=l;const h=nh(c,o);let d,p=s;if(null!=h&&(p=Sz({inputs:{x:s},backend:n,attrs:{perm:h}}),c=sh(c.length,o),u.push(p)),th("prod",c,o),n.shouldExecuteOnCPU([p])){const e=n.texData.get(p.dataId).values,{outVals:t,outShape:r,outDtype:s}=ZO(p.shape,p.dtype,e,c);d=n.makeTensorInfo(r,s,t)}else{const[e,t]=Qc(p.shape,c),r=le(t),a=fz({inputs:{x:p},backend:n,attrs:{shape:[-1,r]}}),i=bz(a,Ia(s.dtype),"prod",n);d=fz({inputs:{x:i},backend:n,attrs:{shape:e}}),u.push(a),u.push(i)}if(i){u.push(d);const e=eh(d.shape,l);d=fz({inputs:{x:d},backend:n,attrs:{shape:e}})}
5057return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}},ZU={kernelName:hr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=r,u=s.map(e=>n.readSync(e.dataId)),l=s.map(e=>e.shape),c=n.readSync(a.dataId),h=n.readSync(i.dataId),[d,p,f]=QO(u,l,c,a.shape,a.dtype,h,i.shape,o),m=d.map(e=>n.makeTensorInfo([e.length],"int32",e)),g=n.makeTensorInfo(f,a.dtype,p);return m.concat([g])}},QU={kernelName:dr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:s,deltas:a}=t,i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=eL(i,r.shape,r.dtype,o,s.shape,u,a.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}},eW={kernelName:pr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.readSync(s.dataId),c=n.readSync(a.dataId),h=n.readSync(i.dataId),d=o.map(e=>n.readSync(e.dataId)),p=o.map(e=>e.shape),[f,m]=tL(l,s.shape,c,a.shape,a.dtype,h,i.shape,d,p,u);return n.makeTensorInfo(f,a.dtype,m)}},tW=e=>{const{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:i}=n,o=nL(r,s,a,i);return t.makeTensorInfo([o.length],i,o)},nW={kernelName:fr,backendName:"webgl",kernelFunc:tW},rW=iz({opSnippet:"return 1.0 / x;"}),sW={kernelName:gr,backendName:"webgl",kernelFunc:rW},aW=iz({opSnippet:RL+"\\n  return (x < 0.0) ? 0.0 : x;\\n",packedOpSnippet:"\\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n"}),iW={kernelName:yr,backendName:"webgl",kernelFunc:aW},oW=iz({opSnippet:RL+"\\n  return (x < 0.0) ? 0.0 : min(6.0, x);\\n",packedOpSnippet:"\\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n"}),uW={kernelName:Ir,backendName:"webgl",kernelFunc:oW};class lW{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\\n          ${l[0]/c[0]},\\n          ${l[1]/c[1]});\\n      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        ivec2 yRC = coords.yz;\\n\\n        // Fractional source index.\\n        vec2 sourceFracIndexRC = ${h};\\n\\n        // Compute the four integer indices.\\n        ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\\n        ivec2 sourceCeilRC = ivec2(\\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\\n\\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\\n\\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\\n\\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\\n        float newValue = top + (bottom - top) * fracRC.x;\\n\\n        setOutput(newValue);\\n      }\\n    `}}class cW{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\\n          ${l[0]/c[0]},\\n          ${l[1]/c[1]},\\n          ${l[1]/c[1]});\\n      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\\n                                     ${o}.0);\\n\\n      float getAValue(int b, int r, int c, int d) {\\n        return getChannel(getA(b, r, c, d), vec2(c, d));\\n      }\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        // Calculate values for next column in yRC.z.\\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\\n\\n        // Fractional source index.\\n        vec3 sourceFracIndexRC = ${h};\\n\\n        // Compute the four integer indices.\\n        ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\\n        ivec3 sourceCeilRC = ivec3(\\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\\n\\n        // Should we calculate next column and row elements in 2x2 packed cell.\\n        bool hasNextCol = d < ${u-1};\\n        bool hasNextRow = coords.z < ${n-1};\\n\\n        // In parallel, construct four corners for all four components in\\n        // packed 2x2 cell.\\n        vec4 topLeft = vec4(\\n          getA
5057Value(b, sourceFloorRC.x, sourceFloorRC.y, d),\\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\\n                     : 0.0,\\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\\n                     : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\\n\\n        vec4 bottomLeft = vec4(\\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\\n                     : 0.0,\\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\\n                     : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\\n\\n        vec4 topRight = vec4(\\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\\n                     : 0.0,\\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\\n                     : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\\n\\n        vec4 bottomRight = vec4(\\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\\n                     : 0.0,\\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\\n                     : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\\n\\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
5057\\n\\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\\n        vec4 newValue = mix(top, bottom, fracRC.x);\\n\\n        setOutput(newValue);\\n      }\\n    `}}const hW={kernelName:vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[u,l]=o,c=Xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cW(s.shape,u,l,a,i):new lW(s.shape,u,l,a,i);return n.runWebGLProgram(c,[s],"float32")}};class dW{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],l=o[0]/u[0],c=o[1]/u[1],h=1/l,d=1/c,p=2*Math.ceil(h)+2,f=2*Math.ceil(d)+2;this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        int r = coords[1];\\n        int c = coords[2];\\n\\n        float accumulator = 0.0;\\n\\n        const float heightScale = float(${l});\\n        const float widthScale = float(${c});\\n\\n        const float invHeightScale = float(${h});\\n        const float invWidthScale = float(${d});\\n\\n        const int winHeight = int(${p});\\n        const int winWidth = int(${f});\\n\\n        // Compute bounds for where in dy we will look\\n        float startRLerp = floor(float(r) * invHeightScale);\\n        int startDyR = int(startRLerp - float(winHeight / 2));\\n\\n        float startCLerp = floor(float(c) * invWidthScale);\\n        int startDyC = int(startCLerp - float(winWidth / 2));\\n\\n        // Loop over dy\\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\\n          int dyR = dyROffset + startDyR;\\n\\n          // Guard against the window exceeding the bounds of dy\\n          if (dyR < 0 || dyR >= ${a}) {\\n            continue;\\n          }\\n\\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\\n            int dyC = dyCOffset + startDyC;\\n\\n            // Guard against the window exceeding the bounds of dy\\n            if (dyC < 0 || dyC >= ${i}) {\\n              continue;\\n            }\\n\\n            float dxR = float(dyR) * heightScale;\\n            int topDxRIndex = int(floor(dxR));\\n            int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\\n            float dxRLerp = dxR - float(topDxRIndex);\\n            float inverseDxRLerp = 1.0 - dxRLerp;\\n\\n            float dxC = float(dyC) * widthScale;\\n            int leftDxCIndex = int(floor(dxC));\\n            int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));\\n            float dxCLerp = dxC - float(leftDxCIndex);\\n            float inverseDxCLerp = 1.0 - dxCLerp;\\n\\n            if (r == topDxRIndex && c == leftDxCIndex) {\\n              // topLeft\\n              accumulator +=\\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\\n            }\\n\\n            if (r == topDxRIndex && c == rightDxCIndex) {\\n              // topRight\\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\\n            }\\n\\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\\n              // bottomLeft\\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\\n            }\\n\\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\\n              // bottomRight\\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\\n            }\\n          }\\n        }\\n        // End loop over dy\\n\\n        setOutput(accumulator);\\n      }\\n    `}}const pW={kernelName:kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new dW(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class fW{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let d;d=s?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\\n          ${l[0]/c[0]},\\n          ${l[1]/c[1]});\\n      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        ivec2 yRC = coords.yz;\\n\\n        // Fractional source index.\\n        vec2 sourceFracIndexRC = ${d};\\n\\n        // Compute the coordinators of nearest neighbor point.\\n        ivec2 sourceNearestRC = ivec2(\\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\\n\\n        setOutput(newValue);\\n      }\\n    `}}
vendor: 17,100 bytes, line 5057
5057class mW{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let d;d=s?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\\n          ${l[0]/c[0]},\\n          ${l[1]/c[1]},\\n          ${l[1]/c[1]});\\n      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\\n                                     ${o}.0);\\n\\n      float getAValue(int b, int r, int c, int d) {\\n        return getChannel(getA(b, r, c, d), vec2(c, d));\\n      }\\n\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        // Calculate values for next column in yRC.z.\\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\\n\\n        // Fractional source index.\\n        vec3 sourceFracIndexRC = ${d};\\n\\n        // Compute the coordinators of nearest neighbor point.\\n        ivec3 sourceNearestRC = ivec3(\\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\\n\\n        // Should we calculate next column and row elements in 2x2 packed cell.\\n        bool hasNextCol = d < ${u-1};\\n        bool hasNextRow = coords.z < ${n-1};\\n\\n        vec4 newValue = vec4(\\n          getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\\n          hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\\n                     : 0.0,\\n          hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\\n                     : 0.0,\\n          (hasNextRow && hasNextCol) ?\\n            getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\\n\\n        setOutput(newValue);\\n      }\\n    `}}const gW={kernelName:xr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[u,l]=o,c=Xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new mW(s.shape,u,l,a,i):new fW(s.shape,u,l,a,i);return n.runWebGLProgram(c,[s],s.dtype)}};class yW{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],l=o[0]/u[0],c=o[1]/u[1],h=1/l,d=1/c,p=2*Math.ceil(h)+2,f=2*Math.ceil(d)+2;this.userCode=`\\n      void main() {\\n        ivec4 coords = getOutputCoords();\\n        int b = coords[0];\\n        int d = coords[3];\\n        int r = coords[1];\\n        int c = coords[2];\\n\\n        float accumulator = 0.0;\\n\\n        const float heightScale = float(${l});\\n        const float widthScale = float(${c});\\n\\n        const float invHeightScale = float(${h});\\n        const float invWidthScale = float(${d});\\n\\n        const int winHeight = int(${p});\\n        const int winWidth = int(${f});\\n\\n        // Compute bounds for where in dy we will look\\n        float startRLerp = floor(float(r) * invHeightScale);\\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\\n\\n        float startCLerp = floor(float(c) * invWidthScale);\\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\\n\\n        // Loop over dy\\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\\n          int dyR = dyROffset + startDyR;\\n\\n          // Guard against the window exceeding the bounds of dy\\n          if (dyR < 0 || dyR >= ${a}) {\\n            continue;\\n          }\\n\\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\\n            int dyC = dyCOffset + startDyC;\\n\\n            // Guard against the window exceeding the bounds of dy\\n            if (dyC < 0 || dyC >= ${i}) {\\n              continue;\\n            }\\n\\n            float sourceFracRow =\\n              float(${o[0]}) *\\n                (float(dyR) / float(${u[0]}));\\n\\n            float sourceFracCol =\\n                float(${o[1]}) *\\n                  (float(dyC) / float(${u[1]}));\\n\\n            int sourceNearestRow = int(min(\\n                float(int(${r}) - 1),\\n                ${n} ? float(round(sourceFracRow)) :\\n                                  float(floor(sourceFracRow))));\\n\\n            int sourceNearestCol = int(min(\\n                float(int(${s}) - 1),\\n                ${n} ? float(round(sourceFracCol)) :\\n                                  float(floor(sourceFracCol))));\\n\\n            if (r == sourceNearestRow && c == sourceNearestCol) {\\n              accumulator += getDy(b, dyR, dyC, d);\\n            }\\n          }\\n        }\\n        // End loop over dy\\n\\n        setOutput(accumulator);\\n      }\\n    `}}const bW={kernelName:wr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new yW(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class xW{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\\n        void main() {\\n          int coord = getOutputCoords();\\n          setOutput(getX(${e[0]} - coord - 1));\\n        }\\n      `);const r=e.map((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r)).join(","),s=GD(n);this.userCode=`\\n      void main() {\\n        ${s} coords = getOutputCoords();\\n        setOutput(getX(${r}));\\n      }\\n    `}}class wW{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=IL("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,i=GD(n);function o(n){const r=e.map((r,s)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(s,n));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\\n        void main(){\\n          int rc = getOutputCoords();\\n          vec4 result = vec4(0.);\\n          result.r = getChannel(getX(${e[0]} - rc - 1),\\n            ${e[0]} - rc - 1);\\n          if(${s}){\\n              result.g = getChannel(getX(${e[0]} - (rc  + 1) - 1),\\n                ${e[0]} - (rc  + 1) - 1);\\n          }\\n          setOutput(result);\\n        }\\n      `:`\\n        void main() {\\n          ${i} rc = getOutputCoords();\\n          vec4 result = vec4(0.);\\n          result.r = ${function(e){return o(e)}(r.slice())};\\n          if(${s}){\\n            result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(r.slice())};\\n          }\\n          if(${a}) {\\n            result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\\n            if(${s}) {\\n              result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\\n            }\\n          }\\n          setOutput(result);\\n        }\\n    `}}const vW={kernelName:Sr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,i=s.shape.length,o=we(a,s.shape);if(0===i)return XL({inputs:{x:s},backend:n});const u=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new wW(s.shape,o):new xW(s.shape,o);return n.runWebGLProgram(u,[s],s.dtype)}};class kW{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],r=e[2];this.outputShape=e;let s="";s="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\\n        vec3 fill = vec3(${t.join(",")});\\n        float outputValue = fill[coords[3]];`,this.userCode=`\\n        void main() {\\n          ivec4 coords = getOutputCoords();\\n          int x = coords[2];\\n          int y = coords[1];\\n          float coordXFloat = (float(x) - params[0]) * params[3] -\\n            (float(y) - params[1]) * params[2];\\n          float coordYFloat = (float(x) - params[0]) * params[2] +\\n            (float(y) - params[1]) * params[3];\\n          int coordX = int(round(coordXFloat + params[0]));\\n          int coordY = int(round(coordYFloat + params[1]));\\n          ${s}\\n          if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\\n            outputValue = getImage(coords[0], coordY, coordX, coords[3]);\\n          }\\n          setOutput(outputValue);\\n        }\\n    `}}const IW={kernelName:ms,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,u=new kW(r.shape,a),[l,c]=Zf(i,r.shape[1],r.shape[2]),h=[[l,c,Math.sin(s),Math.cos(s)]];return o.runWebGLProgram(u,[r],r.dtype,h)}},SW=iz({opSnippet:"\\n  // OpenGL ES does not support round function.\\n  // The algorithm is based on banker\'s rounding.\\n  float base = floor(x);\\n  if ((x - base) < 0.5) {\\n    return floor(x);\\n  } else if ((x - base) > 0.5) {\\n    return ceil(x);\\n  } else {\\n    if (mod(base, 2.0) == 0.0) {\\n      return base;\\n    } else {\\n      return base + 1.0;\\n    }\\n  }\\n"}),NW={kernelName:Nr,backendName:"webgl",kernelFunc:SW},TW=iz({opSnippet:"return inversesqrt(x);",cpuKernelImpl:rL}),EW={kernelName:Tr,backendName:"webgl",kernelFunc:TW};class CW{constructor(e,t,n,r,s,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const u=GD(s.length),l=GD(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let d="";1===r?d="i":2===r&&(d="i, coords[1]");const p=`getUpdates(${d})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`\\n        ${u} strides = ${u}(${s});\\n\\n        void main() {\\n          ${l} coords = getOutputCoords();\\n          float sum = 0.0;\\n          bool found = false;\\n          for (int i = 0; i < ${e}; i++) {\\n            int flattenedIndex = 0;\\n            for (int j = 0; j < ${t}; j++) {\\n              int index = round(${h});\\n              flattenedIndex += index * ${g};\\n            }\\n            if (flattenedIndex == coords[0]) {\\n              sum += ${p};\\n              found = true;\\n            }\\n          }\\n          setOutput(mix(${m}, sum, float(found)));\\n        }\\n      `}}class $W{constructor(e,t,n,r,s,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const u=GD(s.length),l=GD(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let d="";1===r?d="i":2===r&&(d="i, coords[1]");const p=`getUpdates(${d})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`\\n        ${u} strides = ${u}(${s});\\n\\n        void main() {\\n          ${l} coords = getOutputCoords();\\n          vec4 sum = vec4(0.);\\n          vec4 found = vec4(0.);\\n          for (int i = 0; i < ${e}; i+=2) {\\n            ivec2 flattenedIndex = ivec2(0);\\n            for (int j = 0; j < ${t}; j+=2) {\\n              ivec4 index = round(${h});\\n              flattenedIndex += index.xz * ${g};\\n              if (j + 1 < ${t}) {\\n                flattenedIndex += index.yw * ${y};\\n              }\\n            }\\n            if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\\n                flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\\n              vec4 updVals = ${p};\\n              if (flattenedIndex[0] == coords[0]) {\\n                sum.xy += updVals.xy;\\n                found.xy = vec2(1.);\\n              } else if (flattenedIndex[0] == coords[0] + 1) {\\n                sum.zw += updVals.xy;\\n                found.zw = vec2(1.);\\n              }\\n              if (flattenedIndex[1] == coords[0]) {\\n                sum.xy += updVals.zw;\\n                found.xy = vec2(1.);\\n              } else if (flattenedIndex[1] == coords[0] + 1) {\\n                sum.zw += updVals.zw;\\n                found.zw = vec2(1.);\\n              }\\n            }\\n          }\\n          setOutput(mix(${m}, sum, found));\\n        }\\n      `}}const AW={kernelName:Er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=Xu(0,s,i),d=[h/l,l];if(0===h)return n.makeTensorInfo(i,s.dtype);const p=fz({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),f=fz({inputs:{x:a},backend:n,attrs:{shape:[u,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=Xe().getBool("WEBGL_PACK")?new $W(u,o,p.shape.length,f.shape.length,c,d):new CW(u,o,p.shape.length,f.shape.length,c,d);const y=n.runWebGLProgram(g,[f,p,m],f.dtype),b=fz({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class RW{constructor(e,t,n,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=2===Xe().getNumber("WEBGL_VERSION")?"while (left < right) {":s,i="left"===r?"<":"<=";this.userCode=`\\n       int findBound(int batch, float value) {\\n         int left = 0;\\n         int right = numInputs;\\n         int mid;\\n         ${a}\\n           mid = (left + right) / 2;\\n           if (getSortedSequence(batch, mid) ${i} value) {\\n             left = mid + 1;\\n           } else {\\n             right = mid;\\n           }\\n         }\\n         return right;\\n       }\\n\\n       void main() {\\n         ivec2 coords = getOutputCoords();\\n         int batch = coords[0];\\n         int valueIndex = coords[1];\\n\\n         float value = getValues(batch, valueIndex);\\n\\n         setOutput(float(findBound(batch, value)));\\n       }\\n     `}}const _W={kernelName:$r,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:s,values:a}=t,{side:i}=r,o=new RW(s.shape[0],s.shape[1],a.shape[1],i),u=[[s.shape[1]]];return n.runWebGLProgram(o,[s,a],"int32",u)}};class MW{constructor(e,t,n){let r,s;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)s="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let r=0;r<t.length;r++)i.push(`${n[r]}`),r<e&&a.push(`${n[r]}`);r=a.join(),s=i.join()}const a=GD(n);this.userCode=`\\n      void main() {\\n        ${a} resRC = getOutputCoords();\\n        float cVal = getC(${r});\\n        if (cVal >= 1.0) {\\n          setOutput(getA(${s}));\\n        } else {\\n          setOutput(getB(${s}));\\n        }\\n      }\\n    `}}const FW={kernelName:Ar,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,i=new MW(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(i,[r,s,a],ka(s.dtype,a.dtype))}},DW=iz({opSnippet:`\\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\\n  // see: https://arxiv.org/abs/1706.02515\\n  float scaleAlpha = ${sm};\\n  float scale = ${am};\\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\\n`}),OW={kernelName:Rr,backendName:"webgl",kernelFunc:DW},LW=iz({opSnippet:az+"\\n  return 1.0 / (1.0 + exp(-1.0 * x));\\n",packedOpSnippet:"\\n  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\\n  bvec4 isNaN = isnan(x);\\n\\n  result.r = isNaN.r ? x.r : result.r;\\n  result.g = isNaN.g ? x.g : result.g;\\n  result.b = isNaN.b ? x.b : result.b;\\n  result.a = isNaN.a ? x.a : result.a;\\n\\n  return result;\\n",cpuKernelImpl:aL}),zW={kernelName:Or,backendName:"webgl",kernelFunc:LW},PW=iz({opSnippet:"\\n  if (isnan(x)) { return 0.0; }\\n  return sign(x);\\n"}),BW={kernelName:Dr,backendName:"webgl",kernelFunc:PW},VW=iz({opSnippet:az+"\\n  return sin(x);\\n",packedOpSnippet:`\\n  vec4 result = sin(x);\\n  bvec4 isNaN = isnan(x);\\n  ${qL}\\n  return result;\\n`}),UW={kernelName:Mr,backendName:"webgl",kernelFunc:VW},WW=iz({opSnippet:"\\n  float e2x = exp(x);\\n  return (e2x - 1.0 / e2x) / 2.0;\\n"}),GW={kernelName:Fr,backendName:"webgl",kernelFunc:WW},HW=iz({opSnippet:"\\n  float epsilon = 1.1920928955078125e-7;\\n  float threshold = log(epsilon) + 2.0;\\n\\n  bool too_large = x > -threshold;\\n  bool too_small = x < threshold;\\n\\n  float result;\\n  float exp_x = exp(x);\\n\\n  if (too_large){\\n    result = x;\\n  }\\n  else if (too_small){\\n    result = exp_x;\\n  }\\n  else{\\n    result = log(exp_x + 1.0);\\n  }\\n  return result;\\n"}),jW={kernelName:Lr,backendName:"webgl",kernelFunc:HW},qW={kernelName:Br,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}
5057=t,{blockShape:a,paddings:i}=r;ie(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const o=a.reduce((e,t)=>e*t),u=[[0,0]];u.push(...i);for(let e=1+a.length;e<s.shape.length;++e)u.push([0,0]);const l=[],c=qU({inputs:{x:s},backend:n,attrs:{paddings:u,constantValue:0}}),h=Qf(c.shape,a,o,!1),d=em(h.length,a.length,!1),p=tm(c.shape,a,o,!1),f=fz({inputs:{x:c},backend:n,attrs:{shape:h}}),m=Sz({inputs:{x:f},backend:n,attrs:{perm:d}}),g=fz({inputs:{x:m},backend:n,attrs:{shape:p}});return l.push(c),l.push(f),l.push(m),l.forEach(e=>n.disposeIntermediateTensorInfo(e)),g}},KW={kernelName:Wr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\\n         ${a.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\\n         ${r.shape}`);if(1!==s.shape.length)throw new Error(`Values must be a vector, saw:\\n         ${s.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\\n        ${i.shape}`);const o=n.readSync(r.dataId),u=n.readSync(s.dataId),l=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,d,p,f,m]=uL(o,r.shape,r.dtype,u,s.dtype,l,c);return[n.makeTensorInfo(d,r.dtype,h),n.makeTensorInfo([d[0]],s.dtype,p),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(e=>Number(e)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}},XW={kernelName:Gr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(1!==s.shape.length)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.readSync(s.dataId)),o=n.readSync(r.dataId),u=Array.from(n.readSync(a.dataId)),[l,c,h]=lL(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},YW={kernelName:Hr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\\n              ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\\n              ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=cL(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}},JW={kernelName:jr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\\n             ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\\n             ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=cL(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}},ZW={kernelName:qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:h,outputSize:d}=Xu(0,s,o),p=!1;if("string"===a.dtype){const e=n.bufferSync(s),t=n.bufferSync(a),r=Zs(n.readSync(i.dataId)[0]),f=sL(e,t,o,d,c,l,u,h,r,p);return n.makeTensorInfo(o,f.dtype,f.values)}const f=new CW(l,u,s.shape.length,a.shape.length,h,[d,1],p),m=n.runWebGLProgram(f,[a,s,i],a.dtype),g=fz({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),g}},QW={kernelName:Vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:i}=r,o=we(i,s.shape)[0],u=Am(s,a,o),l=s.shape.length,c=new Array(l).fill(0),h=s.shape.slice();return u.map(e=>{const t=[...h];t[o]=e;const r=wP({inputs:{x:s},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,r})}},eG="return sqrt(x);",tG=iz({opSnippet:eG,packedOpSnippet:eG,cpuKernelImpl:hL}),nG={kernelName:zr,backendName:"webgl",kernelFunc:tG},rG=iz({opSnippet:"return x * x;"}),sG={kernelName:Xr,backendName:"webgl",kernelFunc:rG}
vendor: 5,919 bytes, line 5057
5057,aG="return (a - b) * (a - b);",iG=oz({opSnippet:aG,packedOpSnippet:aG}),oG={kernelName:Kr,backendName:"webgl",kernelFunc:iG},uG={kernelName:Yr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");const a=jm(n.readSync(s.dataId)),i=dL(a,"string",r);return n.makeTensorInfo(s.shape,"string",i)}},lG={kernelName:ps,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,s=RL+`\\n    return x > 0.0 ? 1.0 : float(${t.alpha});\\n  `,a=new AL(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}};class cG{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,s=GD(n.length),a=GD(n.length);let i="";if(1===r)i="coords * strides + begin";else{let e=0;i=n.map((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`)).join(",")}this.userCode=`\\n      ${s} begin = ${s}(${e});\\n      ${s} strides = ${s}(${t});\\n\\n      void main() {\\n        ${a} coords = getOutputCoords();\\n        setOutput(getX(${i}));\\n      }\\n    `}}const hG={kernelName:Jr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=r,{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=pl(s.shape,a,i,o,u,l,c,h,d);let v;if(m)v=fz({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){ie(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const e=el(b,x,w),t=wP({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=fz({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([s])){const e=n.readSync(s.dataId),t=ko(s.shape,s.dtype,e),r=pL(p,t,w,b);v=n.makeTensorInfo(f,s.dtype,r.values)}else{const e=new cG(b,w,p);v=n.runWebGLProgram(e,[s],s.dtype)}const k=fz({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}},dG={kernelName:Zr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:h}=t,d=n.readSync(c.dataId),p=n.readSync(h.dataId),[f,m]=fL(d,p,s,a,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}},pG={kernelName:Qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(a.dataId),u=n.readSync(i.dataId)[0],[l,c,h]=mL(o,u,s),d=c.length;return[n.makeTensorInfo([d,2],"int32",l),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}},fG={kernelName:es,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=gL(i,s);return n.makeTensorInfo(a.shape,"int32",o)}},mG=iz({opSnippet:"return tan(x);"}),gG={kernelName:ns,backendName:"webgl",kernelFunc:mG},yG=iz({opSnippet:"\\n  float e2x = exp(-2.0 * abs(x));\\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\\n"}),bG={kernelName:rs,backendName:"webgl",kernelFunc:yG},xG={kernelName:Cr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{tensor:s,indices:a,updates:i}=t,{}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=Xu(0,a,s.shape),d=[h/l,l];if(0===h)return n.makeTensorInfo(s.shape,a.dtype);const p=fz({inputs:{x:a},backend:n,attrs:{shape:[u,o]}}),f=fz({inputs:{x:i},backend:n,attrs:{shape:[u,l]}}),m=fz({inputs:{x:s},backend:n,attrs:{shape:d}}),g=new CW(u,o,p.shape.length,f.shape.length,c,d,!1,!0),y=n.runWebGLProgram(g,[f,p,m],m.dtype),b=fz({inputs:{x:y},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class wG{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.rank=n.length;const r=GD(this.rank),s=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let t=0;t<e.length;t++)r.push(`imod(${n[t]}, ${e[t]})`);return r.join()}(e);this.userCode=`\\n      void main() {\\n        ${r} resRC = getOutputCoords();\\n        setOutput(getA(${s}));\\n      }\\n    `}}function vG(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if("string"===s.dtype||s.shape.length>5){const e=n.readSync(s.dataId),t="string"===s.dtype?e.map(e=>Zs(e)):e,r=ko(s.shape,s.dtype,t),i=bL(r,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new wG(s.shape,a);return n.runWebGLProgram(i,[s],s.dtype)}const kG={kernelName:ss,backendName:"webgl",kernelFunc:vG};class IG{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode="\\n       void main() {\\n         ivec2 coords = getOutputCoords();\\n         int batch = coords[0];\\n         int elemIdx = coords[1];\\n\\n         // We compare elements pair-wise within a group of size 2 * inc.\\n         // The comparing rule for each group alternates between ascending\\n         // and desce
5057nding. Within each group, we compare each pair at\\n         // positions i and i+inc. To decide whether an element at position i\\n         // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\\n         // inc, it is in the first half of the group, we denote it as x0,\\n         // otherwise we denote it as x1.\\n         // For example, as shown in the Bitonic top K paper referenced above,\\n         // Figure5(a) shows that element[1] is in the\\n         // second half of the group when group size is 2, but it is in the\\n         // first half of the group when group size is 4.\\n\\n         bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\\n         int i = isFirstInPair ? elemIdx : elemIdx - inc;\\n\\n         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\\n         int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\\n         float x0 = i0 < n ? getX(batch, i0) : negativeInf;\\n         float x1 = i1 < n ? getX(batch, i1) : negativeInf;\\n\\n         // Denotes which direction indices are in (ascending or descending).\\n         bool reverse = imod(elemIdx, 2 * dir) >= dir;\\n         bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\\n         if (reverse == isGreater) { // Elements in opposite order of direction\\n           int iTemp = i0;\\n           i0 = i1;\\n           i1 = iTemp;\\n         }\\n         if (isFirstInPair) {\\n            setOutput(float(i0));\\n         } else {\\n            setOutput(float(i1));\\n         }\\n       }\\n     "}}class SG{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode="\\n    void main() {\\n         // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\\n         ivec2 coords = getOutputCoords();\\n         int batch = coords[0];\\n         int elemIdx = coords[1];\\n\\n         // The output size is half of the previous size.\\n         // If the previous sequence is | | | | _ _ _ _  | | | |  _ _ _ _ (k=4),\\n         // we only need to output the indices at positions |, the indices at\\n         // positions _ can be thrown away, see Figure5(b) After Phase 2\\n         // (Merge phase) in the Bitonic Top K paper referenced above.\\n         // For example, the paper shows we only need to output the orange bars.\\n         // The output sequence should look like this | | | | | | | |.\\n         // Because the sequence is halved, to map the output index back\\n         // to the previous sequence to find the corresponding value,\\n         // we need to double the index. When we double the index,\\n         // we basically interpolate a position, so 2i looks like\\n         // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\\n         // of each 2k positions by - elemIdx % k. E.g. for output at\\n         // index 4,5,6,7, we want to get the corresponding element at\\n         // original index 8,9,10,11, for output at index 8,9,10,11,\\n         // we want to get the corresponding element at original index\\n         // 16,17,18,19, so on and so forth.\\n\\n         int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\\n         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\\n         int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\\n\\n         float x0 = getX(batch, i0);\\n         float x1 = i1 < n ? getX(batch, i1) : x0;\\n\\n         setOutput(x0 >= x1 ? float(i0) : float(i1));\\n       }\\n     "}}function NG(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function TG(e){let t=1;for(;t<e;)t*=2;return t}const EG={kernelName:as,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:i}=r,o=Xe().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=Xe().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=s.shape,c=l[l.length-1];if(n.shouldExecuteOnCPU([s])||c<o||a>u){const e=n.readSync(s.dataId),[t,r]=xL(e,l,s.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(r.shape,r.dtype,r.values)]}if(0===a)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(1===c)return[s,sV({attrs:{shape:l,dtype:"int32",value:0},backend:n})];const h=n.texData.get(s.dataId),d=null!==h&&h.isPacked,p=d?n.unpackTensor(s):s,f=le(l)/c,m=fz({inputs:{x:p},attrs:{shape:[f,c]},backend:n});d&&NG(n,p);const g=TG(a),y=TG(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,r)=>{const s=x(),a=new IG(r),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(a,s,"int32",i),NG(n,o)};for(let e=1;e<g;e*=2){const t=2*e;for(let n=e;n>=1;n/=2)w(t,n,[f,y])}for(let e=y;e>g;e/=2){const t=x(),r=new SG([f,e/2]),s=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(r,t,"int32",s),NG(n,a);const i=g/2,o=2*i;for(let e=i;e>=1;e/=2)w(o,e,b.shape)}let v=b;b=wP({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,a]}}),NG(n,v);
vendor: 4,142 bytes, line 5057
5057let k=IV({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});NG(n,m);const I=l.slice(0,-1);I.push(a),v=b,b=fz({inputs:{x:b},attrs:{shape:I},backend:n}),NG(n,v);const S=k;return k=fz({inputs:{x:k},attrs:{shape:I},backend:n}),NG(n,S),[k,b]}};class CG{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(r){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}this.userCode=`\\n            float mapCoord(float outCoord, float len) {\\n              float inCoord = outCoord;\\n              if(${o} == 2) {\\n                if (inCoord < 0.0) {\\n                  if (len <= 1.0) {\\n                    inCoord = 0.0;\\n                  } else {\\n                    float sz2 = 2.0 * len;\\n                    if (inCoord < sz2) {\\n                      inCoord = sz2 * float(int(float(-inCoord / sz2))) +\\n                      inCoord;\\n                    }\\n                    inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\\n                  }\\n                } else if (inCoord > len - 1.0) {\\n                  if (len <= 1.0) {\\n                    inCoord = 0.0;\\n                  } else {\\n                    float sz2 = 2.0 * len;\\n                    inCoord -= sz2 * float(int(float(inCoord / sz2)));\\n                    if (inCoord >= len) {\\n                      inCoord = sz2 - inCoord - 1.0;\\n                    }\\n                  }\\n                }\\n                return clamp(inCoord, 0.0, len - 1.0);\\n              } else if (${o} == 3) {\\n                if (inCoord < 0.0) {\\n                  if (len <= 1.0) {\\n                    inCoord = 0.0;\\n                  } else {\\n                    float sz = len - 1.0;\\n                    inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\\n                  }\\n                } else if (inCoord > len - 1.0) {\\n                  if (len <= 1.0) {\\n                    inCoord = 0.0;\\n                  } else {\\n                    float sz = len - 1.0;\\n                    inCoord -= len * float(int(float(inCoord / sz)));\\n                  }\\n                }\\n                return clamp(inCoord, 0.0, len - 1.0);\\n              } else if (${o} == 4) {\\n                return clamp(outCoord, 0.0, len - 1.0);\\n              } else {\\n                return outCoord;\\n              }\\n            }\\n\\n            float readWithFillValue(int batch, int coordY, int coordX,\\n              int channel) {\\n              float outputValue;\\n              if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\\n                  outputValue = getImage(batch, coordY, coordX, channel);\\n              } else {\\n                outputValue = float(${s});\\n              }\\n              return outputValue;\\n            }\\n\\n            void main() {\\n              ivec4 coords = getOutputCoords();\\n              float outputValue;\\n              int batch = coords[0];\\n              int x = coords[2];\\n              int y = coords[1];\\n              int channel = coords[3];\\n              float xf = float(x);\\n              float yf = float(y);\\n              float a1 = getTransforms(batch, 0);\\n              float a2 = getTransforms(batch, 1);\\n              float a3 = getTransforms(batch, 2);\\n              float b1 = getTransforms(batch, 3);\\n              float b2 = getTransforms(batch, 4);\\n              float b3 = getTransforms(batch, 5);\\n              float c1 = getTransforms(batch, 6);\\n              float c2 = getTransforms(batch, 7);\\n              float projection = c1 * xf + c2 * yf + 1.0;\\n              if (projection == 0.0) {\\n                outputValue = float(${s});\\n              } else {\\n                float inX = (a1 * xf + a2 * yf + a3) / projection;\\n                float inY = (b1 * xf + b2 * yf + b3) / projection;\\n                float mapX = mapCoord(inX, float(${t}));\\n                float mapY = mapCoord(inY, float(${e}));\\n\\n                if (${i}
5057 == 1) {\\n                  int coordY = int(round(mapY));\\n                  int coordX = int(round(mapX));\\n                  outputValue = readWithFillValue(batch, coordY, coordX,\\n                    channel);\\n                } else {\\n                  float yFloor = floor(mapY);\\n                  float xFloor = floor(mapX);\\n                  float yCeil = yFloor + 1.0;\\n                  float xCeil = xFloor + 1.0;\\n                  float valueYFloor = (xCeil - mapX) *\\n                  readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\\n                  (mapX - xFloor) *\\n                  readWithFillValue(batch, int(yFloor), int(xCeil), channel);\\n                  float valueYCeil = (xCeil - mapX) *\\n                  readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\\n                  (mapX - xFloor) *\\n                  readWithFillValue(batch, int(yCeil), int(xCeil), channel);\\n                  outputValue = (yCeil - mapY) * valueYFloor +\\n                  (mapY - yFloor) * valueYCeil;\\n                }\\n              }\\n              setOutput(outputValue);\\n            }\\n        `}}const $G={kernelName:is,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=r,[c,h,d,p]=s.shape,[f,m]=null!=l?l:[h,d],g=new CG(h,d,i,o,u,[c,f,m,p]);return n.runWebGLProgram(g,[s,a],"float32")}},AG={kernelName:us,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;ED(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=r.readSync(a.dataId),{outputValues:o,outputShape:u,indices:l}=vL(i,s,a.shape,a.dtype);return[r.makeTensorInfo(u,a.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}},RG={kernelName:ls,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s,o=i.shape.length,u=s.shape[a],l=new Array(o-1);let c=0;for(let e=0;e<o;e++)e!==a&&(l[c++]=i.shape[e]);const h=[],d=new Array(o).fill(0),p=i.shape.slice();p[a]=1;const f=new Array(u);for(let e=0;e<f.length;e++){d[a]=e;const t=wP({inputs:{x:i},backend:n,attrs:{begin:d,size:p}}),r=fz({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,h.push(t)}return h.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}};class _G{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/n);this.outputShape=[r,i];const o=4*Math.floor(n/4),u=n%4,l="\\n        sumValue += dot(values, segFilter);\\n    ";let c="";s%n>0&&(c=`\\n        if (inIdx < 0 || inIdx >= ${s}) {\\n          return initializationValue;\\n        }\\n      `);let h="";s%n>0&&(h=`\\n        if (inIdx < 0 || inIdx >= ${s}) {\\n          return -1.0;\\n        }\\n      `),this.userCode=`\\n      const float initializationValue = 0.0;\\n\\n      float getValue(int batch, int inIdx) {\\n        ${c}\\n        return getX(batch, inIdx);\\n      }\\n\\n      float getSegmentIdAtIndex(int inIdx) {\\n        ${h}\\n        return getSegmentIds(inIdx);\\n      }\\n\\n      void main() {\\n        ivec2 coords = getOutputCoords();\\n        int batch = coords[0];\\n        int outIdx = coords[1];\\n        int inOffset = int(floor(float(outIdx) / float(\\n          ${a})) * float(${n}));\\n        int currentSeg = int(mod(float(outIdx), float(${a})));\\n\\n        float sumValue = 0.0;\\n\\n        for (int i = 0; i < ${o}; i += 4) {\\n          int inIdx = inOffset + i;\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2),\\n            getValue(batch, inIdx + 3)\\n          );\\n\\n          vec4 segFilter = vec4(\\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\\n          );\\n\\n          ${l}\\n        }\\n\\n        int inIdx = inOffset + ${o};\\n        if (${1===u}) {\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            initializationValue,\\n            initializationValue,\\n            initializationValue\\n          );\\n\\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\\n\\n          vec4 segFilter = vec4(\\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\\n            0,\\n            0,\\n            0\\n          );\\n\\n          ${l}\\n        } else if (${2===u}) {\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            initializationValue,\\n            initializationValue\\n          );\\n\\n          vec4 segFilter = vec4(\\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\\n              0,\\n              0\\n          );\\n\\n          ${l}\\n        } else if (${3===u}) {\\n          vec4 values = vec4(\\n            getValue(batch, inIdx),\\n            getValue(batch, inIdx + 1),\\n            getValue(batch, inIdx + 2),\\n            initializationValue\\n          );\\n\\n          vec4 segFilter = vec4(\\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\\n            0\\n          );\\n\\n          ${l}\\n        }\\n        setOutput(sumValue);\\n      }\\n    `}}const MG={kernelName:cs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:i}=r,o=s.shape.length,u=[];let l=0;const c=nh([l],o);let h=s;
5057null!=c&&(h=Sz({inputs:{x:s},backend:n,attrs:{perm:c}}),u.push(h),l=sh(1,o)[0]);const d=Gm(h.shape,l,i),p=le([h.shape[l]]),f=fz({inputs:{x:h},backend:n,attrs:{shape:[-1,p]}});u.push(f);const m=Ia(s.dtype),g=(e,t,r,s,a)=>{const i=e.shape[0],o=e.shape[1],l=Wm(o,a),c=new _G({windowSize:l,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,r],s);if(u.push(h),h.shape[1]===a)return h;const d=tW({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),p=vG({inputs:{x:d},backend:n,attrs:{reps:[o/l]}});return u.push(d),u.push(p),g(h,t,p,s,a)},y=fz({inputs:{x:g(f,"unsortedSegmentSum",a,m,i)},backend:n,attrs:{shape:d}});let b=y;if(null!=c){u.push(y);const e=rh(c);b=Sz({inputs:{x:b},backend:n,attrs:{perm:e}})}return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),b}},FG=[Ez,$z,Rz,Mz,Oz,Pz,Bz,Vz,qz,Kz,Yz,Zz,eP,nP,sP,oP,uP,hP,dP,pP,gP,kP,IP,SP,NP,AP,MP,OP,ZL,PP,qP,tB,iB,uB,lB,cB,hB,pB,mB,yB,IB,SB,NB,EB,AB,MB,FB,OB,zB,PB,VB,UB,GB,jB,KB,YB,QB,nV,aV,oV,cV,dV,mV,bV,xV,vV,SV,TV,CV,YL,$V,GP,RV,MV,DV,tz,LV,PV,BV,UV,GV,jV,KV,YV,QV,tU,rU,aU,iU,oU,cU,hU,dU,pU,fU,gU,xU,vU,AU,pz,_U,FU,OU,zU,EP,BU,WU,GU,KU,YU,sz,JU,ZU,QU,eW,nW,$P,SU,sW,iW,uW,mz,hW,pW,gW,bW,vW,IW,NW,EW,AW,_W,FW,OW,zW,BW,UW,GW,vP,$U,jW,qW,KW,XW,YW,JW,ZW,QW,nG,sG,oG,uG,lG,hG,dG,pG,fG,EU,Iz,gG,bG,xG,kG,EG,$G,Nz,AG,RG,MG,UU];for(const e of FG)Ts(e);const DG={"tfjs-core":$l,"tfjs-backend-cpu":pA,"tfjs-backend-webgl":UL,"tfjs-data":PE,"tfjs-layers":Rw,"tfjs-converter":_T,tfjs:"4.22.0"}},985:function(e,t,n){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&s(t,e,n[i]);return a(t,e),t}),o=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,s=0,a=t.length;s<a;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.computeAffineMatrixML=function(e,t){e.length;var n=e.map(function(e){return o(o([],e,!0),[1],!1)}),r=new u.Matrix(n),s=new u.Matrix(t);return(0,u.solve)(r,s).transpose().to2DArray()},t.applyAffineMatrix=function(e,t){var n=t.reshape([-1,2]),r=l.ones([n.shape[0],1]),s=l.concat([n,r],1),a=e.transpose(),i=l.matMul(s,a);return l.dispose([n,r,s,a]),i.reshape(t.shape)},t.computeHomography=k,t.applyHomography=I,t.warpImageData=S,t.cropImageData=N,t.obtainEyePatch=function(e,t,n,r,s){void 0===n&&(n=[.4,.2]),void 0===r&&(r=512),void 0===s&&(s=[512,128]);var a=t[4],i=t[103],o=t[150],u=t[332],l=[i,o,t[379],u],c=k(l=l.map(function(e){var t=e[0],r=e[1],s=t-a[0],i=r-a[1];return[t+s*n[0],r+i*n[1]]}),[[0,0],[0,r],[r,r],[r,0]]),h=S(e,c,r,r),d=t.map(function(e){return I(c,e)}),p=d[151],f=d[195],m=N(h,0,Math.round(p[1]),h.width,Math.round(f[1]-p[1]));return S(m,k([[0,0],[0,m.height],[m.width,m.height],[m.width,0]],[[0,0],[0,s[1]],[s[0],s[1]],[s[0],0]]),s[0],s[1])},t.translateMatrix=function(e){for(var t=e.data,n=new u.Matrix(e.rows,e.columns),r=0;r<e.rows;r++)for(var s=0;s<e.columns;s++)n.set(r,s,t[r*e.columns+s]);return n},t.createPerspectiveMatrix=function(e){var t=Math.PI/180,n=1/Math.tan(t*x/2),r=1/(w-v),s=new u.Matrix(4,4).fill(0);return s.set(0,0,n/e),s.set(1,1,n),s.set(2,2,(w+v)*r),s.set(2,3,-1),s.set(3,2,2*v*w*r),s},t.createIntrinsicsMatrix=function(e,t,n){var r,s,a=e,i=a/2,o=t/2;if(void 0!==n){var l=n*Math.PI/180;s=r=a/(2*Math.tan(l/2))}else r=s=a;return new u.Matrix([[r,0,i],[0,s,o],[0,0,1]])},t.estimateFaceWidth=function(e){for(var t=[],n=0,r=["left","right"];n<r.length;n++){var s="left"===r[n]?f:p,a=T(e[s[4]].slice(0,2),e[s[2]].slice(0,2));t.push(a)}var i=t.reduce(function(e,t){return e+t},0)/t.length,o=T(e[h],e[d]);return m/(i/o)},t.convertUvToXyz=E,t.imageShiftTo3D=C,t.transform3DTo3D=$,t.transform3DTo2D=A,t.partialProcrustesTranslation2D=R,t.refineDepthByRadialMagnitude=_,t.faceReconstruction=function(e,t,n,r,s,a,i,o){var l;void 0===o&&(o=60);var c=t.map(function(t){var n=t[0],r=t[1];return E(e,n,r,o)}),p=c[4],f=c.map(function(e){var t=e[0],n=e[1],r=e[2];return[-(t-p[0]),-(n-p[1]),r-p[2]]}),m=f[h],g=f[d],y=Math.hypot(m[0]-g[0],m[1]-g[1],m[2]-g[2]),b=f.map(function(e){var t=e[0],n=e[1],r=e[2];return[t/y*s,n/y*s,r/y*s]}),x=n.subMatrix(0,2,0,2),w=M(x),v=w[0],k=w[1],I=w[2],S=F(v=(l=[-k,v])[0],k=l[1],I),N=b.map(function(e){return t=e,n=S.transpose(),r=t[0],s=t[1],a=t[2],[(i=n.mmul(u.Matrix.columnVector([r,s,a])).to1DArray())[0],i[1],i[2]];var t,n,r,s,a,i}),T=[0,1,2].map(function(e){return Math.sqrt(Math.pow(x.get(0,e),2)+Math.pow(x.get(1,e),2)+Math.pow(x.get(2,e),2))}).reduce(function(e,t){return e+t},0)/3,D=u.Matrix.eye(4);D.setSubMatrix(S.div(T),0,0),D.set(0,3,0),D.set(1,3,0),D.set(2,3,o);var O=N.map(function(e){return $(e,D)}).map(function(e){return A(e,r)}),L=t.map(function(e){var t=e[0],n=e[1];return[t*a,n*i]}),z=C(R(O,L),o,r),P=D.clone();P.set(0,3,P.get(0,3)+z[0]),P.set(1,3,P.get(1,3)+z[1]),P.set(2,3,P.get(2,3)+z[2]);for(var B=P.clone(),V=o,U=0;U<10&&(V=_(N.map(function(e){return A($(e,P),r)}),L,P.get(2,3),.5),!(Math.abs(V-P.get(2,3))<.25));U++){var W=B.get(0,3)*(V/o),G=B.get(1,3)*(V/o);P.set(0,3,W),P.set(1,3,G),P.set(2,3,V)}var H=N.map(function(e){return $(e,P)});return[P,H]},t.computeFaceOrigin3D=function(e){var t=function(t){var n=t.map(function(t){return e[t]}),r=n.reduce(function(e,t){var n=t[0],r=t[1],s=t[2];return[e[0]+n,e[1]+r,e[2]+s]},[0,0,0]);return[r[0]/n.length,r[1]/n.length,r[2]/n.length]},n=t(g),r=t(y);return[(n[0]+r[0])/2,(n[1]+r[1])/2,(n[2]+r[2])/2]},t.matrixToEuler=M,t.eulerToMatrix=F,t.getHeadVector=function(e){var t=M(new u.Matrix([[e.get(0,0),e.get(0,1),e.get(0,2)],[e.get(1,0),e.get(1,1),e.get(1,2)],[e.get(2,0),e.get(2,1),e.get(2,2)]]),!1),n=t[0],r=[-t[1],n,t[2]];return function(e,t,n){var r=Math.cos(e)*Math.sin(t),s=Math.sin(e),a=-Math.cos(e)*Math.cos(t),i=new u.Matrix([[r,s,a]]),o=[Math.cos(n),Math.sin(n)],l=o[0],c=o[1];return new u.Matrix([[l,-c,0],[c,l,0],[0,0,1]]).mmul(i.transpose()).transpose().to1DArray()}(r[0],r[1],r[2])},t.computeEAR=function(e,t){var n=("left"===t?D:O).map(function(t){return[e[t].x,e[t].y]}
5057),r=n[0],s=n[1],a=n[2],i=n[3],o=n[4],u=n[5];return(Math.sqrt(Math.pow(s[0]-u[0],2)+Math.pow(s[1]-u[1],2))+Math.sqrt(Math.pow(a[0]-o[0],2)+Math.pow(a[1]-o[1],2)))/(2*Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2)))};var u=n(673),l=i(n(951)),c=n(298),h=356,d=127,p=[468,470,469,472,471],f=[473,475,474,477,476],m=1.2,g=[362,263],y=[33,133],b=5,x=60,w=1,v=1e4;function k(e,t){if(4!==e.length||4!==t.length)throw new Error("Need exactly 4 source and 4 destination points");for(var n=[],r=0;r<4;r++){var s=e[r],a=s[0],i=s[1],o=t[r],l=o[0],h=o[1];n.push([-a,-i,-1,0,0,0,a*l,i*l,l]),n.push([0,0,0,-a,-i,-1,a*h,i*h,h])}var d=new u.Matrix(n),p=(0,c.safeSVD)(d).rightSingularVectors,f=p.getColumn(p.columns-1);return[f.slice(0,3),f.slice(3,6),f.slice(6,9)]}function I(e,t){var n=t[0],r=t[1],s=e[2][0]*n+e[2][1]*r+e[2][2];return[(e[0][0]*n+e[0][1]*r+e[0][2])/s,(e[1][0]*n+e[1][1]*r+e[1][2])/s]}function S(e,t,n,r){for(var s=(0,u.inverse)(new u.Matrix(t)).to2DArray(),a=new ImageData(n,r),i=e.data,o=a.data,l=e.width,c=e.height,h=0;h<r;h++)for(var d=0;d<n;d++){var p=s[2][0]*d+s[2][1]*h+s[2][2],f=(s[0][0]*d+s[0][1]*h+s[0][2])/p,m=(s[1][0]*d+s[1][1]*h+s[1][2])/p,g=Math.floor(f),y=Math.floor(m);if(!(g<0||y<0||g>=l||y>=c)){var b=4*(y*l+g),x=4*(h*n+d);o[x]=i[b],o[x+1]=i[b+1],o[x+2]=i[b+2],o[x+3]=i[b+3]}}return a}function N(e,t,n,r,s){for(var a=new ImageData(r,s),i=e.data,o=a.data,u=e.width,l=0;l<s;l++)for(var c=0;c<r;c++){var h=4*((n+l)*u+(t+c)),d=4*(l*r+c);o[d]=i[h],o[d+1]=i[h+1],o[d+2]=i[h+2],o[d+3]=i[h+3]}return a}function T(e,t){var n=e[0]-t[0],r=e[1]-t[1];return Math.sqrt(n*n+r*r)}function E(e,t,n,r){var s=2*t-1,a=1-2*n,i=new u.Matrix([[s],[a],[-1],[1]]),o=(0,u.inverse)(e).mmul(i),l=o.get(3,0),c=o.get(0,0)/l,h=o.get(1,0)/l;return o.get(2,0),[-c,h,r]}function C(e,t,n){var r=n.get(0,0),s=n.get(1,1);return[e[0]*(t/r),e[1]*(t/s),0]}function $(e,t){var n=[e[0],e[1],e[2],1],r=t.mmul(u.Matrix.columnVector(n)).to1DArray();return[r[0],r[1],r[2]]}function A(e,t){var n=1e-6,r=e[0],s=e[1],a=e[2],i=t.mmul(u.Matrix.columnVector([r,s,a])).to1DArray(),o=Math.abs(i[2])<n?n:i[2];return[Math.round(i[0]/o),Math.round(i[1]/o)]}function R(e,t){var n=e[4],r=n[0],s=n[1],a=t[4];return[a[0]-r,a[1]-s]}function _(e,t,n,r){void 0===r&&(r=.5);for(var s=e.length,a=t.reduce(function(e,t){var n=t[0],r=t[1];return[e[0]+n/s,e[1]+r/s]},[0,0]),i=0,o=0;o<s;o++){var u=e[o],l=t[o],c=[l[0]-u[0],l[1]-u[1]],h=Math.hypot(c[0],c[1]),d=[a[0]-u[0],a[1]-u[1]];i+=c[0]*d[0]+c[1]*d[1]<0?-h:h}var p=i/s*.1;return n+Math.max(-b,Math.min(b,p))}function M(e,t){if(void 0===t&&(t=!0),3!==e.rows||3!==e.columns)throw new Error("Rotation matrix must be 3x3.");var n=Math.asin(-e.get(2,0)),r=Math.atan2(e.get(2,1),e.get(2,2)),s=Math.atan2(e.get(1,0),e.get(0,0));if(t){var a=180/Math.PI;return[n*a,r*a,s*a]}return[n,r,s]}function F(e,t,n,r){void 0===r&&(r=!0),r&&(e*=Math.PI/180,t*=Math.PI/180,n*=Math.PI/180);var s=Math.cos(e),a=Math.sin(e),i=Math.cos(t),o=Math.sin(t),l=Math.cos(n),c=Math.sin(n),h=new u.Matrix([[1,0,0],[0,s,-a],[0,a,s]]),d=new u.Matrix([[i,0,o],[0,1,0],[-o,0,i]]);return new u.Matrix([[l,-c,0],[c,l,0],[0,0,1]]).mmul(d).mmul(h)}var D=[362,385,387,263,373,380],O=[133,158,160,33,144,153]}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var a=t[r]={id:r,loaded:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n(44)})();',"Worker",void 0,void 0)}},985:function(Et,ye,Z){var Xe,Vt=this&&this.__createBinding||(Object.create?function(De,Ye,rt,qe){qe===void 0&&(qe=rt);var He=Object.getOwnPropertyDescriptor(Ye,rt);
5057He&&!("get"in He?!Ye.__esModule:He.writable||He.configurable)||(He={enumerable:!0,get:function(){return Ye[rt]}}),Object.defineProperty(De,qe,He)}:function(De,Ye,rt,qe){qe===void 0&&(qe=rt),De[qe]=Ye[rt]}),ht=this&&this.__setModuleDefault||(Object.create?function(De,Ye){Object.defineProperty(De,"default",{enumerable:!0,value:Ye})}:function(De,Ye){De.default=Ye}),Nt=this&&this.__importStar||(Xe=function(De){return Xe=Object.getOwnPropertyNames||function(Ye){var rt=[];for(var qe in Ye)Object.prototype.hasOwnProperty.call(Ye,qe)&&(rt[rt.length]=qe);return rt},Xe(De)},function(De){if(De&&De.__esModule)return De;var Ye={};if(De!=null)for(var rt=Xe(De),qe=0;qe<rt.length;qe++)rt[qe]!=="default"&&Vt(Ye,De,rt[qe]);return ht(Ye,De),Ye}),ct=this&&this.__spreadArray||function(De,Ye,rt){if(rt||arguments.length===2)for(var qe,He=0,At=Ye.length;He<At;He++)!qe&&He in Ye||(qe||(qe=Array.prototype.slice.call(Ye,0,He)),qe[He]=Ye[He]);return De.concat(qe||Array.prototype.slice.call(Ye))};Object.defineProperty(ye,"__esModule",{value:!0}),ye.computeAffineMatrixML=function(De,Ye){De.length;var rt=De.map(function(At){return ct(ct([],At,!0),[1],!1)}),qe=new Te.Matrix(rt),He=new Te.Matrix(Ye);return(0,Te.solve)(qe,He).transpose().to2DArray()},ye.applyAffineMatrix=function(De,Ye){var rt=Ye.reshape([-1,2]),qe=ke.ones([rt.shape[0],1]),He=ke.concat([rt,qe],1),At=De.transpose(),Ut=ke.matMul(He,At);return ke.dispose([rt,qe,He,At]),Ut.reshape(Ye.shape)},ye.computeHomography=pt,ye.applyHomography=Ne,ye.warpImageData=Pe,ye.cropImageData=G,ye.obtainEyePatch=function(De,Ye,rt,qe,He){rt===void 0&&(rt=[.4,.2]),qe===void 0&&(qe=512),He===void 0&&(He=[512,128]);var At=Ye[4],Ut=Ye[103],at=Ye[150],Kt=Ye[332],M=[Ut,at,Ye[379],Kt],S=pt(M=M.map(function(Q){var te=Q[0],Ce=Q[1],Ae=te-At[0],mt=Ce-At[1];return[te+Ae*rt[0],Ce+mt*rt[1]]}),[[0,0],[0,qe],[qe,qe],[qe,0]]),b=Pe(De,S,qe,qe),k=Ye.map(function(Q){return Ne(S,Q)}),E=k[151],F=k[195],B=G(b,0,Math.round(E[1]),b.width,Math.round(F[1]-E[1]));return Pe(B,pt([[0,0],[0,B.height],[B.width,B.height],[B.width,0]],[[0,0],[0,He[1]],[He[0],He[1]],[He[0],0]]),He[0],He[1])},ye.translateMatrix=function(De){for(var Ye=De.data,rt=new Te.Matrix(De.rows,De.columns),qe=0;qe<De.rows;qe++)for(var He=0;He<De.columns;He++)rt.set(qe,He,Ye[qe*De.columns+He]);return rt},ye.createPerspectiveMatrix=function(De){var Ye=Math.PI/180,rt=1/Math.tan(Ye*tt/2),qe=1/(Ee-Re),He=new Te.Matrix(4,4).fill(0);return He.set(0,0,rt/De),He.set(1,1,rt),He.set(2,2,(Ee+Re)*qe),He.set(2,3,-1),He.set(3,2,2*Re*Ee*qe),He},ye.createIntrinsicsMatrix=function(De,Ye,rt){var qe,He,At=De,Ut=At/2,at=Ye/2;if(rt!==void 0){var Kt=rt*Math.PI/180;He=qe=At/(2*Math.tan(Kt/2))}else qe=He=At;return new Te.Matrix([[qe,0,Ut],[0,He,at],[0,0,1]])},ye.estimateFaceWidth=function(De){for(var Ye=[],rt=0,qe=["left","right"];rt<qe.length;rt++){var He=qe[rt]==="left"?Se:pe,At=Be(De[He[4]].slice(0,2),De[He[2]].slice(0,2));Ye.push(At)}var Ut=Ye.reduce(function(Kt,M){return Kt+M},0)/Ye.length,at=Be(De[H],De[ie]);return Qe/(Ut/at)},ye.convertUvToXyz=Ze,ye.imageShiftTo3D=$t,ye.transform3DTo3D=Wt,ye.transform3DTo2D=yn,ye.partialProcrustesTranslation2D=Jt,ye.refineDepthByRadialMagnitude=fn,ye.faceReconstruction=function(De,Ye,rt,qe,He,At,Ut,at){var Kt;at===void 0&&(at=60);var M=Ye.map(function(q){var Le=q[0],Oe=q[1];return Ze(De,Le,Oe,at)}),S=M[4],b=M.map(function(q){var Le=q[0],Oe=q[1],je=q[2];return[-(Le-S[0]),-(Oe-S[1]),je-S[2]]}),k=b[H],E=b[ie],F=Math.hypot(k[0]-E[0],k[1]-E[1],k[2]-E[2]),B=b.map(function(q){var Le=q[0],Oe=q[1],je=q[2];return[Le/F*He,Oe/F*He,je/F*He]}),Q=rt.subMatrix(0,2,0,2),te=cn(Q),Ce=te[0],Ae=te[1],mt=te[2],et=Yn(Ce=(Kt=[-Ae,Ce])[0],Ae=Kt[1],mt),it=B.map(function(q){return Le=q,Oe=et.transpose(),je=Le[0],_t=Le[1],Zt=Le[2],[(hn=Oe.mmul(Te.Matrix.columnVector([je,_t,Zt])).to1DArray())[0],hn[1],hn[2]];var Le,Oe,je,_t,Zt,hn}),A=[0,1,2].map(function(q){return Math.sqrt(Math.pow(Q.get(0,q),2)+Math.pow(Q.get(1,q),2)+Math.pow(Q.get(2,q),2))}).reduce(function(q,Le){return q+Le},0)/3,ge=Te.Matrix.eye(4);ge.setSubMatrix(et.div(A),0,0),ge.set(0,3,0),ge.set(1,3,0),ge.set(2,3,at);var Ve=it.map(function(q){return Wt(q,ge)}).map(function(q){return yn(q,qe)}),j=Ye.map(function(q){var Le=q[0],Oe=q[1];return[Le*At,Oe*Ut]}),oe=$t(Jt(Ve,j),at,qe),Y=ge.clone();Y.set(0,3,Y.get(0,3)+oe[0]),Y.set(1,3,Y.get(1,3)+oe[1]),Y.set(2,3,Y.get(2,3)+oe[2]);for(var le=Y.clone(),ue=at,vt=0;vt<10&&(ue=fn(it.map(function(q){return yn(Wt(q,Y),qe)}),j,Y.get(2,3)),!(Math.abs(ue-Y.get(2,3))<.25));vt++){var Me=le.get(0,3)*(ue/at),en=le.get(1,3)*(ue/at);Y.set(0,3,Me),Y.set(1,3,en),Y.set(2,3,ue)}var jt=it.map(function(q){return Wt(q,Y)});return[Y,jt]},ye.computeFaceOrigin3D=function(De){var Ye=function(He){var At=He.map(function(at){return De[at]}),Ut=At.reduce(function(at,Kt){var M=Kt[0],S=Kt[1],b=Kt[2];return[at[0]+M,at[1]+S,at[2]+b]},[0,0,0]);return[Ut[0]/At.length,Ut[1]/At.length,Ut[2]/At.length]},rt=Ye(Ke),qe=Ye(de);return[(rt[0]+qe[0])/2,(rt[1]+qe[1])/2,(rt[2]+qe[2])/2]},ye.matrixToEuler=cn,ye.eulerToMatrix=Yn,ye.getHeadVector=function(De){var Ye=cn(new Te.Matrix([[De.get(0,0),De.get(0,1),De.get(0,2)],[De.get(1,0),De.get(1,1),De.get(1,2)],[De.get(2,0),De.get(2,1),De.get(2,2)]]),!1),rt=Ye[0],qe=[-Ye[1],rt,Ye[2]];return function(He,At,Ut){var at=Math.cos(He)*Math.sin(At),Kt=Math.sin(He),M=-Math.cos(He)*Math.cos(At),S=new Te.Matrix([[at,Kt,M]]),b=[Math.cos(Ut),Math.sin(Ut)],k=b[0],E=b[1];return new Te.Matrix([[k,-E,0],[E,k,0],[0,0,1]]).mmul(S.transpose()).transpose().to1DArray()}(qe[0],qe[1],qe[2])},ye.computeEAR=function(De,Ye){var rt=(Ye==="left"?Dn:zn).map(function(M){return[De[M].x,De[M].y]}),qe=rt[0],He=rt[1],At=rt[2],Ut=rt[3],at=rt[4],Kt=rt[5];return(Math.sqrt(Math.pow(He[0]-Kt[0],2)+Math.pow(He[1]-Kt[1],2))+Math.sqrt(Math.pow(At[0]-at[0],2)+Math.pow(At[1]-at[1],2)))/(2*Math.sqrt(Math.pow(qe[0]-Ut[0],2)+Math.pow(qe[1]-Ut[1],2)))};var Te=Z(673),ke=Nt(Z(951)),K=Z(298),H=356,ie=127,pe=[468,470,469,472,471],Se=[473,475,474,477,476],Qe=1.2,Ke=[362,263],de=[33,133],Fe=5,tt=60,Ee=1,Re=1e4;function pt(De,Ye){if(De.length!==4||Ye.length!==4)throw new Error("Need exactly 4 source and 4 destination points");for(var rt=[],qe=0;qe<4;qe++){var He=De[qe],At=He[0],Ut=He[1],at=Ye[qe],Kt=at[0],M=at[1];rt.push([-At,-Ut,-1,0,0,0,At*Kt,Ut*Kt,Kt]),rt.push([0,0,0,-At,-Ut,-1,At*M,Ut*M,M])}var S=new Te.Matrix(rt),b=(0,K.safeSVD)(S).rightSingularVectors,k=b.getColumn(b.columns-1);return[k.slice(0,3),k.slice(3,6),k.slice(6,9)]}function Ne(De,Ye){var rt=Ye[0],qe=Ye[1],He=De[2][0]*rt+De[2][1]*qe+De[2][2];return[(De[0][0]*rt+De[0][1]*qe+De[0][2])/He,(De[1][0]*rt+De[1][1]*qe+De[1][2])/He]}function Pe(De,Ye,rt,qe){for(var He=(0,Te.inverse)(new Te.Matrix(Ye)).to2DArray(),At=new ImageData(rt,qe),Ut=De.data,at=At.data,Kt=De.width,M=De.height,S=0;S<qe;S++)for(var b=0;b<rt;b++){var k=He[2][0]*b+He[2][1]*S+He[2][2],E=(He[0][0]*b+He[0][1]*S+He[0][2])/k,F=(He[1][0]*b+He[1][1]*S+He[1][2])/k,B=Math.floor(E),Q=Math.floor(F);if(!(B<0||Q<0||B>=Kt||Q>=M)){var te=4*(Q*Kt+B),Ce=4*(S*rt+b);at[Ce]=Ut[te],at[Ce+1]=Ut[te+1],at[Ce+2]=Ut[te+2],at[Ce+3]=Ut[te+3]}}return At}function G(De,Ye,rt,qe,He){for(var At=new ImageData(qe,He),Ut=De.data,at=At.data,Kt=De.width,M=0;M<He;M++)for(var S=0;S<qe;S++){var b=4*((rt+M)*Kt+(Ye+S)),k=4*(M*qe+S);at[k]=Ut[b],at[k+1]=Ut[b+1],at[k+2]=Ut[b+2],at[k+3]=Ut[b+3]}return At}function Be(De,Ye){var rt=De[0]-Ye[0],qe=De[1]-Ye[1];return Math.sqrt(rt*rt+qe*qe)}function Ze(De,Ye,rt,qe){var He=2*Ye-1,At=1-2*rt,Ut=new Te.Matrix([[He],[At],[-1],[1]]),at=(0,Te.inverse)(De).mmul(Ut),Kt=at.get(3,0),M=at.get(0,0)/Kt,S=at.get(1,0)/Kt;return at.get(2,0),[-M,S,qe]}function $t(De,Ye,rt){var qe=rt.get(0,0),He=rt.get(1,1);return[De[0]*(Ye/qe),De[1]*(Ye/He),0]}function Wt(De,Ye){var rt=[De[0],De[1],De[2],1],qe=Ye.mmul(Te.Matr
5057ix.columnVector(rt)).to1DArray();return[qe[0],qe[1],qe[2]]}function yn(De,Ye){var rt=1e-6,qe=De[0],He=De[1],At=De[2],Ut=Ye.mmul(Te.Matrix.columnVector([qe,He,At])).to1DArray(),at=Math.abs(Ut[2])<rt?rt:Ut[2];return[Math.round(Ut[0]/at),Math.round(Ut[1]/at)]}function Jt(De,Ye){var rt=De[4],qe=rt[0],He=rt[1],At=Ye[4];return[At[0]-qe,At[1]-He]}function fn(De,Ye,rt,qe){for(var He=De.length,At=Ye.reduce(function(F,B){var Q=B[0],te=B[1];return[F[0]+Q/He,F[1]+te/He]},[0,0]),Ut=0,at=0;at<He;at++){var Kt=De[at],M=Ye[at],S=[M[0]-Kt[0],M[1]-Kt[1]],b=Math.hypot(S[0],S[1]),k=[At[0]-Kt[0],At[1]-Kt[1]];Ut+=S[0]*k[0]+S[1]*k[1]<0?-b:b}var E=Ut/He*.1;return rt+Math.max(-Fe,Math.min(Fe,E))}function cn(De,Ye){if(Ye===void 0&&(Ye=!0),De.rows!==3||De.columns!==3)throw new Error("Rotation matrix must be 3x3.");var rt=Math.asin(-De.get(2,0)),qe=Math.atan2(De.get(2,1),De.get(2,2)),He=Math.atan2(De.get(1,0),De.get(0,0));if(Ye){var At=180/Math.PI;return[rt*At,qe*At,He*At]}return[rt,qe,He]}function Yn(De,Ye,rt,qe){qe===void 0&&(qe=!0),qe&&(De*=Math.PI/180,Ye*=Math.PI/180,rt*=Math.PI/180);var He=Math.cos(De),At=Math.sin(De),Ut=Math.cos(Ye),at=Math.sin(Ye),Kt=Math.cos(rt),M=Math.sin(rt),S=new Te.Matrix([[1,0,0],[0,He,-At],[0,At,He]]),b=new Te.Matrix([[Ut,0,at],[0,1,0],[-at,0,Ut]]);return new Te.Matrix([[Kt,-M,0],[M,Kt,0],[0,0,1]]).mmul(b).mmul(S)}var Dn=[362,385,387,263,373,380],zn=[133,158,160,33,144,153]}},_a={};function es(Et){var ye=_a[Et];if(ye!==void 0)return ye.exports;var Z=_a[Et]={id:Et,loaded:!1,exports:{}};return vr[Et].call(Z.exports,Z,Z.exports,es),Z.loaded=!0,Z.exports}return es.amdD=function(){throw new Error("define cannot be used indirect")},es.amdO={},es.n=Et=>{var ye=Et&&Et.__esModule?()=>Et.default:()=>Et;return es.d(ye,{a:ye}),ye},es.d=(Et,ye)=>{for(var Z in ye)es.o(ye,Z)&&!es.o(Et,Z)&&Object.defineProperty(Et,Z,{enumerable:!0,get:ye[Z]})},es.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),es.o=(Et,ye)=>Object.prototype.hasOwnProperty.call(Et,ye),es.r=Et=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Et,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Et,"__esModule",{value:!0})},es.nmd=Et=>(Et.paths=[],Et.children||(Et.children=[]),Et),es(156)})())})(iT);var oT=iT.exports;const g6=p6(oT),x6=m6({__proto__:null,default:g6},[oT]);export{x6 as i};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.