/** * @license * Copyright 2023 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@tensorflow/tfjs-core")):"function"==typeof define&&define.amd?define(["exports","@tensorflow/tfjs-core"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{},e.tf)}(this,(function(e,t){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,t}function r(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),e}var s=n(t);var a,o;t.env().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"}(a||(a={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(o||(o={}));const i={};function u(e){return i[e]}function p(e,n,r,s,a){const o=n.inputParams[e];if(o&&void 0!==o.inputIndexStart){const e=o.inputIndexStart,i=0===o.inputIndexEnd?void 0:void 0===o.inputIndexEnd?e+1:o.inputIndexEnd,u=e<0?n.inputNames.length+e:e;if("tensor"===o.type)return l(n.inputNames[u],r,s,a);if("tensors"===o.type){const t=n.inputs.slice(e,i);return n.inputNames.slice(e,i).filter(((e,n)=>{var r;return"NoOp"!==(null===(r=t[n])||void 0===r?void 0:r.op)})).map((e=>l(e,r,s,a)))}const p=l(n.inputNames[u],r,s,a),c=p.dataSync();return"number"===o.type?c[0]:t.util.toNestedArray(p.shape,c)}const i=n.attrParams[e];return i&&i.value}function l(e,t,n,r){const[s,a]=m(e,n);if(null!=r){const e=r.getHashTableHandleByName(s);if(null!=e)return e}const o=n.currentContextIds.find((e=>!!t[d(s,e)]));return void 0!==o?t[d(s,o)][a]:void 0}function c(e,t,n){return t[d(e,n.currentContextId)]}function h(e,t){const[n,r,s]=m(e,t);return[d(n,t&&t.currentContextId),r,s]}function d(e,t){return t?`${e}-${t}`:e}function m(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 f(e,t,n){let r=p("pad",e,t,n);if("explicit"===r){r=p("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 y(e){return e.kept?e:t.clone(e)}var g={__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]};var b={__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]};var x={__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]};var N={__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]};var w={__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]};var k={__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]};var T={__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]};var v={__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]};var S={__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]};var _={__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]};var E={__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]};var I={__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]};var $={__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}]};var A={__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]};var D={__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]};var O={__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]};var M={__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]};var C={__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]};var F={__proto__:null,json:[{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 R{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[g,b,x,N,w,k,T,v,S,_,E,I,$,A,D,O,M,C,F].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,r=[],s=[],a=[],o=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 i=[];const u=[];let p={},l={};null!=t&&(p=this.mapSignatureEntries(t.inputs),l=this.mapSignatureEntries(t.outputs));const c=Object.keys(o);c.forEach((e=>{const t=o[e];t.inputNames.forEach(((e,n)=>{const[r,,s]=h(e),a=o[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(l).length?c.forEach((e=>{const t=o[e];0===t.children.length&&u.push(t)})):Object.keys(l).forEach((e=>{const[t]=h(e),n=o[t];null!=n&&(n.signatureKey=l[e],u.push(n))})),Object.keys(p).length>0?Object.keys(p).forEach((e=>{const[t]=h(e),n=o[t];n&&(n.signatureKey=p[e],i.push(n))})):i=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 m={nodes:o,inputs:i,outputs:u,weights:s,placeholders:r,signature:t,functions:d};return a.length>0&&(m.initNodes=a),m}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=u(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=V(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=V(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":s=H(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=H(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":s=B(e.attr,n.tfName,n.defaultValue||0),void 0===s&&n.tfDeprecatedName&&(s=B(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":s=G(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=G(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":s=L(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=L(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":s=Q(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Q(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":s=W(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=W(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":s=Z(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Z(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":s=q(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=q(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":s=U(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=U(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":s=K(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=K(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]=h(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:P(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]=h(e),o=r[s];if(null!=o.outputs){const e=o.outputs.indexOf(a);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)}))}));const o=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=h(o[e.name]),s=r[t];null!=s&&(s.defaultOutput=n,a.push(s))}));const i=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:a,weights:n,placeholders:[],signature:i}}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 z(e,n){const r=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const n=t.env().global;if("undefined"!=typeof n.atob)return n.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 n?r:r.toLowerCase()}function V(e,t,n,r=!1){const s=e[t];return null!=s?z(s.s,r):n}function L(e,t,n){const r=e[t];return r?r.b:n}function B(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 P(e){switch("string"==typeof e&&(e=a[e]),e){case a.DT_FLOAT:case a.DT_HALF:return"float32";case a.DT_INT32:case a.DT_INT64:case a.DT_INT8:case a.DT_UINT8:return"int32";case a.DT_BOOL:return"bool";case a.DT_DOUBLE:return"float32";case a.DT_STRING:return"string";default:return null}}function K(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function q(e,t,n){const r=e[t];return r&&r.type?P(r.type):n}function U(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>P(e))):n}function j(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function W(e,t,n){const r=e[t];return r&&r.shape?j(r.shape):n}function G(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 H(e,t,n,r=!1){const s=e[t];return s&&s.list&&s.list.s?s.list.s.map((e=>z(e,r))):n}function Z(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>j(e))):n}function Q(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Y{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 l(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return l(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return B(this.node.rawAttrs,e,t);if(null!=n.s)return V(this.node.rawAttrs,e,t);if(null!=n.b)return L(this.node.rawAttrs,e,t);if(null!=n.shape)return W(this.node.rawAttrs,e,t);if(null!=n.type)return q(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return G(this.node.rawAttrs,e,t);if(null!=n.list.s)return H(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Z(this.node.rawAttrs,e,t);if(null!=n.list.b)return Q(this.node.rawAttrs,e,t);if(null!=n.list.type)return U(this.node.rawAttrs,e,t)}return t}}function X(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 J(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function ee(e,t,n=""){J(re(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function te(e){J(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function ne(e){if(0===e.length)return 1;let t=e[0];for(let n=1;nt)):[].concat(e)).every((e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),J(e.every((e=>se(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}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 ue(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 pe(e){return"string"==typeof e||e instanceof String}function le(e){return Array.isArray(e)?le(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"==typeof e?"float32":pe(e)?"string":function(e){return"boolean"==typeof e}(e)?"bool":"float32"}function ce(e){return!!(e&&e.constructor&&e.call&&e.apply)}function he(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 de(e,t,n,r=!1){const s=new Array;if(1===t.length){const a=t[0]*(r?2:1);for(let t=0;te*t))*(r?2:1);for(let t=0;te*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 de(0,e,t,n)}function fe(e,t){const n=ye(e,t);for(let e=0;e{J(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function be(e){return e&&e.then&&"function"==typeof e.then}const xe="tfjsflags";class Ne{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=we,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(ke().getBool("IS_TEST")||ke().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];ke().getBool("IS_TEST")||ke().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(be(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("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(xe in e){e.tfjsflags.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 we(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 ke(){return ve}let Te,ve=null;function Se(){if(null==Te){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Te=e}return Te}function _e(e,t){const n=function(){const e=Se();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 Ee="Cast",Ie="Identity",$e="Tile",Ae="Transpose",De="_FusedMatMul",Oe="FusedConv2D",Me="FusedDepthwiseConv2D";function Ce(...e){ke().getBool("IS_TEST")||ke().getBool("PROD")||console.warn(...e)}const Fe=_e("kernelRegistry",(()=>new Map)),Re=_e("gradRegistry",(()=>new Map));function ze(e,t){const n=function(e,t){return`${t}_${e}`}(e,t);return Fe.get(n)}function Ve(e){return Re.get(e)}function Le(e){const t=Fe.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[a,o]=s,[i]=a.split("_");i===e&&n.push(o)}return n}var Be="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Pe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ke(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){if(this instanceof e){var n=[null];n.push.apply(n,arguments);var r=Function.bind.apply(t,n);return new r}return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var qe=je,Ue=null;try{Ue=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 je(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function We(e){return!0===(e&&e.__isLong__)}je.prototype.__isLong__,Object.defineProperty(je.prototype,"__isLong__",{value:!0}),je.isLong=We;var Ge={},He={};function Ze(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=He[e])?r:(n=Ye(e,(0|e)<0?-1:0,!0),s&&(He[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=Ge[e])?r:(n=Ye(e,e<0?-1:0,!1),s&&(Ge[e]=n),n)}function Qe(e,t){if(isNaN(e))return t?ot:at;if(t){if(e<0)return ot;if(e>=nt)return ct}else{if(e<=-rt)return ht;if(e+1>=rt)return lt}return e<0?Qe(-e,t).neg():Ye(e%tt|0,e/tt|0,t)}function Ye(e,t,n){return new je(e,t,n)}je.fromInt=Ze,je.fromNumber=Qe,je.fromBits=Ye;var Xe=Math.pow;function Je(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return at;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return Je(e.substring(1),t,n).neg();for(var s=Qe(Xe(n,8)),a=at,o=0;o>>0:this.low},dt.toNumber=function(){return this.unsigned?(this.high>>>0)*tt+(this.low>>>0):this.high*tt+(this.low>>>0)},dt.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((a=i).isZero())return u+o;for(;u.length<6;)u="0"+u;o=""+u+o}},dt.getHighBits=function(){return this.high},dt.getHighBitsUnsigned=function(){return this.high>>>0},dt.getLowBits=function(){return this.low},dt.getLowBitsUnsigned=function(){return this.low>>>0},dt.getNumBitsAbs=function(){if(this.isNegative())return this.eq(ht)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},dt.isOdd=function(){return 1==(1&this.low)},dt.isEven=function(){return 0==(1&this.low)},dt.equals=function(e){return We(e)||(e=et(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},dt.eq=dt.equals,dt.notEquals=function(e){return!this.eq(e)},dt.neq=dt.notEquals,dt.ne=dt.notEquals,dt.lessThan=function(e){return this.comp(e)<0},dt.lt=dt.lessThan,dt.lessThanOrEqual=function(e){return this.comp(e)<=0},dt.lte=dt.lessThanOrEqual,dt.le=dt.lessThanOrEqual,dt.greaterThan=function(e){return this.comp(e)>0},dt.gt=dt.greaterThan,dt.greaterThanOrEqual=function(e){return this.comp(e)>=0},dt.gte=dt.greaterThanOrEqual,dt.ge=dt.greaterThanOrEqual,dt.compare=function(e){if(We(e)||(e=et(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},dt.comp=dt.compare,dt.negate=function(){return!this.unsigned&&this.eq(ht)?ht:this.not().add(it)},dt.neg=dt.negate,dt.add=function(e){We(e)||(e=et(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=0,p=0,l=0,c=0;return l+=(c+=s+(65535&e.low))>>>16,p+=(l+=r+i)>>>16,u+=(p+=n+o)>>>16,u+=t+a,Ye((l&=65535)<<16|(c&=65535),(u&=65535)<<16|(p&=65535),this.unsigned)},dt.subtract=function(e){return We(e)||(e=et(e)),this.add(e.neg())},dt.sub=dt.subtract,dt.multiply=function(e){if(this.isZero())return at;if(We(e)||(e=et(e)),Ue)return Ye(Ue.mul(this.low,this.high,e.low,e.high),Ue.get_high(),this.unsigned);if(e.isZero())return at;if(this.eq(ht))return e.isOdd()?ht:at;if(e.eq(ht))return this.isOdd()?ht:at;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(st)&&e.lt(st))return Qe(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=65535&e.low,p=0,l=0,c=0,h=0;return c+=(h+=s*u)>>>16,l+=(c+=r*u)>>>16,c&=65535,l+=(c+=s*i)>>>16,p+=(l+=n*u)>>>16,l&=65535,p+=(l+=r*i)>>>16,l&=65535,p+=(l+=s*o)>>>16,p+=t*u+n*i+r*o+s*a,Ye((c&=65535)<<16|(h&=65535),(p&=65535)<<16|(l&=65535),this.unsigned)},dt.mul=dt.multiply,dt.divide=function(e){if(We(e)||(e=et(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Ue)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Ye((this.unsigned?Ue.div_u:Ue.div_s)(this.low,this.high,e.low,e.high),Ue.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?ot:at;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return ot;if(e.gt(this.shru(1)))return ut;r=ot}else{if(this.eq(ht))return e.eq(it)||e.eq(pt)?ht:e.eq(ht)?it:(t=this.shr(1).div(e).shl(1)).eq(at)?e.isNegative()?it:pt:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(ht))return this.unsigned?ot:at;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();r=at}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),a=s<=48?1:Xe(2,s-48),o=Qe(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=Qe(t-=a,this.unsigned)).mul(e);o.isZero()&&(o=it),r=r.add(o),n=n.sub(i)}return r},dt.div=dt.divide,dt.modulo=function(e){return We(e)||(e=et(e)),Ue?Ye((this.unsigned?Ue.rem_u:Ue.rem_s)(this.low,this.high,e.low,e.high),Ue.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},dt.mod=dt.modulo,dt.rem=dt.modulo,dt.not=function(){return Ye(~this.low,~this.high,this.unsigned)},dt.and=function(e){return We(e)||(e=et(e)),Ye(this.low&e.low,this.high&e.high,this.unsigned)},dt.or=function(e){return We(e)||(e=et(e)),Ye(this.low|e.low,this.high|e.high,this.unsigned)},dt.xor=function(e){return We(e)||(e=et(e)),Ye(this.low^e.low,this.high^e.high,this.unsigned)},dt.shiftLeft=function(e){return We(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ye(this.low<>>32-e,this.unsigned):Ye(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ye(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},dt.shr=dt.shiftRight,dt.shiftRightUnsigned=function(e){if(We(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Ye(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Ye(32===e?t:t>>>e-32,0,this.unsigned)},dt.shru=dt.shiftRightUnsigned,dt.shr_u=dt.shiftRightUnsigned,dt.toSigned=function(){return this.unsigned?Ye(this.low,this.high,!1):this},dt.toUnsigned=function(){return this.unsigned?this:Ye(this.low,this.high,!0)},dt.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},dt.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]},dt.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]},je.fromBytes=function(e,t,n){return n?je.fromBytesLE(e,t):je.fromBytesBE(e,t)},je.fromBytesLE=function(e,t){return new je(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},je.fromBytesBE=function(e,t){return new je(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var mt=Pe(qe);const ft=mt||r({__proto__:null,default:mt},[qe]);function yt(e){return ft.fromString(e,!0,16)}function gt(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=wt(e)),ke().getBool("DEBUG")&&function(e,t){for(let n=0;n{r=n()};let a;const o=bt();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();a=Promise.resolve({kernelMs:bt()-o})}if(ke().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{Tt(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;n.forEach((e=>{Promise.all([e.data(),r,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])}))}))}}function Tt(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${l}\t%c${p}\t%c${c}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function St(e,t,n,r){const s=he(t),a=function(e,t,n,r){const s=ne(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,u="complex64"===n?$t(e):e;if(i>1)for(let e=0;e" "+e)).join("\n")),u.join("\n")}function _t(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:pe(e)?`'${e}'`:"bool"===n?Et(e):parseFloat(e.toFixed(7)).toString(),ae(r,t)}function Et(e){return 0===e?"false":"true"}function It(e,t,n,r,s,a=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u){if("complex64"===n){return[_t($t(e)[0],0,n)]}return"bool"===n?[Et(e[0])]:[e[0].toString()]}if(1===u){if(i>20){const t=3*o;let r=Array.from(e.slice(0,t)),a=Array.from(e.slice((i-3)*o,i*o));return"complex64"===n&&(r=$t(r),a=$t(a)),["["+r.map(((e,t)=>_t(e,s[t],n))).join(", ")+", ..., "+a.map(((e,t)=>_t(e,s[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?$t(e):Array.from(e)).map(((e,t)=>_t(e,s[t],n))).join(", ")+"]"]}const p=t.slice(1),l=r.slice(1),c=r[0]*o,h=[];if(i>20){for(let t=0;t<3;t++){const r=t*c,a=r+c;h.push(...It(e.slice(r,a),p,n,l,s,!1))}h.push("...");for(let t=i-3;t0?h[0]+d:"");for(let e=1;e`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=he(e)}set(e,...t){0===t.length&&(t=[0]),J(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;txt(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(),Dt().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Dt().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>xt(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 Dt().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Dt().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ot.print(this,e)}clone(){return this.throwIfDisposed(),Ot.clone(this)}toString(e=!1){return St(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ot.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Dt().makeVariable(this,e,t,n)}}function Ct(){return _e("Tensor",(()=>Mt))}Object.defineProperty(Mt,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Ct();class Ft extends Mt{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(!re(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Dt().disposeTensor(this),this.dataId=e.dataId,Dt().incRef(this,null)}dispose(){Dt().disposeVariable(this),this.isDisposedInternal=!0}}var Rt,zt,Vt,Lt,Bt;Object.defineProperty(Ft,Symbol.hasInstance,{value:e=>e instanceof Mt&&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"}(Rt||(Rt={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(zt||(zt={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Vt||(Vt={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Lt||(Lt={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Bt||(Bt={}));const Pt={float32:Lt,int32:zt,bool:Vt,complex64:Bt};function Kt(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function qt(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Ut(e,t){if(e.dtype===t.dtype)return[e,t];const n=function(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Pt[e][t]}(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function jt(e){const t=[];return Wt(e,t,new Set),t}function Wt(e,t,n){if(null==e)return;if(e instanceof Mt)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),Wt(r,t,n))}}function Gt(e){return null!=e.kernelName}class Ht{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 Zt{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ht}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){Le(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 class{refCount(e){return X("refCount")}incRef(e){return X("incRef")}timerAvailable(){return!0}time(e){return X("time")}read(e){return X("read")}readSync(e){return X("readSync")}readToGPU(e,t){return X("readToGPU")}numDataIds(){return X("numDataIds")}disposeData(e,t){return X("disposeData")}write(e,t,n){return X("write")}move(e,t,n,r,s){return X("move")}createTensorFromGPUData(e,t,n){return X("createTensorFromGPUData")}memory(){return X("memory")}floatPrecision(){return X("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return X("dispose")}}||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.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 Zt.nextTensorId++}nextVariableId(){return Zt.nextVariableId++}clone(e){const t=Qt.runKernel(Ie,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return Qt.runKernel(Ee,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=ze(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],o=r-t-s-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let o,i;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Gt(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Gt(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const u=ze(t,this.backendName);J(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:s,attrs:a,backend:this.backend});const o=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const p=o.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,s,p);n=this.saveTensorsForBackwardMode(e)}return p}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy((()=>t(this.backend,s)));const n=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:p,attrs:l}=e,c=Gt(e)?null:e.backwardsFunc;let h;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(u,p,(()=>o())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()})),r&&this.addTapeNode(u,p,t,c,n,l),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(p).map((e=>null!=p[e]?p[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=Ve(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(J(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 o=n.filter(((e,t)=>s[t]));return a.concat(o)}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&&pe(e[0])&&(s=e.map((e=>function(e,t="utf-8"){return t=t||"utf-8",ke().platform.encode(e,t)}(e))));const a=r.write(s,t,n),o=new Mt(t,n,a,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(a),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}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 Mt(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 Ft(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*ue(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 Ft||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*ue(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>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,a){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},i=Ve(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=ye(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(o)}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=jt(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(J(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)));J(s instanceof Mt,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const r={},s={};for(let e=0;er[e.id]=!0)),i=!0,s[a.id]=!0;break}if(i)break}}const a={};a[n.id]=!0;const o={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e0)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=fe(ne(e),"float32");return Qt.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],o=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const i=a.gradient(o);for(const t in a.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const s=n((()=>i[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 o=a.inputs[t];if(!re(s.shape,o.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 '${o.shape}'`);if(null==e[o.id])e[o.id]=s;else{const t=e[o.id];e[o.id]=r(t,s),t.dispose()}}}}(e,a,(e=>this.tidy(e)),Yt);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 J(ce(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;J(t.every((e=>e instanceof Mt)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};t.forEach(((e,t)=>{r[t]=e}));return this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),J(n.value instanceof Mt,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),J(ce(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];J(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(...).")),J(a.every((e=>e instanceof Mt)),(()=>"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 o={};return a.forEach(((e,t)=>{o[t]=()=>e})),o},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=bt(),n=await this.backend.time(e);return n.wallMs=bt()-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 Ht;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}}Zt.nextTensorId=0,Zt.nextVariableId=0;const Qt=function(){const e=Se();if(null==e._tfengine){const t=new Ne(e);e._tfengine=new Zt(t)}var t;return t=e._tfengine.ENV,ve=t,Dt=()=>e._tfengine,e._tfengine}();function Yt(e,t){const n={a:e,b:t};return Qt.runKernel("Add",n)}function Xt(e,t){let n=e;if(Nt(e))return"string"===t?[]:[e.length];if(Kt(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(qt(e))return[e.buffer.size/(null==t?4:ue(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Nt(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&ke().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Jt(e,r,[]),r}function Jt(e,t,n){if(n=n||[],!Array.isArray(e)&&!Nt(e))return void J(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));J(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),J(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=0&&(s=r),en(r,s,t,n),null==e||!Nt(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=Xt(e,s);Nt(e)||Array.isArray(e)||(e=[e]);const o="string"!==s?gt(e,s):wt(e,[],!0);return Qt.makeTensor(o,a,s)}function nn(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)=>tn(e,`${t}[${s}]`,n,r)))}const rn="__op";function sn(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+=rn;const s=(...e)=>{Qt.startScope(n);try{const t=r(...e);return be(t)&&console.error("Cannot return a Promise inside of tidy."),Qt.endScope(t),t}catch(e){throw Qt.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const an=sn({abs_:function(e){const t=tn(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Qt.runKernel("ComplexAbs",e)}{const e={x:t};return Qt.runKernel("Abs",e)}}});const on=sn({acos_:function(e){const t={x:tn(e,"x","acos")};return Qt.runKernel("Acos",t)}});const un=sn({acosh_:function(e){const t={x:tn(e,"x","acosh")};return Qt.runKernel("Acosh",t)}});const pn=sn({add_:function(e,t){let n=tn(e,"a","add"),r=tn(t,"b","add");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Add",s)}});const ln=sn({addN_:function(e){J(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),J(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>tn(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(!re(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return Qt.runKernel("AddN",r)}});const cn=sn({all_:function(e,t=null,n=!1){const r={x:tn(e,"x","all","bool")},s={axis:t,keepDims:n};return Qt.runKernel("All",r,s)}});const hn=sn({any_:function(e,t=null,n=!1){const r={x:tn(e,"x","any","bool")},s={axis:t,keepDims:n};return Qt.runKernel("Any",r,s)}});const dn=sn({argMax_:function(e,t=0){const n={x:tn(e,"x","argMax")},r={axis:t};return Qt.runKernel("ArgMax",n,r)}});const mn=sn({argMin_:function(e,t=0){const n={x:tn(e,"x","argMin")},r={axis:t};return Qt.runKernel("ArgMin",n,r)}});const fn=sn({asin_:function(e){const t={x:tn(e,"x","asin")};return Qt.runKernel("Asin",t)}});const yn=sn({asinh_:function(e){const t={x:tn(e,"x","asinh")};return Qt.runKernel("Asinh",t)}});const gn=sn({atan_:function(e){const t={x:tn(e,"x","atan")};return Qt.runKernel("Atan",t)}});const bn=sn({atan2_:function(e,t){let n=tn(e,"a","atan2"),r=tn(t,"b","atan2");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Atan2",s)}});const xn=sn({atanh_:function(e){const t={x:tn(e,"x","atanh")};return Qt.runKernel("Atanh",t)}});const Nn=sn({cast_:function(e,t){const n=tn(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(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 Qt.runKernel(Ee,r,s)}});function wn(e,t,n,r,s,a,o=!1,i="channelsLast"){let[u,p,l,c]=[-1,-1,-1,-1];if("channelsLast"===i)[u,p,l,c]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,c,p,l]=e}const[h,d,,m]=t,[f,y]=kn(n),[g,b]=kn(r),x=Tn(h,g),N=Tn(d,b),{padInfo:w,outHeight:k,outWidth:T}=function(e,t,n,r,s,a,o,i,u){let p,l,c;if("number"==typeof e){p={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=function(e,t,n,r=1){const s=Tn(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}(e,t,n));const a=e[0],o=e[1],i=vn((a-t+2*r)/n+1,s),u=vn((o-t+2*r)/n+1,s);return[i,u]}([t,n],a,r,e,i);l=s[0],c=s[1]}else if("same"===e){l=Math.ceil(t/r),c=Math.ceil(n/s);const e=Math.max(0,(l-1)*r+a-t),i=Math.max(0,(c-1)*s+o-n),u=Math.floor(e/2),h=e-u,d=Math.floor(i/2);p={top:u,bottom:h,left:d,right:i-d,type:"SAME"}}else if("valid"===e)p={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-a+1)/r),c=Math.ceil((n-o+1)/s);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const h="channelsLast"===u?e[1][0]:e[2][0],d="channelsLast"===u?e[1][1]:e[2][1],m="channelsLast"===u?e[2][0]:e[3][0],f="channelsLast"===u?e[2][1]:e[3][1];p={top:h,bottom:d,left:m,right:f,type:0===h&&0===d&&0===m&&0===f?"VALID":"EXPLICIT"},l=vn((t-a+h+d)/r+1,i),c=vn((n-o+m+f)/s+1,i)}}return{padInfo:p,outHeight:l,outWidth:c}}(s,p,l,f,y,x,N,a,i),v=o?m*c:m;let S;return"channelsFirst"===i?S=[u,v,k,T]:"channelsLast"===i&&(S=[u,k,T,v]),{batchSize:u,dataFormat:i,inHeight:p,inWidth:l,inChannels:c,outHeight:k,outWidth:T,outChannels:v,padInfo:w,strideHeight:f,strideWidth:y,filterHeight:h,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:N,dilationHeight:g,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function kn(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Tn(e,t){return t<=1?e:e+(e-1)*(t-1)}function vn(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 Sn(e){const[t,n,r]=kn(e);return 1===t&&1===n&&1===r}function _n(e,t){return Sn(e)||Sn(t)}function En(e){return kn(e).every((e=>e>0))}function In(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)J(se(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=>{J(se(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const $n=sn({reshape_:function(e,t){const n={x:tn(e,"x","reshape","string_or_numeric")},r={shape:t};return Qt.runKernel("Reshape",n,r)}});const An=sn({avgPool_:function(e,t,n,r,s){const a=tn(e,"x","avgPool","float32");J(_n(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let o=a,i=!1;3===a.rank&&(i=!0,o=$n(a,[1,a.shape[0],a.shape[1],a.shape[2]])),J(4===o.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`)),In("avgPool",r,s);const u={x:o},p={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let l=Qt.runKernel("AvgPool",u,p);return l=Nn(l,a.dtype),i?$n(l,[l.shape[1],l.shape[2],l.shape[3]]):l}});const Dn=sn({avgPool3d_:function(e,t,n,r,s,a="NDHWC"){const o=tn(e,"x","avgPool3d","float32");let i=o,u=!1;4===o.rank&&(u=!0,i=$n(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),J(5===i.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`)),J("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),J("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}'`)),In("avgPool3d",r,s);const p={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a};let c=Qt.runKernel("AvgPool3D",p,l);return c=Nn(c,i.dtype),u?$n(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}});const On=sn({clone_:function(e){const t={x:tn(e,"x","clone","string_or_numeric")};return Qt.runKernel(Ie,t)}});const Mn=sn({concat_:function(e,t=0){J(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=nn(e,"tensors","concat","string_or_numeric");if("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 On(n[0]);const r=n,s={axis:t};return Qt.runKernel("Concat",r,s)}});const Cn=sn({matMul_:function(e,t,n=!1,r=!1){let s=tn(e,"a","matMul"),a=tn(t,"b","matMul");[s,a]=Ut(s,a);const o={a:s,b:a},i={transposeA:n,transposeB:r};return Qt.runKernel("BatchMatMul",o,i)}});const Fn=sn({mul_:function(e,t){let n=tn(e,"a","mul"),r=tn(t,"b","mul");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Multiply",s)}});const Rn=sn({sigmoid_:function(e){const t={x:tn(e,"x","sigmoid","float32")};return Qt.runKernel("Sigmoid",t)}});const zn=sn({slice_:function(e,t,n){const r=tn(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 Qt.runKernel("Slice",s,a)}});const Vn=sn({tanh_:function(e){const t={x:tn(e,"x","tanh","float32")};return Qt.runKernel("Tanh",t)}});const Ln=sn({basicLSTMCell_:function(e,t,n,r,s,a){const o=tn(e,"forgetBias","basicLSTMCell"),i=tn(t,"lstmKernel","basicLSTMCell"),u=tn(n,"lstmBias","basicLSTMCell"),p=tn(r,"data","basicLSTMCell"),l=tn(s,"c","basicLSTMCell"),c=tn(a,"h","basicLSTMCell"),h=Mn([p,c],1),d=Cn(h,i),m=pn(d,u),f=m.shape[0],y=m.shape[1]/4,g=[f,y],b=zn(m,[0,0],g),x=zn(m,[0,y],g),N=zn(m,[0,2*y],g),w=zn(m,[0,3*y],g),k=pn(Fn(Rn(b),Vn(x)),Fn(l,Rn(pn(o,N))));return[k,Fn(Vn(k),Rn(w))]}});const Bn=sn({batchToSpaceND_:function(e,t,n){const r=tn(e,"x","batchToSpaceND"),s=t.reduce(((e,t)=>e*t));J(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),J(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),J(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},o={blockShape:t,crops:n};return Qt.runKernel("BatchToSpaceND",a,o)}});const Pn=sn({batchNorm_:function(e,t,n,r,s,a){null==a&&(a=.001);const o=tn(e,"x","batchNorm"),i=tn(t,"mean","batchNorm"),u=tn(n,"variance","batchNorm");let p,l;null!=s&&(p=tn(s,"scale","batchNorm")),null!=r&&(l=tn(r,"offset","batchNorm")),J(i.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),J(null==l||i.rank===l.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),J(null==p||i.rank===p.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const c=function(e){let t;return t=0===e.rank||1===e.rank?$n(e,[1,1,1,e.size]):2===e.rank?$n(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?$n(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),h={x:c,scale:p,offset:l,mean:i,variance:u},d={varianceEpsilon:a},m=Qt.runKernel("FusedBatchNorm",h,d);return $n(m,o.shape)}});const Kn=sn({batchNorm2d_:function(e,t,n,r,s,a){const o=tn(e,"x","batchNorm"),i=tn(t,"mean","batchNorm"),u=tn(n,"variance","batchNorm");let p,l;return null!=s&&(p=tn(s,"scale","batchNorm")),null!=r&&(l=tn(r,"offset","batchNorm")),J(2===o.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`)),J(2===i.rank||1===i.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`)),J(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=p&&J(2===p.rank||1===p.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`)),null!=l&&J(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`)),Pn(o,i,u,l,p,a)}});const qn=sn({batchNorm3d_:function(e,t,n,r,s,a){const o=tn(e,"x","batchNorm"),i=tn(t,"mean","batchNorm"),u=tn(n,"variance","batchNorm");let p,l;return null!=s&&(p=tn(s,"scale","batchNorm")),null!=r&&(l=tn(r,"offset","batchNorm")),J(3===o.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`)),J(3===i.rank||1===i.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`)),J(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=p&&J(3===p.rank||1===p.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`)),null!=l&&J(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`)),Pn(o,i,u,l,p,a)}});const Un=sn({batchNorm4d_:function(e,t,n,r,s,a){const o=tn(e,"x","batchNorm"),i=tn(t,"mean","batchNorm"),u=tn(n,"variance","batchNorm");let p,l;return null!=s&&(p=tn(s,"scale","batchNorm")),null!=r&&(l=tn(r,"offset","batchNorm")),J(4===o.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`)),J(4===i.rank||1===i.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`)),J(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=p&&J(4===p.rank||1===p.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`)),null!=l&&J(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${l.rank}.`)),Pn(o,i,u,l,p,a)}});const jn=sn({bincount_:function(e,t,n){const r=tn(e,"x","bincount"),s=tn(t,"weights","bincount");J("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),J(n>=0,(()=>`size must be non-negative, but got ${n}.`)),J(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},o={size:n};return Qt.runKernel("Bincount",a,o)}});const Wn=sn({bitwiseAnd_:function(e,t){const n=tn(e,"x","bitwiseAnd"),r=tn(t,"y","bitwiseAnd");if(!re(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 Qt.runKernel("BitwiseAnd",s)}});const Gn=sn({broadcastArgs_:function(e,t){const n=tn(e,"s0","broadcastArgs","int32"),r=tn(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 Qt.runKernel("BroadcastArgs",s)}});const Hn=sn({broadcastTo_:function(e,t){let n=tn(e,"broadcastTo","x");const r=n.shape;if(ge(t),t.lengthn.rank){const e=n.shape.slice();for(;e.length=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 On(n);const o={x:n},i={reps:a};return Qt.runKernel($e,o,i)}});function Zn(e,t="float32",n){return t=t||"float32",ge(e),new At(e,t,n)}const Qn=sn({ceil_:function(e){const t={x:tn(e,"x","ceil","float32")};return Qt.runKernel("Ceil",t)}});function Yn(e,t,n){ge(e);const r={shape:e,value:t,dtype:n=n||le(t)};return Qt.runKernel("Fill",{},r)}const Xn=sn({clipByValue_:function(e,t,n){const r=tn(e,"x","clipByValue");if(J(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Yn(r.shape,t,r.dtype);const s={x:r},a={clipValueMin:t,clipValueMax:n};return Qt.runKernel("ClipByValue",s,a)}});const Jn=sn({complex_:function(e,t){const n=tn(e,"real","complex"),r=tn(t,"imag","complex");ee(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 Qt.runKernel("Complex",s)}});const er=sn({concat1d_:function(e){return Mn(e,0)}});const tr=sn({concat2d_:function(e,t){return Mn(e,t)}});const nr=sn({concat3d_:function(e,t){return Mn(e,t)}});const rr=sn({concat4d_:function(e,t){return Mn(e,t)}});const sr=sn({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],o){const i=tn(e,"x","conv2d","float32"),u=tn(t,"filter","conv2d","float32");let p=i,l=!1;3===i.rank&&(l=!0,p=$n(i,[1,i.shape[0],i.shape[1],i.shape[2]])),J(4===p.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`)),J(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),In("conv2d",r,o);const c="NHWC"===s?p.shape[3]:p.shape[1];J(c===u.shape[2],(()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${u.shape[2]}.`)),J(_n(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),J(En(a),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),J(En(n),(()=>"Error in conv2D: Strides should be larger than 0."));const h={x:p,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},m=Qt.runKernel("Conv2D",h,d);return l?$n(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const ar=sn({conv1d_:function(e,t,n,r,s="NWC",a=1,o){const i=tn(e,"x","conv1d"),u=tn(t,"filter","conv1d");let p=i,l=!1;2===i.rank&&(l=!0,p=$n(i,[1,i.shape[0],i.shape[1]])),J(3===p.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`)),J(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),In("conv1d",r,o),J(p.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),J(_n(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),J(En(a),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),J(En(n),(()=>"Error in conv1D: Stride should be larger than 0.")),J("NWC"===s,(()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`));const c=$n(u,[1,u.shape[0],u.shape[1],u.shape[2]]),h=$n(p,[p.shape[0],1,p.shape[1],p.shape[2]]),d=sr(h,c,[1,n],r,"NHWC",[1,a],o);return $n(d,l?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}});const or=sn({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",o){J(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let i=e,u=t,p=!1;3===t.rank&&(p=!0,u=$n(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),J(4===i.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`)),J(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),J(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const l="NHWC"===a?i[3]:i[1],c="NHWC"===a?u.shape[3]:u.shape[1];J(l===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[2]}.`)),J(c===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[3]}.`)),In("conv2dDerInput",s,o);const h={dy:u,filter:n},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,inputShape:i},m=Qt.runKernel("Conv2DBackpropInput",h,d);return p?$n(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const ir=sn({conv2dTranspose_:function(e,t,n,r,s,a){const o=tn(e,"x","conv2dTranspose"),i=tn(t,"filter","conv2dTranspose");return or(n,o,i,r,s,"NHWC",a)}});const ur=sn({conv3d_:function(e,t,n,r,s="NDHWC",a=[1,1,1]){const o=tn(e,"x","conv3d"),i=tn(t,"filter","conv3d");let u=o,p=!1;4===o.rank&&(p=!0,u=$n(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),J(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),J(5===i.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`)),J(u.shape[4]===i.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${i.shape[3]}.`)),J(_n(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),J("NDHWC"===s,(()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`)),J(En(a),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),J(En(n),(()=>"Error in conv3D: Strides should be larger than 0."));const l={x:u,filter:i},c={strides:n,pad:r,dataFormat:s,dilations:a},h=Qt.runKernel("Conv3D",l,c);return p?$n(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const pr=sn({conv3DBackpropInput_:function(e,t,n,r,s){J(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let a=e,o=t,i=!1;4===t.rank&&(i=!0,o=$n(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],p=o.shape[4];J(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),J(5===o.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`)),J(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),J(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),J(p===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`));const l={dy:o,filter:n},c={pad:s,strides:r,inputShape:a},h=Qt.runKernel("Conv3DBackpropInputV2",l,c);return i?$n(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const lr=sn({conv3dTranspose_:function(e,t,n,r,s){const a=tn(e,"x","conv3dTranspose"),o=tn(t,"filter","conv3dTranspose");return pr(n,a,o,r,s)}});const cr=sn({cos_:function(e){const t={x:tn(e,"x","cos","float32")};return Qt.runKernel("Cos",t)}});const hr=sn({cosh_:function(e){const t={x:tn(e,"x","cosh","float32")};return Qt.runKernel("Cosh",t)}});const dr=sn({cumprod_:function(e,t=0,n=!1,r=!1){const s={x:tn(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:r};return Qt.runKernel("Cumprod",s,a)}});const mr=sn({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:tn(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:r};return Qt.runKernel("Cumsum",s,a)}});const fr=sn({denseBincount_:function(e,t,n,r=!1){const s=tn(e,"x","denseBincount"),a=tn(t,"weights","denseBincount");J("int32"===s.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`)),J(s.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`)),J(n>=0,(()=>`size must be non-negative, but got ${n}.`)),J(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 o={x:s,weights:a},i={size:n,binaryOutput:r};return Qt.runKernel("DenseBincount",o,i)}});const yr=sn({depthToSpace_:function(e,t,n="NHWC"){const r=tn(e,"x","depthToSpace","float32"),s="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];J(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),J(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),J(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),J(o%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`));const i={x:r},u={blockSize:t,dataFormat:n};return Qt.runKernel("DepthToSpace",i,u)}});const gr=sn({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],o){const i=tn(e,"x","depthwiseConv2d","float32"),u=tn(t,"filter","depthwiseConv2d","float32");let p=i,l=!1;3===i.rank&&(l=!0,p=$n(i,[1,i.shape[0],i.shape[1],i.shape[2]])),J(4===p.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`)),J(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const c="NHWC"===s?p.shape[3]:p.shape[1];J(c===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${c}) must match the inChannels dimension in filter ${u.shape[2]}.`)),In("depthwiseConv2d",r,o);const h={x:p,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},m=Qt.runKernel("DepthwiseConv2dNative",h,d);return l?$n(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const br=sn({diag_:function(e){const t={x:tn(e,"x","diag")};return Qt.runKernel("Diag",t)}});const xr=sn({dilation2d_:function(e,t,n,r,s=[1,1],a="NHWC"){const o=tn(e,"x","dilation2d"),i=tn(t,"filter","dilation2d");J(3===o.rank||4===o.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`)),J(3===i.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`)),J("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let u=o,p=!1;3===o.rank&&(u=$n(o,[1,o.shape[0],o.shape[1],o.shape[2]]),p=!0),J(u.shape[3]===i.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${i.shape[2]}`));const l={x:u,filter:i},c={strides:n,pad:r,dilations:s},h=Qt.runKernel("Dilation2D",l,c);return p?$n(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Nr=sn({floorDiv_:function(e,t){let n=tn(e,"a","floorDiv"),r=tn(t,"b","floorDiv");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("FloorDiv",s)}});const wr=sn({div_:function(e,t){let n=tn(e,"a","div"),r=tn(t,"b","div");if([n,r]=Ut(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Nr(n,r);const s={a:n,b:r};return Qt.runKernel("RealDiv",s,{})}});function kr(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let s=0;s`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(J(s===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`)),1===n.rank&&1===r.rank){const e=$n(n,[1,-1]),t=$n(r,[-1,1]),s=Cn(e,t);return $n(s,[])}if(1===n.rank&&2===r.rank){const e=$n(n,[1,-1]),t=$n(r,[r.shape[0],r.shape[1]]),s=Cn(e,t);return $n(s,[s.size])}if(2===n.rank&&1===r.rank){const e=$n(r,[-1,1]),t=Cn(n,e);return $n(t,[t.size])}{const e=$n(r,[r.shape[0],r.shape[1]]);return Cn(n,e)}}});const Ir=sn({einsum_:function(e,...t){const n=t.map(((e,t)=>tn(e,`tensors${t}`,"einsum"))),r={equation:e};return Qt.runKernel("Einsum",n,r)}});const $r=sn({elu_:function(e){const t={x:tn(e,"x","elu","float32")};return Qt.runKernel("Elu",t)}});const Ar=sn({ensureShape_:function(e,t){const n=tn(e,"x","ensureShape","string_or_numeric");if(!function(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"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Nn(t,"float32"));const n={x:t};return Qt.runKernel("Erf",n)}});function Or(e,t){return function(e,t,n){const r=e.length+t.length,s=[];let a=0,o=0;for(let i=0;i1)),t)}const Mr=sn({max_:function(e,t=null,n=!1){const r={x:tn(e,"x","max")},s={reductionIndices:t,keepDims:n};return Qt.runKernel("Max",r,s)}});const Cr=sn({min_:function(e,t=null,n=!1){const r={x:tn(e,"x","min")},s={axis:t,keepDims:n};return Qt.runKernel("Min",r,s)}});const Fr=sn({pow_:function(e,t){let n=tn(e,"base","pow"),r=tn(t,"exp","pow");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Pow",s)}});function Rr(e,t,n,r){if(null==r)r=le(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(qt(e)||Kt(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 Qt.backend.createTensorFromGPUData(e,t||n,r)}if(!Nt(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){ge(t);const e=ne(t),r=ne(n);J(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Nt(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?gt(e,r):wt(e,[],!0),Qt.makeTensor(e,t,r)}function zr(e,t){if((Nt(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&&Nt(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Rr(e,[],[],t)}const Vr=sn({sqrt_:function(e){const t={x:tn(e,"x","sqrt","float32")};return Qt.runKernel("Sqrt",t)}});const Lr=sn({square_:function(e){const t=tn(e,"x","square");return Qt.runKernel("Square",{x:t},{})}});const Br=sn({sum_:function(e,t=null,n=!1){let r=tn(e,"x","sum");"bool"===r.dtype&&(r=Nn(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Qt.runKernel("Sum",s,a)}});function Pr(e,t,n=null){if(0===e.rank)return an(e);if(1!==e.rank&&null===n)return Pr($n(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Br(an(e),n);if(t===1/0)return Mr(an(e),n);if(t===-1/0)return Cr(an(e),n);if("euclidean"===t||2===t)return Vr(Br(Fr(an(e),zr(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Mr(Br(an(e),n[0]),n[1]-1);if(t===1/0)return Mr(Br(an(e),n[1]),n[0]);if(t===-1/0)return Cr(Br(an(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Vr(Br(Lr(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Kr=sn({norm_:function(e,t="euclidean",n=null,r=!1){const s=Pr(e=tn(e,"x","norm"),t,n);let a=s.shape;if(r){const t=oe(n,e.shape);a=Or(s.shape,t)}return $n(s,a)}});const qr=sn({euclideanNorm_:function(e,t=null,n=!1){return Kr(e,"euclidean",t,n)}});const Ur=sn({exp_:function(e){const t={x:tn(e,"x","exp")};return Qt.runKernel("Exp",t)}});const jr=sn({expandDims_:function(e,t=0){const n=tn(e,"x","expandDims","string_or_numeric");J(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},s={dim:t};return Qt.runKernel("ExpandDims",r,s)}});const Wr=sn({expm1_:function(e){const t={x:tn(e,"x","expm1")};return Qt.runKernel("Expm1",t)}});const Gr=sn({tile_:function(e,t){const n=tn(e,"x","tile","string_or_numeric");J(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 Qt.runKernel($e,r,s)}});const Hr=sn({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=Zn([e,t],r),a=e<=t?e:t;for(let e=0;e`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`)),J(se(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let o=a,i=!1;3===a.rank&&(i=!0,o=$n(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={x:o},p={depthRadius:t,bias:n,alpha:r,beta:s},l=Qt.runKernel("LRN",u,p);return i?$n(l,[l.shape[1],l.shape[2],l.shape[3]]):l}});const is=sn({log_:function(e){const t={x:tn(e,"x","log","float32")};return Qt.runKernel("Log",t)}});const us=sn({log1p_:function(e){const t={x:tn(e,"x","log1p")};return Qt.runKernel("Log1p",t)}});function ps(e){return Qt.customGrad(e)}const ls=sn({neg_:function(e){const t={x:tn(e,"x","neg")};return Qt.runKernel("Neg",t)}});const cs=sn({softplus_:function(e){const t={x:tn(e,"x","softplus")};return Qt.runKernel("Softplus",t)}});const hs=sn({logSigmoid_:function(e){const t=tn(e,"x","logSigmoid"),n=ps((e=>({value:ls(cs(ls(e))),gradFunc:t=>Fn(t,Rn(ls(e)))})));return n(t)}});const ds=sn({sub_:function(e,t){let n=tn(e,"a","sub"),r=tn(t,"b","sub");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Sub",s)}});const ms=sn({logSoftmax_:function(e,t=-1){const n=tn(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} and axis was ${t}`);const r=ps(((e,n)=>{const r=Mr(e,t,!0),s=ds(e,r),a=ds(Nn(s,"float32"),is(Br(Ur(s),t,!0)));n([a]);return{value:a,gradFunc:(e,n)=>{const[r]=n,s=Ur(r);return ds(e,Fn(Br(e,t,!0),s))}}}));return r(n)}});const fs=sn({logSumExp_:function(e,t=null,n=!1){const r=tn(e,"x","logSumExp"),s=oe(t,r.shape),a=Mr(r,s,!0),o=ds(r,a),i=Ur(o),u=Br(i,s),p=is(u),l=pn($n(a,p.shape),p);if(n){const e=Or(l.shape,s);return $n(l,e)}return l}});const ys=sn({logicalAnd_:function(e,t){const n=tn(e,"a","logicalAnd","bool"),r=tn(t,"b","logicalAnd","bool");kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("LogicalAnd",s)}});const gs=sn({logicalNot_:function(e){const t={x:tn(e,"x","logicalNot","bool")};return Qt.runKernel("LogicalNot",t)}});const bs=sn({logicalOr_:function(e,t){const n=tn(e,"a","logicalOr","bool"),r=tn(t,"b","logicalOr","bool");kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("LogicalOr",s)}});const xs=sn({logicalXor_:function(e,t){const n=tn(e,"a","logicalXor","bool"),r=tn(t,"b","logicalXor","bool");return kr(n.shape,r.shape),ys(bs(e,t),gs(ys(e,t)))}}),Ns=2147483648;const ws=sn({searchSorted_:function(e,t,n="left"){const r=tn(e,"sortedSequence","searchSorted"),s=tn(t,"values","searchSorted"),a=r.shape[r.shape.length-1],o=s.shape[s.shape.length-1],i=$n(r,[-1,a]),u=$n(s,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(ne(u.shape)>=Ns)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=Ns)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const p={sortedSequence:i,values:u},l={side:n};return Qt.runKernel("SearchSorted",p,l)}});const ks=sn({maxPool_:function(e,t,n,r,s){const a=tn(e,"x","maxPool");let o=a,i=!1;3===a.rank&&(i=!0,o=$n(a,[1,a.shape[0],a.shape[1],a.shape[2]])),J(4===o.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`)),J(_n(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),In("maxPool",r,s);const u={x:o},p={filterSize:t,strides:n,pad:r,dimRoundingMode:s},l=Qt.runKernel("MaxPool",u,p);return i?$n(l,[l.shape[1],l.shape[2],l.shape[3]]):l}});const Ts=sn({maxPool3d_:function(e,t=[1,1,1],n,r,s,a="NDHWC"){const o=tn(e,"x","maxPool3d");let i=o,u=!1;4===o.rank&&(u=!0,i=$n(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),J(5===i.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`)),J("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),In("maxPool3d",r,s);const p={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},c=Qt.runKernel("MaxPool3D",p,l);return u?$n(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}});const vs=sn({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const a={x:tn(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},i=Qt.runKernel("MaxPoolWithArgmax",a,o);return{result:i[0],indexes:i[1]}}});const Ss=sn({maximum_:function(e,t){let n=tn(e,"a","maximum"),r=tn(t,"b","maximum");[n,r]=Ut(n,r),"bool"===n.dtype&&(n=Nn(n,"int32"),r=Nn(r,"int32")),kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("Maximum",s)}});const _s=sn({mean_:function(e,t=null,n=!1){const r={x:tn(e,"x","mean")},s={axis:t,keepDims:n};return Qt.runKernel("Mean",r,s)}});function Es(e,t="float32"){if(ge(e),"complex64"===t){const t=Es(e,"float32"),n=Es(e,"float32");return Jn(t,n)}const n=ye(ne(e),t);return Qt.makeTensor(n,e,t)}function Is(e,t="float32"){if(ge(e),"complex64"===t){const t=Is(e,"float32"),n=Es(e,"float32");return Jn(t,n)}const n=fe(ne(e),t);return Qt.makeTensor(n,e,t)}const $s=sn({minimum_:function(e,t){let n=tn(e,"a","minimum"),r=tn(t,"b","minimum");[n,r]=Ut(n,r),"bool"===n.dtype&&(n=Nn(n,"int32"),r=Nn(r,"int32")),kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("Minimum",s)}});const As=sn({mirrorPad_:function(e,t,n){J("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=tn(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");J(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"Invalid number of paddings. Must be length of 2 each.")),J(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},o={x:r};return Qt.runKernel("MirrorPad",o,a)}});const Ds=sn({mod_:function(e,t){let n=tn(e,"a","mod"),r=tn(t,"b","mod");[n,r]=Ut(n,r);const s={a:n,b:r};return Qt.runKernel("Mod",s)}});const Os=sn({moments_:function(e,t=null,n=!1){const r=oe(t,(e=tn(e,"x","moments")).shape),s=_s(e,r,n);let a=s.shape;n||(a=Or(s.shape,r));const o=Lr(ds(Nn(e,"float32"),$n(s,a)));return{mean:s,variance:_s(o,r,n)}}});const Ms=sn({multiRNNCell_:function(e,t,n,r){const s=tn(t,"data","multiRNNCell"),a=nn(n,"c","multiRNNCell"),o=nn(r,"h","multiRNNCell");let i=s;const u=[];for(let t=0;t2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?$n(s,[1,-1]):s},u={numSamples:t,seed:n,normalized:r},p=Qt.runKernel("Multinomial",i,u);return 1===o?$n(p,[p.size]):p}});const Fs=sn({notEqual_:function(e,t){let n=tn(e,"a","notEqual","string_or_numeric"),r=tn(t,"b","notEqual","string_or_numeric");[n,r]=Ut(n,r),kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("NotEqual",s)}});const Rs=sn({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:tn(e,"indices","oneHot","int32")},o={dtype:s,depth:t,onValue:n,offValue:r};return Qt.runKernel("OneHot",a,o)}});const zs=sn({onesLike_:function(e){const t={x:tn(e,"x","onesLike")};return Qt.runKernel("OnesLike",t)}});const Vs=sn({outerProduct_:function(e,t){const n=tn(e,"v1","outerProduct"),r=tn(t,"v2","outerProduct");J(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const s=$n(n,[-1,1]),a=$n(r,[1,-1]);return Cn(s,a)}});const Ls=sn({pad_:function(e,t,n=0){const r=tn(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 Qt.runKernel("PadV2",a,s)}});const Bs=sn({pad1d_:function(e,t,n=0){return J(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Ls(e,[t],n)}});const Ps=sn({pad2d_:function(e,t,n=0){return J(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Ls(e,t,n)}});const Ks=sn({pad3d_:function(e,t,n=0){return J(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.")),Ls(e,t,n)}});const qs=sn({pad4d_:function(e,t,n=0){return J(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.")),Ls(e,t,n)}});const Us=sn({spaceToBatchND_:function(e,t,n){const r=tn(e,"x","spaceToBatchND");J(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),J(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),J(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 Qt.runKernel("SpaceToBatchND",s,a)}});const js=sn({pool_:function(e,t,n,r,s,a,o){null==s&&(s=[1,1]),null==a&&(a=1),0===r&&(r="valid");const i=tn(e,"x","maxPool");let u=i,p=!1;3===i.rank&&(p=!0,u=$n(i,[1,i.shape[0],i.shape[1],i.shape[2]])),J(_n(a,s),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`));const l=function(e,t,n,r,s,a,o="channelsLast"){const[i,u]=kn(t);let p;if("channelsLast"===o)p=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);p=[i,u,e[1],e[1]]}return wn(e,p,n,r,s,a,!1,o)}(u.shape,t,a,s,r),c=[l.dilationHeight,l.dilationWidth];let h;h="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]]))}([l.filterHeight,l.filterWidth],c):[[0,0],[0,0]];const d=1===c[0]&&1===c[1],[m,f]=function(e,t,n){const r=n.map((e=>e[0])),s=n.map((e=>e[1])),a=e.concat(r,s),o=t.map(((e,t)=>(e-a[t]%e)%e)),i=s.map(((e,t)=>e+o[t])),u=t.map(((e,t)=>[r[t],i[t]])),p=t.map(((e,t)=>[0,o[t]]));return[u,p]}([l.inHeight,l.inWidth],c,h),y=d?r:"valid",g=d?u:Us(u,c,m),b=("avg"===n?()=>An(g,t,a,y,o):()=>ks(g,t,a,y,o))(),x=d?b:Bn(b,c,f);return p?$n(x,[x.shape[1],x.shape[2],x.shape[3]]):x}});const Ws=sn({prelu_:function(e,t){const n={x:tn(e,"x","prelu"),alpha:tn(t,"alpha","prelu")};return Qt.runKernel("Prelu",n)}});const Gs=sn({prod_:function(e,t=null,n=!1){let r=tn(e,"x","prod");"bool"===r.dtype&&(r=Nn(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Qt.runKernel("Prod",s,a)}});const Hs=sn({raggedGather_:function(e,t,n,r){const s={paramsNestedSplits:e.map(((e,t)=>tn(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:tn(t,"paramsDenseValues","raggedGather"),indices:tn(n,"indices","raggedGather","int32")},a={outputRaggedRank:r},o=Qt.runKernel("RaggedGather",s,a);return{outputNestedSplits:o.slice(0,o.length-1),outputDenseValues:o[o.length-1]}}});const Zs=sn({raggedRange_:function(e,t,n){const r=tn(e,"starts","raggedRange"),s={starts:r,limits:tn(t,"limits","raggedRange",r.dtype),deltas:tn(n,"deltas","raggedRange",r.dtype)},a=Qt.runKernel("RaggedRange",s);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}});const Qs=sn({raggedTensorToTensor_:function(e,t,n,r,s){const a=tn(e,"shape","raggedTensorToTensor","int32"),o=tn(t,"values","raggedTensorToTensor"),i={shape:a,values:o,defaultValue:tn(n,"defaultValue","raggedTensorToTensor",o.dtype),rowPartitionTensors:r.map(((e,t)=>tn(e,`tensors${t}`,"raggedTensorToTensor","int32")))},u={rowPartitionTypes:s};return Qt.runKernel("RaggedTensorToTensor",i,u)}});const Ys=sn({rand_:function(e,t,n){ge(e);const r=ne(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>>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 s(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,a&&("object"==typeof a&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.alea=a}(0,e,!1)}(Xs);var Js=Xs.exports,ea={exports:{}};!function(e){!function(e,t,n){function r(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>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,a&&("object"==typeof a&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a}(0,e,!1)}(ea);var ta=ea.exports,na={exports:{}};!function(e){!function(e,t,n){function r(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>>4),t.next()}function s(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 a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,a&&("object"==typeof a&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a}(0,e,!1)}(na);var ra=na.exports,sa={exports:{}};!function(e){!function(e,t,n){function r(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;n0;--n)e.next()}(t,e)}function s(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,a&&(a.x&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a}(0,e,!1)}(sa);var aa=sa.exports,oa={exports:{}};!function(e){!function(e,t,n){function r(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,o,i=[],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>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,s=0==(n=i[127&a]^=r+o)?s+1:0);for(s>=128&&(i[127&(t&&t.length||0)]=-1),s=127,a=512;a>0;--a)r=i[s+34&127],n=i[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[s]=r^n;e.w=o,e.X=i,e.i=s}(t,e)}function s(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,a&&(a.X&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a}(0,e,!1)}(oa);var ia=oa.exports,ua={exports:{}};!function(e){!function(e,t,n){function r(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>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,a&&("object"==typeof a&&s(a,n),o.state=function(){return s(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a}(0,e,!1)}(ua);var pa=ua.exports,la={exports:{}},ca=Ke({__proto__:null,default:{}});!function(e){!function(t,n,r){var s,a=256,o=r.pow(a,6),i=r.pow(2,52),u=2*i,p=255;function l(e,p,l){var y=[],g=m(d((p=1==p?{entropy:!0}:p||{}).entropy?[e,f(n)]:null==e?function(){try{var e;return s&&(e=s.randomBytes)?e=e(a):(e=new Uint8Array(a),(t.crypto||t.msCrypto).getRandomValues(e)),f(e)}catch(e){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,f(n)]}}():e,3),y),b=new c(y),x=function(){for(var e=b.g(6),t=o,n=0;e=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,m(f(b.S),n),(p.pass||l||function(e,t,n,s){return s&&(s.S&&h(s,b),e.state=function(){return h(b,{})}),n?(r.random=e,t):e})(x,g,"global"in p?p.global:this==r,p.state)}function c(e){var t,n=e.length,r=this,s=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);s=1||0===a);const o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*s*o,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 wa{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=xa.alea(s.toString()),this.randn=new Na(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(),snull==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=xa.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Ta=sn({randomGamma_:function(e,t,n=1,r="float32",s){if(ge(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const a=new wa(t,n,r,s),o=Zn(e,r);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Ma(t,0)}});const Fa=sn({reverse2d_:function(e,t){const n=tn(e,"x","reverse");return J(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Ma(n,t)}});const Ra=sn({reverse3d_:function(e,t){const n=tn(e,"x","reverse");return J(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Ma(n,t)}});const za=sn({reverse4d_:function(e,t){const n=tn(e,"x","reverse");return J(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Ma(n,t)}});const Va=sn({round_:function(e){const t={x:tn(e,"x","round")};return Qt.runKernel("Round",t)}});const La=sn({rsqrt_:function(e){const t={x:tn(e,"x","rsqrt","float32")};return Qt.runKernel("Rsqrt",t)}});const Ba=sn({selu_:function(e){const t={x:tn(e,"x","selu")};return Qt.runKernel("Selu",t)}});const Pa=sn({separableConv2d_:function(e,t,n,r,s,a=[1,1],o="NHWC"){const i=tn(e,"x","separableConv2d"),u=tn(t,"depthwiseFilter","separableConv2d"),p=tn(n,"pointwiseFilter","separableConv2d");let l=i,c=!1;if(3===i.rank&&(c=!0,l=$n(i,[1,i.shape[0],i.shape[1],i.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");J(4===l.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`)),J(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),J(4===p.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),J(1===p.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`)),J(1===p.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`));const h=u.shape[2],d=u.shape[3];J(p.shape[2]===h*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*d}, but got ${p.shape[2]}.`));const m=gr(l,u,r,s,o,a),f=sr(m,p,1,"valid",o);return c?$n(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const Ka=async function(e,t){const n=tn(e,"x","setdiff1d"),r=tn(t,"y","setdiff1d");J(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),J(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),J(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const s=await n.data(),a=await r.data(),o=new Set(a);let i=0;for(let e=0;e`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),zn(r,[t],[n])}});const Ga=sn({slice2d_:function(e,t,n){const r=tn(e,"x","slice2d");return J(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),zn(r,t,n)}});const Ha=sn({slice3d_:function(e,t,n){const r=tn(e,"x","slice3d");return J(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),zn(r,t,n)}});const Za=sn({slice4d_:function(e,t,n){const r=tn(e,"x","slice4d");return J(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),zn(r,t,n)}});const Qa=sn({softmax_:function(e,t=-1){const n=tn(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 Qt.runKernel("Softmax",r,s)}});const Ya=sn({fft_:function(e){J("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Qt.runKernel("FFT",t)}});const Xa=sn({ifft_:function(e){J("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Qt.runKernel("IFFT",t)}});const Ja=sn({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=$n(e,[n,t]);r=Xa(s)}else{const s=[n,2*(t-1)],a=$n($a(e),[n,t]),o=$n(Jr(e),[n,t]),i=Ma(zn(a,[0,1],[n,t-2]),1),u=Fn(Ma(zn(o,[0,1],[n,t-2]),1),zr(-1)),p=Mn([a,i],1),l=Mn([o,u],1),c=$n(Jn(p,l),[s[0],s[1]]);r=Xa(c)}if(r=$a(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=$n(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const eo=sn({split_:function(e,t,n=0){const r={x:tn(e,"x","split")},s={numOrSizeSplits:t,axis:n};return Qt.runKernel("SplitV",r,s)}});const to=sn({rfft_:function(e,t){J("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&&t0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,s=zn(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=Mn([e,Es(r)],e.shape.length-1),n=t}else s=e;const a=Sr(s),o=$n(Jn(s,a),[r,n]),i=Ya(o),u=Math.floor(n/2)+1,p=$a(i),l=Jr(i),c=eo(p,[u,n-u],p.shape.length-1),h=eo(l,[u,n-u],l.shape.length-1),d=s.shape.slice();return d[s.shape.length-1]=u,$n(Jn(c[0],h[0]),d)}});const no=sn({squaredDifference_:function(e,t){let n=tn(e,"a","squaredDifference"),r=tn(t,"b","squaredDifference");[n,r]=Ut(n,r),kr(n.shape,r.shape);const s={a:n,b:r};return Qt.runKernel("SquaredDifference",s,{})}});const ro=sn({squeeze_:function(e,t){const n=tn(e,"x","squeeze","string_or_numeric");return $n(n,function(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||s?null:oe(t,e).sort();let o=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),r.push(t)),a[o]<=t&&o++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}(n.shape,t).newShape)}});const so=sn({stack_:function(e,t=0){const n=nn(e,"tensors","stack","string_or_numeric");J(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&J(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,s={axis:t};return Qt.runKernel("Pack",r,s)}});const ao=sn({step_:function(e,t=0){const n={x:tn(e,"x","step")},r={alpha:t};return Qt.runKernel("Step",n,r)}});const oo=sn({stridedSlice_:function(e,t,n,r,s=0,a=0,o=0,i=0,u=0){const p={x:tn(e,"x","stridedSlice","string_or_numeric")},l={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return Qt.runKernel("StridedSlice",p,l)}});const io=sn({tan_:function(e){const t={x:tn(e,"x","tan","float32")};return Qt.runKernel("Tan",t)}});function uo(e,t,n){return Rr(e,t,Xt(e,n),n)}function po(e,t){te(e);const n=Xt(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Rr(e,null,n,t)}function lo(e,t,n){if(te(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Xt(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 Rr(e,t,r,n)}function co(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}`)}!function(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= 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},o={k:t,sorted:n},[i,u]=Qt.runKernel("TopK",a,o);return{values:i,indices:u}}});const fo=sn({truncatedNormal_:function(e,t=0,n=1,r,s){if(ge(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const a=new Na(t,n,r,!0,s),o=Zn(e,r);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const r={x:n},s={axis:t},[a,o]=Qt.runKernel("Unique",r,s);return{values:a,indices:o}}});const go=sn({unsortedSegmentSum_:function(e,t,n){const r=tn(e,"x","unsortedSegmentSum"),s=tn(t,"segmentIds","unsortedSegmentSum","int32");J(se(n),(()=>"numSegments must be of dtype int"));const a={x:r,segmentIds:s},o={numSegments:n};return Qt.runKernel("UnsortedSegmentSum",a,o)}});const bo=sn({unstack_:function(e,t=0){const n=tn(e,"x","unstack","string_or_numeric");J(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},s={axis:t};return Qt.runKernel("Unpack",r,s)}});const xo=async function(e){const t=tn(e,"condition","whereAsync","bool"),n=await t.data(),r=function(e,t){const n=[];for(let e=0;e0,(()=>"mask cannot be scalar")),ee(i.slice(a,a+o),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let e=a;et)).reverse()),J(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{J(e>=0&&e"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?(o=()=>{let e=$a(r),t=Jr(r);return e=Qt.runKernel(Ae,{x:e},a),t=Qt.runKernel(Ae,{x:t},a),n&&(t=ls(t)),Jn(e,t)},Qt.tidy(o,i)):Qt.runKernel(Ae,s,a);var o,i}});const ko=sn({movingAverage_:function(e,t,n,r,s=!0){const a=tn(e,"v","movingAverage"),o=tn(t,"x","movingAverage"),i=tn(n,"decay","movingAverage");var u,p;p=o,J((u=a).dtype===p.dtype,(()=>`The dtypes of the first(${u.dtype}) and second(${p.dtype}) input must match`)),J(re(a.shape,o.shape),(()=>"Shape mismatch in v and x"));const l=zr(1),c=ds(l,i);let h=Fn(ds(o,a),c);if(s){J(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=tn(r,"step","movingAverage");h=wr(h,ds(l,Fr(i,e)))}return pn(a,h)}});const To=sn({scatterND_:function(e,t,n){ge(n);const r=tn(e,"indices","scatterND","int32"),s=tn(t,"updates","scatterND");co(s,r,n);const a={indices:r,updates:s},o={shape:n};return Qt.runKernel("ScatterNd",a,o)}});const vo=sn({sparseToDense_:function(e,t,n,r=0){ge(n);const s=tn(e,"sparseIndices","sparseToDense","int32"),a=tn(t,"sparseValues","sparseToDense","string_or_numeric"),o=tn(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 o=t.size;if(0!==t.rank&&(1!==t.rank||o!==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,o);const i={sparseIndices:s,sparseValues:a,defaultValue:o},u={outputShape:n};return Qt.runKernel("SparseToDense",i,u)}});const So=sn({gatherND_:function(e,t){const n=tn(t,"indices","gatherND","int32"),r={params:tn(e,"x","gatherND","string_or_numeric"),indices:n};return Qt.runKernel("GatherNd",r)}});const _o=sn({dropout_:function(e,t,n,r){const s=tn(e,"x","dropout");if(J("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.`)),J(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Mt?s.clone():s;const a=function(e,t){if(null==t)return e.shape.slice();if(re(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),J(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}`)),ee(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];J(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const o=await r.data(),i=await s.data(),[u,p]=[o.length/a,a],l=function(e,t){return ie(e,t)}("bool",u);for(let e=0;et.value-e.value)),l[e]=0;for(let t=0;t`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`)),J(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),J(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const p="NHWC"===a?i.shape[3]:i.shape[1],l="NHWC"===a?u.shape[3]:u.shape[1];J(p===n[2],(()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${n[2]}.`)),J(l===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${l}) must match output depth for filter (${n[3]}).`)),In("conv2dDerFilter",s,o);const c={x:i,dy:u},h={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,filterShape:n};return Qt.runKernel("Conv2DBackpropFilter",c,h)}});function Do(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Fn(e,ao(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Oo(e,t){let n=t;const r=function(e,t){const n=[];for(let r=0;r1)&&n.unshift(a)}return n}(e.shape,t.shape);return r.length>0&&(n=Br(n,r)),$n(n,e.shape)}function Mo(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Da(e);if("elu"===t)return $r(e);if("relu6"===t)return Oa(e);if("prelu"===t)return Ws(e,n);if("leakyrelu"===t)return rs(e,r);if("sigmoid"===t)return Rn(e);throw new Error(`Unknown fused activation ${t}.`)}const Co=(e,t)=>!(e>0)||"linear"===t;const Fo=sn({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:p,leakyreluAlpha:l}){if(u=u||"linear",!1===Co(Qt.state.gradientDepth,u)){J("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 c=sr(e,t,n,r,s,a,o);return null!=i&&(c=pn(c,i)),Mo(c,u,p,l)}const c=tn(e,"x","conv2d","float32"),h=tn(t,"filter","conv2d","float32");let d=c,m=!1;3===c.rank&&(m=!0,d=$n(c,[1,c.shape[0],c.shape[1],c.shape[2]])),J(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),J(4===h.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`)),In("fused conv2d",r,o);const f="NHWC"===s?d.shape[3]:d.shape[1];J(h.shape[2]===f,(()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${h.shape[2]}.`)),J(_n(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const y=wn(d.shape,h.shape,n,a,r,o);let g,b;if(null!=i&&(g=tn(i,"bias","fused conv2d"),[g]=Ut(g,c),"NHWC"===s?kr(y.outShape,g.shape):(J(g.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${g.shape.length}.`)),J(0===g.shape.length||g.shape[0]===y.outChannels||1===g.shape[0],(()=>`Error in fused conv2d: bias shape (${g.shape}) is not compatible with the number of output channels (${y.outChannels})`)))),null!=p){const e=p.shape;if(J(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}.`)),1===e.length)J(1===e[0]||e[0]===y.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${y.outChannels}).`));else if(3===e.length)try{kr(e,y.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${y.outShape}).`;throw Error(n)}b=tn(p,"prelu weights","fused conv2d")}const x=(e,t)=>{J("NHWC"===s,(()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`));const[o,i,p,l]=t,c=Do(e,p,u);J(Sn(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const h=[or(i.shape,c,o,n,r),Ao(i,c,o.shape,n,r)];if(null!=l){const e=Oo(l,c);h.push(e)}return h},N={x:d,filter:h,bias:g,preluActivationWeights:b},w={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:u,leakyreluAlpha:l};if(null==i){const e=ps(((e,t,n)=>{let r=Qt.runKernel(Oe,N,w);return n([t,e,r]),m&&(r=$n(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(d,h)}{const e=ps(((e,t,n,r)=>{let s=Qt.runKernel(Oe,N,w);return r([t,e,s,n]),m&&(s=$n(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(d,h,g)}}});const Ro=sn({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,a=[1,1],o){let i=e;3===e.rank&&(i=$n(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=$n(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p={x:i,dy:u},l={strides:r,pad:s,dimRoundingMode:o,dilations:a,filterShape:n};return Qt.runKernel("DepthwiseConv2dNativeBackpropFilter",p,l)}});const zo=sn({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,a=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=$n(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p={dy:i,filter:n},l={strides:r,pad:s,dimRoundingMode:o,dilations:a,inputShape:e},c=Qt.runKernel("DepthwiseConv2dNativeBackpropInput",p,l);return u?$n(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Vo=sn({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:p,leakyreluAlpha:l}){if(!1===Co(Qt.state.gradientDepth,u)){let c=gr(e,t,n,r,s,a,o);return null!=i&&(c=pn(c,i)),Mo(c,u,p,l)}const c=tn(e,"x","depthwiseConv2d","float32"),h=tn(t,"filter","depthwiseConv2d","float32");let d=c,m=!1;3===c.rank&&(m=!0,d=$n(c,[1,c.shape[0],c.shape[1],c.shape[2]])),J(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),J(4===h.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`)),J(d.shape[3]===h.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`)),null==a&&(a=[1,1]),J(_n(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),In("fused depthwiseConv2d",r,o);const f=wn(d.shape,h.shape,n,a,r,o,!0);let y,g;null!=i&&(y=tn(i,"bias","fused conv2d"),[y]=Ut(y,c),kr(f.outShape,y.shape)),null!=p&&(g=tn(p,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{J(Sn(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[s,i,p,l]=t,c=Do(e,p,u),h=zo(i.shape,c,s,n,r,a,o),d=Ro(i,c,s.shape,n,r,a,o);if(null!=l){return[h,d,Oo(y,c)]}return[h,d]},x={x:d,filter:h,bias:y,preluActivationWeights:g},N={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:u,leakyreluAlpha:l};if(null==i){const e=ps(((e,t,n)=>{let r=Qt.runKernel(Me,x,N);return n([t,e,r]),m&&(r=$n(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,h)}{const e=ps(((e,t,n,r)=>{let s=Qt.runKernel(Me,x,N);return r([t,e,s,n]),m&&(s=$n(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}));return e(d,h,y)}}});var Lo={__proto__:null,conv2d:Fo,depthwiseConv2d:Vo,matMul:sn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(!1===Co(Qt.state.gradientDepth,a)){let u=Cn(e,t,n,r);return null!=s&&(u=pn(u,s)),Mo(u,a,o,i)}let u=tn(e,"a","fused matMul"),p=tn(t,"b","fused matMul");[u,p]=Ut(u,p);const l=n?u.shape[u.rank-2]:u.shape[u.rank-1],c=r?p.shape[p.rank-1]:p.shape[p.rank-2],h=n?u.shape[u.rank-1]:u.shape[u.rank-2],d=r?p.shape[p.rank-2]:p.shape[p.rank-1],m=u.shape.slice(0,-2),f=p.shape.slice(0,-2),y=ne(m),g=ne(f);J(l===c,(()=>`Error in fused matMul: inner shapes (${l}) and (${c}) of Tensors with shapes ${u.shape} and ${p.shape} and transposeA=${n} and transposeB=${r} must match.`));const b=kr(u.shape.slice(0,-2),p.shape.slice(0,-2)).concat([h,d]),x=$n(u,n?[y,l,h]:[y,h,l]),N=$n(p,r?[g,d,c]:[g,c,d]);let w,k;null!=s&&(w=tn(s,"bias","fused matMul"),[w]=Ut(w,u),kr(b,w.shape)),null!=o&&(k=tn(o,"prelu weights","fused matMul"));const T=(e,t)=>{const[o,i,u,p]=t,l=Do($n(e,u.shape),u,a);let c,h;if(n||r?!n&&r?(c=Cn(l,i,!1,!1),h=Cn(l,o,!0,!1)):n&&!r?(c=Cn(i,l,!1,!0),h=Cn(o,l,!1,!1)):(c=Cn(i,l,!0,!0),h=Cn(l,o,!0,!0)):(c=Cn(l,i,!1,!0),h=Cn(o,l,!0,!1)),null!=s){return[c,h,Oo(p,l)]}return[c,h]},v={a:x,b:N,bias:w,preluActivationWeights:k},S={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:i};if(null==s){const e=ps(((e,t,n)=>{const r=Qt.runKernel(De,v,S);return n([e,t,r]),{value:$n(r,b),gradFunc:T}}));return e(x,N)}{const e=ps(((e,t,n,r)=>{const s=Qt.runKernel(De,v,S);return r([e,t,s,n]),{value:$n(s,b),gradFunc:T}}));return e(x,N,w)}}})};const Bo=sn({hammingWindow_:function(e){return Io(e,.54,.46)}});const Po=sn({hannWindow_:function(e){return Io(e,.5,.5)}});const Ko=sn({frame_:function(e,t,n,r=!1,s=0){let a=0;const o=[];for(;a+t<=e.size;)o.push(zn(e,a,t)),a+=n;if(r)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`)),J(2===i.rank&&4===i.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${i.shape}.`)),J(1===u.rank&&u.shape[0]===p,(()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${i.shape}.`)),J(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),J(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),J("bilinear"===s||"nearest"===s,(()=>`method must be bilinear or nearest, but was ${s}`));const l={image:o,boxes:i,boxInd:u},c={method:s,extrapolationValue:a,cropSize:r};return Qt.runKernel("CropAndResize",l,c)}});const jo=sn({flipLeftRight_:function(e){const t=tn(e,"image","flipLeftRight","float32");J(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Qt.runKernel("FlipLeftRight",n,{})}});const Wo=sn({grayscaleToRGB_:function(e){const t=tn(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];J(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),J(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,Gr(t,s)}});const Go=sn({rgbToGrayscale_:function(e){const t=tn(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];J(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),J(3===r,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`));const s=t.dtype,a=Nn(t,"float32"),o=po([.2989,.587,.114]);let i;switch(t.rank){case 2:i=Ir("ij,j->i",a,o);break;case 3:i=Ir("ijk,k->ij",a,o);break;case 4:i=Ir("ijkl,l->ijk",a,o);break;case 5:i=Ir("ijklm,m->ijkl",a,o);break;case 6:i=Ir("ijklmn,n->ijklm",a,o);break;default:throw new Error("Not a valid tensor rank.")}return i=jr(i,-1),Nn(i,s)}});const Ho=sn({rotateWithOffset_:function(e,t,n=0,r=.5){const s=tn(e,"image","rotateWithOffset","float32");J(4===s.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`));const a={image:s},o={radians:t,fillValue:n,center:r};return Qt.runKernel("RotateWithOffset",a,o)}});function Zo(e,t,n,r,s,a){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==a&&(a=0);const o=e.shape[0];return n=Math.min(n,o),J(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),J(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),J(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),J(1===t.rank,(()=>"scores must be a 1D tensor")),J(t.shape[0]===o,(()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`)),J(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const Qo=sn({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=tn(e,"boxes","nonMaxSuppression","float32"),o=tn(t,"scores","nonMaxSuppression","float32"),i=Zo(a,o,n,r,s),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:s=i.scoreThreshold};return Qt.runKernel("NonMaxSuppressionV3",{boxes:a,scores:o},u)}});function Yo(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,a=0,o=!1;for(;r>>1);const i=n(t,e[a]);i>0?r=a+1:(s=a,o=!i)}return o?r:-r-1}(e,t,n||Xo)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function Xo(e,t){return e>t?1:es&&p.push({score:t[e],boxIndex:e,suppressBeginIndex:0});p.sort(ni);const l=a>0?-.5/a:0,c=[],h=[];for(;c.length0;){const t=p.pop(),{score:n,boxIndex:a,suppressBeginIndex:o}=t;if(n=o;--n){const o=ei(e,a,c[n]);if(o>=r){i=!0;break}if(t.score=t.score*ti(r,l,o),t.score<=s)break}t.suppressBeginIndex=c.length,i||(t.score===n?(c.push(a),h.push(t.score)):t.score>s&&Yo(p,t,ni))}const d=c.length,m=n-d;i&&m>0&&(c.push(...new Array(m).fill(0)),h.push(...new Array(m).fill(0)));const f={selectedIndices:c};return o&&(f.selectedScores=h),u&&(f.validOutputs=d),f}function ei(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]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),p=Math.min(s[0],s[2]),l=Math.min(s[1],s[3]),c=Math.max(s[0],s[2]),h=Math.max(s[1],s[3]),d=(i-a)*(u-o),m=(c-p)*(h-l);if(d<=0||m<=0)return 0;const f=Math.max(a,p),y=Math.max(o,l),g=Math.min(i,c),b=Math.min(u,h),x=Math.max(g-f,0)*Math.max(b-y,0);return x/(d+m-x)}function ti(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function ni(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const ri=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=tn(e,"boxes","nonMaxSuppressionAsync"),o=tn(t,"scores","nonMaxSuppressionAsync"),i=Zo(a,o,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;const u=await Promise.all([a.data(),o.data()]),p=u[0],l=u[1],{selectedIndices:c}=function(e,t,n,r,s){return Jo(e,t,n,r,s,0)}(p,l,n,r,s);return a!==e&&a.dispose(),o!==t&&o.dispose(),po(c,"int32")};const si=sn({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const o=tn(e,"boxes","nonMaxSuppression"),i=tn(t,"scores","nonMaxSuppression"),u=Zo(o,i,n,r,s,a),p={boxes:o,scores:i},l={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:s=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},c=Qt.runKernel("NonMaxSuppressionV5",p,l);return{selectedIndices:c[0],selectedScores:c[1]}}});const ai=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const o=tn(e,"boxes","nonMaxSuppressionAsync"),i=tn(t,"scores","nonMaxSuppressionAsync"),u=Zo(o,i,n,r,s,a);n=u.maxOutputSize,r=u.iouThreshold,s=u.scoreThreshold,a=u.softNmsSigma;const p=await Promise.all([o.data(),i.data()]),l=p[0],c=p[1],{selectedIndices:h,selectedScores:d}=function(e,t,n,r,s,a){return Jo(e,t,n,r,s,a,!0)}(l,c,n,r,s,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:po(h,"int32"),selectedScores:po(d)}};const oi=sn({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const o=tn(e,"boxes","nonMaxSuppression"),i=tn(t,"scores","nonMaxSuppression"),u=Zo(o,i,n,r,s,null),p={boxes:o,scores:i},l={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:a},c=Qt.runKernel("NonMaxSuppressionV4",p,l);return{selectedIndices:c[0],validOutputs:c[1]}}});const ii=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const o=tn(e,"boxes","nonMaxSuppressionAsync"),i=tn(t,"scores","nonMaxSuppressionAsync"),u=Zo(o,i,n,r,s,null),p=u.maxOutputSize,l=u.iouThreshold,c=u.scoreThreshold,[h,d]=await Promise.all([o.data(),i.data()]),{selectedIndices:m,validOutputs:f}=function(e,t,n,r,s,a){return Jo(e,t,n,r,s,0,!1,a,!0)}(h,d,p,l,c,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:po(m,"int32"),validOutputs:zr(f,"int32")}};const ui=sn({resizeBilinear_:function(e,t,n=!1,r=!1){const s=tn(e,"images","resizeBilinear");J(3===s.rank||4===s.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`)),J(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),J(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=s,o=!1;3===s.rank&&(o=!0,a=$n(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const i={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},p=Qt.runKernel("ResizeBilinear",i,u);return o?$n(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});const pi=sn({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=tn(e,"images","resizeNearestNeighbor");J(3===s.rank||4===s.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`)),J(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),J("float32"===s.dtype||"int32"===s.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),J(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=s,o=!1;3===s.rank&&(o=!0,a=$n(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const i={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},p=Qt.runKernel("ResizeNearestNeighbor",i,u);return o?$n(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});const li=sn({threshold_:function(e,t="binary",n=!1,r=.5){const s=tn(e,"image","threshold"),a=s.shape[0]*s.shape[1];let o,i,u,p,l=Fn(po([r]),255);if(J(3===s.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`)),J(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]}.`)),J("int32"===s.dtype||"float32"===s.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`)),J("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===s.shape[2]){[o,i,u]=eo(s,[1,1,1],-1);const e=Fn(o,.2989),t=Fn(i,.587),n=Fn(u,.114);p=pn(pn(e,t),n)}else p=e;if("otsu"===t){l=function(e,t){let n,r,s,a,o,i,u=po([-1]),p=po([0]),l=po([0]);for(let c=0;c`Error in transform: image must be rank 4,but got rank ${o.rank}.`)),J(2===i.rank&&(i.shape[0]===o.shape[0]||1===i.shape[0])&&8===i.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),J(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const u={image:o,transforms:i},p={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return Qt.runKernel("Transform",u,p)}});const hi=sn({bandPart_:function(e,t,n){const r=tn(e,"a","bandPart");J(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const s=r.shape,[a,o]=r.shape.slice(-2);let i,u;"number"==typeof t?(J(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),J(t<=a,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`)),i=tn(t<0?a:t,"numLower","bandPart")):(J("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),i=vr(ss(t,0),a,$s(t,a))),"number"==typeof n?(J(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),J(n<=o,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`)),u=tn(n<0?o:n,"numUpper","bandPart")):(J("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=vr(ss(n,0),o,$s(n,o)));const p=$n(Ia(0,a,1,"int32"),[-1,1]),l=Ia(0,o,1,"int32"),c=ds(p,l),h=ys(as(c,i),Xr(c,ls(u))),d=Es([a,o],r.dtype);return $n(so(bo($n(r,[-1,a,o])).map((e=>vr(h,e,d)))),s)}});const di=sn({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,J(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`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=eo(e,e.shape[0],0).map((e=>ro(e,[0])));J(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{let e=r[t];if(t>0)for(let r=0;r{J(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=Hr(n),a=On(e);const o=lo([[1]],[1,1]);let i=On(o);const u=n>=r?r:n;for(let e=0;e{const t=zn(a,[e,e],[n-e,1]),u=Kr(t),p=zn(a,[e,e],[1,1]),l=vr(Yr(p,0),lo([[-1]]),lo([[1]])),c=ds(p,Fn(l,u)),h=wr(t,c);i=1===h.shape[0]?On(o):Mn([o,zn(h,[1,0],[h.shape[0]-1,h.shape[1]])],0);const d=ls(wr(Cn(l,c),u)),m=zn(a,[e,0],[n-e,r]),f=Fn(d,i),y=wo(i);if(0===e)a=ds(m,Cn(f,Cn(y,m)));else{const t=ds(m,Cn(f,Cn(y,m)));a=Mn([zn(a,[0,0],[e,r]),t],0)}const g=wo(f),b=zn(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=ds(b,Cn(Cn(b,i),g));else{const t=ds(b,Cn(Cn(b,i),g));s=Mn([zn(s,[0,0],[n,e]),t],1)}return[i,a,s]})),jt([t,u,p]).forEach((e=>e.dispose()))}return!t&&n>r&&(s=zn(s,[0,0],[n,r]),a=zn(a,[0,0],[r,r])),[s,a]}))}const fi=sn({qr_:function(e,t=!1){if(J(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return mi(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=bo($n(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];r.forEach((e=>{const[n,r]=mi(e,t);s.push(n),a.push(r)}));return[$n(so(s,0),e.shape),$n(so(a,0),e.shape)]}}});var yi;!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"}(yi||(yi={}));const gi=sn({computeWeightedLoss_:function(e,t,n=yi.SUM_BY_NONZERO_WEIGHTS){const r=tn(e,"losses","computeWeightedLoss");let s=null;null!=t&&(s=tn(t,"weights","computeWeightedLoss"));const a=null==s?r:Fn(r,s);if(n===yi.NONE)return a;if(n===yi.SUM)return Br(a);if(n===yi.MEAN){if(null==s)return _s(a);{const e=r.size/s.size,t=wr(Br(a),Br(s));return e>1?wr(t,zr(e)):t}}if(n===yi.SUM_BY_NONZERO_WEIGHTS){if(null==s)return wr(Br(a),zr(r.size));{const e=Fn(s,Is(r.shape)),t=Nn(Br(Fs(e,zr(0))),"float32");return wr(Br(a),t)}}throw Error(`Unknown reduction: ${n}`)}});const bi=sn({absoluteDifference_:function(e,t,n,r=yi.SUM_BY_NONZERO_WEIGHTS){const s=tn(e,"labels","absoluteDifference"),a=tn(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=tn(n,"weights","absoluteDifference")),ee(s.shape,a.shape,"Error in absoluteDifference: ");const i=an(ds(s,a));return gi(i,o,r)}});const xi=sn({cosineDistance_:function(e,t,n,r,s=yi.SUM_BY_NONZERO_WEIGHTS){const a=tn(e,"labels","cosineDistance"),o=tn(t,"predictions","cosineDistance");let i=null;null!=r&&(i=tn(r,"weights","cosineDistance")),ee(a.shape,o.shape,"Error in cosineDistance: ");const u=zr(1),p=ds(u,Br(Fn(a,o),n,!0));return gi(p,i,s)}});const Ni=sn({hingeLoss_:function(e,t,n,r=yi.SUM_BY_NONZERO_WEIGHTS){let s=tn(e,"labels","hingeLoss");const a=tn(t,"predictions","hingeLoss");let o=null;null!=n&&(o=tn(n,"weights","hingeLoss")),ee(s.shape,a.shape,"Error in hingeLoss: ");const i=zr(1);s=ds(Fn(zr(2),s),i);const u=Da(ds(i,Fn(s,a)));return gi(u,o,r)}});const wi=sn({huberLoss_:function(e,t,n,r=1,s=yi.SUM_BY_NONZERO_WEIGHTS){const a=tn(e,"labels","huberLoss"),o=tn(t,"predictions","huberLoss");let i=null;null!=n&&(i=tn(n,"weights","huberLoss")),ee(a.shape,o.shape,"Error in huberLoss: ");const u=zr(r),p=an(ds(o,a)),l=$s(p,u),c=ds(p,l),h=pn(Fn(zr(.5),Lr(l)),Fn(u,c));return gi(h,i,s)}});const ki=sn({logLoss_:function(e,t,n,r=1e-7,s=yi.SUM_BY_NONZERO_WEIGHTS){const a=tn(e,"labels","logLoss"),o=tn(t,"predictions","logLoss");let i=null;null!=n&&(i=tn(n,"weights","logLoss")),ee(a.shape,o.shape,"Error in logLoss: ");const u=zr(1),p=zr(r),l=ls(Fn(a,is(pn(o,p)))),c=Fn(ds(u,a),is(pn(ds(u,o),p))),h=ds(l,c);return gi(h,i,s)}});const Ti=sn({meanSquaredError_:function(e,t,n,r=yi.SUM_BY_NONZERO_WEIGHTS){const s=tn(e,"labels","meanSquaredError"),a=tn(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=tn(n,"weights","meanSquaredError")),ee(s.shape,a.shape,"Error in meanSquaredError: ");const i=no(s,a);return gi(i,o,r)}});const vi=sn({sigmoidCrossEntropy_:function(e,t,n,r=0,s=yi.SUM_BY_NONZERO_WEIGHTS){let a=tn(e,"multiClassLabels","sigmoidCrossEntropy");const o=tn(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=tn(n,"weights","sigmoidCrossEntropy")),ee(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=zr(r),t=zr(1),n=zr(.5);a=pn(Fn(a,ds(t,e)),Fn(n,e))}const u=function(e,t){const n=tn(e,"labels","sigmoidCrossEntropyWithLogits"),r=tn(t,"logits","sigmoidCrossEntropyWithLogits");ee(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=Da(r),a=Fn(r,n),o=us(Ur(ls(an(r))));return pn(ds(s,a),o)}(a,o);return gi(u,i,s)}});const Si=sn({softmaxCrossEntropy_:function(e,t,n,r=0,s=yi.SUM_BY_NONZERO_WEIGHTS){let a=tn(e,"onehotLabels","softmaxCrossEntropy");const o=tn(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=tn(n,"weights","softmaxCrossEntropy")),ee(a.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=zr(r),t=zr(1),n=zr(a.shape[1]);a=pn(Fn(a,ds(t,e)),wr(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=ps(((e,t,r)=>{const s=fs(t,[n],!0),a=ds(Nn(t,"float32"),s);r([e,a]);const o=ls(Fn(a,e));return{value:Br(o,[n]),gradFunc:(e,t)=>{const[r,s]=t,a=Or(e.shape,[n]);return[Fn($n(e,a),ds(Nn(r,"float32"),Ur(s))),Fn($n(e,a),ds(Ur(s),Nn(r,"float32")))]}}}));return r(e,t)}(a,o);return gi(u,i,s)}});const _i=sn({sparseFillEmptyRows_:function(e,t,n,r){const s=tn(e,"indices","sparseFillEmptyRows","int32"),a=tn(t,"values","sparseFillEmptyRows"),o=tn(n,"denseShape","sparseFillEmptyRows","int32"),i=tn(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!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:s,values:a,denseShape:o,defaultValue:i},p=Qt.runKernel("SparseFillEmptyRows",u);return{outputIndices:p[0],outputValues:p[1],emptyRowIndicator:p[2],reverseIndexMap:p[3]}}});const Ei=sn({sparseReshape_:function(e,t,n){const r=tn(e,"inputIndices","sparseReshape","int32"),s=tn(t,"inputShape","sparseReshape","int32"),a=tn(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 o={inputIndices:r,inputShape:s,newShape:a},i=Qt.runKernel("SparseReshape",o);return{outputIndices:i[0],outputShape:i[1]}}});const Ii=sn({sparseSegmentMean_:function(e,t,n){const r=tn(e,"data","sparseSegmentMean"),s=tn(t,"indices","sparseSegmentMean","int32"),a=tn(n,"segmentIds","sparseSegmentMean","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 o={data:r,indices:s,segmentIds:a};return Qt.runKernel("SparseSegmentMean",o)}});const $i=sn({sparseSegmentSum_:function(e,t,n){const r=tn(e,"data","sparseSegmentSum"),s=tn(t,"indices","sparseSegmentSum","int32"),a=tn(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 o={data:r,indices:s,segmentIds:a};return Qt.runKernel("SparseSegmentSum",o)}});const Ai=sn({stringNGrams_:function(e,t,n,r,s,a,o,i){const u=tn(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 p=tn(t,"dataSplits","stringNGrams");if("int32"!==p.dtype)throw new Error("Data splits must be of datatype int32");const l={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},c={data:u,dataSplits:p},h=Qt.runKernel("StringNGrams",c,l);return{nGrams:h[0],nGramsSplits:h[1]}}});var Di={__proto__:null,OP_SCOPE_SUFFIX:rn,abs:an,acos:on,acosh:un,add:pn,addN:ln,all:cn,any:hn,argMax:dn,argMin:mn,asin:fn,asinh:yn,atan:gn,atan2:bn,atanh:xn,avgPool:An,avgPool3d:Dn,basicLSTMCell:Ln,batchNorm:Pn,batchNorm2d:Kn,batchNorm3d:qn,batchNorm4d:Un,batchToSpaceND:Bn,bincount:jn,bitwiseAnd:Wn,booleanMaskAsync:No,broadcastArgs:Gn,broadcastTo:Hn,buffer:Zn,cast:Nn,ceil:Qn,clipByValue:Xn,clone:On,complex:Jn,concat:Mn,concat1d:er,concat2d:tr,concat3d:nr,concat4d:rr,conv1d:ar,conv2d:sr,conv2dTranspose:ir,conv3d:ur,conv3dTranspose:lr,cos:cr,cosh:hr,cosineWindow:Io,cumprod:dr,cumsum:mr,denseBincount:fr,depthToSpace:yr,depthwiseConv2d:gr,diag:br,dilation2d:xr,div:wr,divNoNan:_r,dot:Er,dropout:_o,einsum:Ir,elu:$r,enclosingPowerOfTwo:Eo,ensureShape:Ar,equal:Tr,erf:Dr,euclideanNorm:qr,exp:Ur,expandDims:jr,expm1:Wr,eye:Hr,fft:Ya,fill:Yn,floor:Zr,floorDiv:Nr,fused:Lo,gather:Qr,gatherND:So,greater:Yr,greaterEqual:Xr,ifft:Xa,imag:Jr,image:{flipLeftRight:jo,grayscaleToRGB:Wo,resizeNearestNeighbor:pi,resizeBilinear:ui,rgbToGrayscale:Go,rotateWithOffset:Ho,cropAndResize:Uo,nonMaxSuppression:Qo,nonMaxSuppressionAsync:ri,nonMaxSuppressionWithScore:si,nonMaxSuppressionWithScoreAsync:ai,nonMaxSuppressionPadded:oi,nonMaxSuppressionPaddedAsync:ii,threshold:li,transform:ci},inTopKAsync:$o,irfft:Ja,isFinite:es,isInf:ts,isNaN:ns,leakyRelu:rs,less:ss,lessEqual:as,linalg:{bandPart:hi,gramSchmidt:di,qr:fi},linspace:function(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 Qt.runKernel("LinSpace",{},r)},localResponseNormalization:os,log:is,log1p:us,logSigmoid:hs,logSoftmax:ms,logSumExp:fs,logicalAnd:ys,logicalNot:gs,logicalOr:bs,logicalXor:xs,losses:{absoluteDifference:bi,computeWeightedLoss:gi,cosineDistance:xi,hingeLoss:Ni,huberLoss:wi,logLoss:ki,meanSquaredError:Ti,sigmoidCrossEntropy:vi,softmaxCrossEntropy:Si},lowerBound:function(e,t){return ws(e,t,"left")},matMul:Cn,max:Mr,maxPool:ks,maxPool3d:Ts,maxPoolWithArgmax:vs,maximum:Ss,mean:_s,meshgrid:function(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=tn(e,"x","meshgrid",e instanceof Mt?e.dtype:"float32");if(void 0===t)return[r];let s=tn(t,"y","meshgrid",t instanceof Mt?t.dtype:"float32");const a=ne(r.shape),o=ne(s.shape);return"xy"===n?(r=$n(r,[1,-1]),s=$n(s,[-1,1]),[Cn(Is([o,1],r.dtype),r),Cn(s,Is([1,a],s.dtype))]):(r=$n(r,[-1,1]),s=$n(s,[1,-1]),[Cn(r,Is([1,o],r.dtype)),Cn(Is([a,1],s.dtype),s)])},min:Cr,minimum:$s,mirrorPad:As,mod:Ds,moments:Os,movingAverage:ko,mul:Fn,multiRNNCell:Ms,multinomial:Cs,neg:ls,norm:Kr,notEqual:Fs,oneHot:Rs,ones:Is,onesLike:zs,op:sn,outerProduct:Vs,pad:Ls,pad1d:Bs,pad2d:Ps,pad3d:Ks,pad4d:qs,pool:js,pow:Fr,prelu:Ws,print:function(e,t=!1){console.log(e.toString(t))},prod:Gs,raggedGather:Hs,raggedRange:Zs,raggedTensorToTensor:Qs,rand:Ys,randomGamma:Ta,randomNormal:va,randomStandardNormal:Sa,randomUniform:_a,randomUniformInt:Ea,range:Ia,real:$a,reciprocal:Aa,relu:Da,relu6:Oa,reshape:$n,reverse:Ma,reverse1d:Ca,reverse2d:Fa,reverse3d:Ra,reverse4d:za,rfft:to,round:Va,rsqrt:La,scalar:zr,scatterND:To,searchSorted:ws,selu:Ba,separableConv2d:Pa,setdiff1dAsync:Ka,sigmoid:Rn,sign:qa,signal:{hammingWindow:Bo,hannWindow:Po,frame:Ko,stft:qo},sin:Ua,sinh:ja,slice:zn,slice1d:Wa,slice2d:Ga,slice3d:Ha,slice4d:Za,softmax:Qa,softplus:cs,spaceToBatchND:Us,sparse:{sparseFillEmptyRows:_i,sparseReshape:Ei,sparseSegmentMean:Ii,sparseSegmentSum:$i},sparseToDense:vo,spectral:{fft:Ya,ifft:Xa,rfft:to,irfft:Ja},split:eo,sqrt:Vr,square:Lr,squaredDifference:no,squeeze:ro,stack:so,step:ao,stridedSlice:oo,string:{stringNGrams:Ai,stringSplit:sn({stringSplit_:function(e,t,n=!0){const r=tn(e,"input","stringSplit","string"),s=tn(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},o={input:r,delimiter:s},i=Qt.runKernel("StringSplit",o,a);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:sn({stringToHashBucketFast_:function(e,t){const n=tn(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 Qt.runKernel("StringToHashBucketFast",s,r)}}),staticRegexReplace:sn({staticRegexReplace_:function(e,t,n,r=!0){const s=tn(e,"input","staticRegexReplace","string"),a={pattern:t,rewrite:n,replaceGlobal:r};return Qt.runKernel("StaticRegexReplace",{x:s},a)}})},sub:ds,sum:Br,tan:io,tanh:Vn,tensor:uo,tensor1d:po,tensor2d:lo,tensor3d:function(e,t,n){if(te(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Xt(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 Rr(e,t,r,n)},tensor4d:function(e,t,n){if(te(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Xt(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 Rr(e,t,r,n)},tensor5d:function(e,t,n){if(te(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Xt(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 Rr(e,t,r,n)},tensor6d:function(e,t,n){if(te(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Xt(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 Rr(e,t=t||r,r,n)},tensorScatterUpdate:ho,tile:Gr,topk:mo,transpose:wo,truncatedNormal:fo,unique:yo,unsortedSegmentSum:go,unstack:bo,upperBound:function(e,t){return ws(e,t,"right")},variable:function(e,t=!0,n,r){return Qt.makeVariable(e,t,n,r)},where:vr,whereAsync:xo,zeros:Es,zerosLike:Sr};function Oi(e,n,r=""){if("number"!=typeof e&&"number"!=typeof n){t.util.assert(e.length===n.length,(()=>r+` Shapes ${e} and ${n} must match`));for(let s=0;sr+` Shapes ${e} and ${n} must match`))}}}function Mi(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Ci(e,t,n){let r=Fi(e,n);const s=!Mi(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=Fi(e.shape,r)})),!Mi(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Fi(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=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}class Ri{constructor(e,n,r,s,a,o,i){this.name=e,this.dtype=n,this.maxSize=r,this.elementShape=s,this.identicalElementShapes=a,this.dynamicSize=o,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=t.scalar(0),t.keep(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,n){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(n.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${n.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=n.shape),Oi(this.elementShape,n.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=n,t.keep(n),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(((e,n)=>this.write(e,t[n])))}gather(e,n){if(n&&n!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${n}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(e,t.unstack(n,0))}split(e,n){if(n.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${n.dtype}`);let r=0;const s=e.map((e=>(r+=e,r)));if(r!==n.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: ${n.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=0===r?0:n.size/r,o=[];t.tidy((()=>{n=t.reshape(n,[1,r,a]);for(let r=0;r{if(r!==e.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${e.dtype}`);Oi(n,e.shape,"TensorList shape mismatch: "),t.keep(e)})),this.idTensor=t.scalar(0),this.maxNumElements=s,t.keep(this.idTensor)}copy(){return new zi([...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,n,r=-1){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(-1!==r&&this.tensors.length!==r)throw new Error(`Operation expected a list with ${r} elements but got a list with ${this.tensors.length} elements.`);Oi(e,this.elementShape,"TensorList shape mismatch: ");const s=Ci(this.elementShape,this.tensors,e);return t.tidy((()=>{const e=this.tensors.map((e=>t.reshape(e,s)));return t.stack(e,0)}))}popBack(e,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const r=Ci(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,Oi(s.shape,e,"TensorList shape mismatch: "),t.reshape(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(Oi(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");t.keep(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 zi([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;nthis.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.`);Oi(this.tensors[e].shape,n,"TensorList shape mismatch: ");const s=Ci(this.elementShape,this.tensors,n);return t.reshape(this.tensors[e],s)}setItem(e,n){if(n.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n.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.`);Oi(this.elementShape,n.shape,"TensorList shape mismatch: "),t.keep(n),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=n}gather(e,n,r){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);Oi(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=Ci(this.elementShape,this.tensors,r);return 0===e.length?t.tensor([],[0].concat(s)):t.tidy((()=>{const n=e.map((e=>t.reshape(this.tensors[e],s)));return t.stack(n,0)}))}concat(e,n){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Oi(this.elementShape,n,"TensorList shape mismatch: ");const r=Ci(this.elementShape,this.tensors,n);return 0===this.size()?t.tensor([],[0].concat(r)):t.tidy((()=>{const e=this.tensors.map((e=>t.reshape(e,r)));return t.concat(e,0)}))}}const Vi=async(e,n,r)=>{switch(e.op){case"If":case"StatelessIf":{const t=p("thenBranch",e,n,r),s=p("elseBranch",e,n,r),a=p("cond",e,n,r),o=p("args",e,n,r);return(await a.data())[0]?r.functionMap[t].executeFunctionAsync(o,r.tensorArrayMap,r.tensorListMap):r.functionMap[s].executeFunctionAsync(o,r.tensorArrayMap,r.tensorListMap)}case"While":case"StatelessWhile":{const t=p("body",e,n,r),s=p("cond",e,n,r),a=p("args",e,n,r),o=await r.functionMap[s].executeFunctionAsync(a,r.tensorArrayMap,r.tensorListMap),i=a.map((e=>e.id));let u=await o[0].data();o.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()}));let l=a;for(;u[0];){const e=l;l=await r.functionMap[t].executeFunctionAsync(l,r.tensorArrayMap,r.tensorListMap);const n=l.map((e=>e.id));e.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==n.indexOf(e.id)||e.dispose()}));const a=await r.functionMap[s].executeFunctionAsync(l,r.tensorArrayMap,r.tensorListMap);u=await a[0].data(),a.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==n.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[y(p("pred",e,n,r))];case"Switch":{const t=p("pred",e,n,r);let s=p("data",e,n,r);return s.kept||(s=y(s)),(await t.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const t=e.inputNames.find((e=>void 0!==l(e,n,r)));if(t){return[y(l(t,n,r))]}return}case"Enter":{const t=p("frameName",e,n,r),s=p("tensor",e,n,r);return r.enterFrame(t),[y(s)]}case"Exit":{const t=p("tensor",e,n,r);return r.exitFrame(),[y(t)]}case"NextIteration":{const t=p("tensor",e,n,r);return r.nextIteration(),[y(t)]}case"TensorArrayV3":{const s=p("size",e,n,r),a=p("dtype",e,n,r),o=p("elementShape",e,n,r),i=p("dynamicSize",e,n,r),u=p("clearAfterRead",e,n,r),l=p("identicalElementShapes",e,n,r),c=p("name",e,n,r),h=new Ri(c,a,s,o,l,i,u);return r.addTensorArray(h),[h.idTensor,t.scalar(1)]}case"TensorArrayWriteV3":{const t=p("tensorArrayId",e,n,r),s=p("index",e,n,r),a=p("tensor",e,n,r),o=r.getTensorArray(t.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{const t=p("tensorArrayId",e,n,r),s=p("index",e,n,r);return[r.getTensorArray(t.id).read(s)]}case"TensorArrayGatherV3":{const t=p("tensorArrayId",e,n,r),s=p("indices",e,n,r),a=p("dtype",e,n,r);return[r.getTensorArray(t.id).gather(s,a)]}case"TensorArrayScatterV3":{const t=p("tensorArrayId",e,n,r),s=p("indices",e,n,r),a=p("tensor",e,n,r),o=r.getTensorArray(t.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{const t=p("tensorArrayId",e,n,r),s=r.getTensorArray(t.id),a=p("dtype",e,n,r);return[s.concat(a)]}case"TensorArraySplitV3":{const t=p("tensorArrayId",e,n,r),s=p("tensor",e,n,r),a=p("lengths",e,n,r),o=r.getTensorArray(t.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{const s=p("tensorArrayId",e,n,r),a=r.getTensorArray(s.id);return[t.scalar(a.size(),"int32")]}case"TensorArrayCloseV3":{const t=p("tensorArrayId",e,n,r),s=r.getTensorArray(t.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const t=p("tensorListId",e,n,r),s=p("index",e,n,r),a=p("tensor",e,n,r),o=r.getTensorList(t.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{const t=p("tensorListId",e,n,r),s=p("index",e,n,r),a=p("elementShape",e,n,r),o=p("elementDType",e,n,r);return[r.getTensorList(t.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{const s=p("indices",e,n,r),a=function(e,n,r,s){if(n.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${n.length} vs. ${e.shape[0]}`);const a=Math.max(...n);if(null!=s&&-1!==s&&a>=s)throw new Error(`Max index must be < array size (${a} vs. ${s})`);const o=new zi([],r,e.dtype,s),i=t.unstack(e,0);return n.forEach(((e,t)=>{o.setItem(e,i[t])})),o}(p("tensor",e,n,r),s,p("elementShape",e,n,r),p("numElements",e,n,r));return r.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const t=p("elementShape",e,n,r),s=p("elementDType",e,n,r);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=p(a,e,n,r),i=function(e,t,n,r){return new zi([],e,t,r)}(t,s,0,"TensorListReserve"===e.op?-1:o);return r.addTensorList(i),[i.idTensor]}case"TensorListGather":{const t=p("tensorListId",e,n,r),s=p("indices",e,n,r),a=p("elementShape",e,n,r),o=p("elementDType",e,n,r);return[r.getTensorList(t.id).gather(s,o,a)]}case"TensorListStack":{const t=p("tensorListId",e,n,r),s=p("elementShape",e,n,r),a=p("elementDType",e,n,r),o=p("numElements",e,n,r);return[r.getTensorList(t.id).stack(s,a,o)]}case"TensorListFromTensor":{const s=function(e,n,r){const s=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!==r)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${r}`);Oi(e.shape.slice(1),n,"TensorList shape mismatch: ");const a=t.unstack(e);return new zi(a,n,s)}(p("tensor",e,n,r),p("elementShape",e,n,r),p("elementDType",e,n,r));return r.addTensorList(s),[s.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const t=p("tensorListId",e,n,r),s=r.getTensorList(t.id),a=p("dtype",e,n,r),o=p("elementShape",e,n,r);return[s.concat(a,o)]}case"TensorListPushBack":{const t=p("tensorListId",e,n,r),s=p("tensor",e,n,r),a=r.getTensorList(t.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const t=p("tensorListId",e,n,r),s=p("elementShape",e,n,r),a=p("elementDType",e,n,r);return[r.getTensorList(t.id).popBack(s,a)]}case"TensorListSplit":{const s=p("tensor",e,n,r),a=p("elementShape",e,n,r),o=function(e,n,r){let s=0;const a=n.map((e=>(s+=e,s)));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${s}, and tensor's shape is: ${e.shape}`);const o=Fi(e.shape.slice(1),r),i=0===s?0:e.size/s,u=t.tidy((()=>{const r=[];e=t.reshape(e,[1,s,i]);for(let s=0;se.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return zr(this.size(),"int32")}async import(e,n){this.checkKeyAndValueTensor(e,n);const r=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),t.tidy((()=>{const e=t.unstack(n),s=r.length,a=e.length;t.util.assert(s===a,(()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`));for(let n=0;n{const e=[];for(let t=0;t{switch(e.category){case"arithmetic":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(p("a",e,t,n),p("b",e,t,n))];case"AddN":return[r.addN(p("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(p("a",e,t,n),p("b",e,t,n))];case"Mul":return[r.mul(p("a",e,t,n),p("b",e,t,n))];case"RealDiv":case"Div":return[r.div(p("a",e,t,n),p("b",e,t,n))];case"DivNoNan":return[r.divNoNan(p("a",e,t,n),p("b",e,t,n))];case"FloorDiv":return[r.floorDiv(p("a",e,t,n),p("b",e,t,n))];case"Sub":return[r.sub(p("a",e,t,n),p("b",e,t,n))];case"Minimum":return[r.minimum(p("a",e,t,n),p("b",e,t,n))];case"Maximum":return[r.maximum(p("a",e,t,n),p("b",e,t,n))];case"Pow":return[r.pow(p("a",e,t,n),p("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(p("a",e,t,n),p("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"basic_math":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(p("x",e,t,n))];case"Acos":return[r.acos(p("x",e,t,n))];case"Acosh":return[r.acosh(p("x",e,t,n))];case"Asin":return[r.asin(p("x",e,t,n))];case"Asinh":return[r.asinh(p("x",e,t,n))];case"Atan":return[r.atan(p("x",e,t,n))];case"Atan2":return[r.atan2(p("x",e,t,n),p("y",e,t,n))];case"Atanh":return[r.atanh(p("x",e,t,n))];case"Ceil":return[r.ceil(p("x",e,t,n))];case"Complex":return[r.complex(p("real",e,t,n),p("imag",e,t,n))];case"Cos":return[r.cos(p("x",e,t,n))];case"Cosh":return[r.cosh(p("x",e,t,n))];case"Elu":return[r.elu(p("x",e,t,n))];case"Erf":return[r.erf(p("x",e,t,n))];case"Exp":return[r.exp(p("x",e,t,n))];case"Expm1":return[r.expm1(p("x",e,t,n))];case"Floor":return[r.floor(p("x",e,t,n))];case"Log":return[r.log(p("x",e,t,n))];case"Log1p":return[r.log1p(p("x",e,t,n))];case"Imag":return[r.imag(p("x",e,t,n))];case"Neg":return[r.neg(p("x",e,t,n))];case"Reciprocal":return[r.reciprocal(p("x",e,t,n))];case"Real":return[r.real(p("x",e,t,n))];case"Relu":return[r.relu(p("x",e,t,n))];case"Round":return[r.round(p("x",e,t,n))];case"Selu":return[r.selu(p("x",e,t,n))];case"Sigmoid":return[r.sigmoid(p("x",e,t,n))];case"Sin":return[r.sin(p("x",e,t,n))];case"Sign":return[r.sign(p("x",e,t,n))];case"Sinh":return[r.sinh(p("x",e,t,n))];case"Softplus":return[r.softplus(p("x",e,t,n))];case"Sqrt":return[r.sqrt(p("x",e,t,n))];case"Square":return[r.square(p("x",e,t,n))];case"Tanh":return[r.tanh(p("x",e,t,n))];case"Tan":return[r.tan(p("x",e,t,n))];case"ClipByValue":return[r.clipByValue(p("x",e,t,n),p("clipValueMin",e,t,n),p("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(p("x",e,t,n))];case"Rsqrt":return[r.rsqrt(l(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(p("x",e,t,n),p("alpha",e,t,n))];case"Prelu":return[r.prelu(p("x",e,t,n),p("alpha",e,t,n))];case"IsNan":return[r.isNaN(l(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(l(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(l(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"control":return Vi(e,n,r);case"convolution":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Conv1D":{const s=p("stride",e,t,n),a=p("pad",e,t,n),o=p("dataFormat",e,t,n).toUpperCase(),i=p("dilation",e,t,n);return[r.conv1d(p("x",e,t,n),p("filter",e,t,n),s,a,o,i)]}case"Conv2D":{const s=p("strides",e,t,n),a=f(e,t,n),o=p("dataFormat",e,t,n).toUpperCase(),i=p("dilations",e,t,n);return[r.conv2d(p("x",e,t,n),p("filter",e,t,n),[s[1],s[2]],a,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=Li(e,t,n);return[r.fused.conv2d({x:p("x",e,t,n),filter:p("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=Li(e,t,n);return[r.fused.depthwiseConv2d({x:p("x",e,t,n),filter:p("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=p("outputShape",e,t,n),a=p("strides",e,t,n),o=f(e,t,n);return[r.conv2dTranspose(p("x",e,t,n),p("filter",e,t,n),s,[a[1],a[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=p("strides",e,t,n),a=f(e,t,n),o=p("dilations",e,t,n),i=p("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(p("input",e,t,n),p("filter",e,t,n),[s[1],s[2]],a,i,[o[1],o[2]])]}case"Conv3D":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("dataFormat",e,t,n).toUpperCase(),i=p("dilations",e,t,n);return[r.conv3d(p("x",e,t,n),p("filter",e,t,n),[s[1],s[2],s[3]],a,o,[i[1],i[2],i[3]])]}case"AvgPool":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("kernelSize",e,t,n);return[r.avgPool(p("x",e,t,n),[o[1],o[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("kernelSize",e,t,n);return[r.maxPool(p("x",e,t,n),[o[1],o[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("kernelSize",e,t,n),i=p("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(p("x",e,t,n),[o[1],o[2]],[s[1],s[2]],a,i);return[u,l]}case"AvgPool3D":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("kernelSize",e,t,n);return[r.avgPool3d(p("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("kernelSize",e,t,n);return[r.maxPool3d(p("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=p("strides",e,t,n),a=p("pad",e,t,n),o=p("dilations",e,t,n),i=s[1],u=s[2],l=o[1],c=o[2];return[r.dilation2d(p("x",e,t,n),p("filter",e,t,n),[i,u],a,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"creation":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Fill":{const s=p("shape",e,t,n),a=p("dtype",e,t,n),o=p("value",e,t,n);return[r.fill(s,o,a)]}case"LinSpace":{const s=p("start",e,t,n),a=p("stop",e,t,n),o=p("num",e,t,n);return[r.linspace(s,a,o)]}case"Multinomial":{const s=p("logits",e,t,n),a=p("numSamples",e,t,n),o=p("seed",e,t,n);return[r.multinomial(s,a,o)]}case"OneHot":{const s=p("indices",e,t,n),a=p("depth",e,t,n),o=p("onValue",e,t,n),i=p("offValue",e,t,n),u=p("dtype",e,t,n);return[r.oneHot(s,a,o,i,u)]}case"Ones":return[r.ones(p("shape",e,t,n),p("dtype",e,t,n))];case"OnesLike":return[r.onesLike(p("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(p("shape",e,t,n),p("dtype",e,t,n),p("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(p("shape",e,t,n),p("minval",e,t,n),p("maxval",e,t,n),p("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(p("shape",e,t,n),p("minval",e,t,n),p("maxval",e,t,n),p("seed",e,t,n))];case"Range":{const s=p("start",e,t,n),a=p("stop",e,t,n),o=p("step",e,t,n);return[r.range(s,a,o,p("dtype",e,t,n))]}case"TruncatedNormal":{const s=p("shape",e,t,n),a=p("mean",e,t,n),o=p("stdDev",e,t,n),i=p("seed",e,t,n);return[r.truncatedNormal(s,a,o,p("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(p("shape",e,t,n),p("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(p("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"dynamic":return(async(e,t,n,r,s=Di)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:a,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:p}=Bi(e,t,n),l=await s.image.nonMaxSuppressionWithScoreAsync(r,a,o,i,u,p);return[l.selectedIndices,l.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:a,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Bi(e,t,n),l=p("padToMaxOutputSize",e,t,n),c=await s.image.nonMaxSuppressionPaddedAsync(r,a,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:a,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Bi(e,t,n);return[await s.image.nonMaxSuppressionAsync(r,a,o,i,u)]}case"Where":{const r=s.cast(p("condition",e,t,n),"bool"),a=[await s.whereAsync(r)];return r.dispose(),a}case"ListDiff":return s.setdiff1dAsync(p("x",e,t,n),p("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r);case"evaluation":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"LowerBound":{const s=p("sortedSequence",e,t,n),a=p("values",e,t,n);return[r.lowerBound(s,a)]}case"TopKV2":{const s=p("x",e,t,n),a=p("k",e,t,n),o=p("sorted",e,t,n),i=r.topk(s,a,o);return[i.values,i.indices]}case"UpperBound":{const s=p("sortedSequence",e,t,n),a=p("values",e,t,n);return[r.upperBound(s,a)]}case"Unique":{const s=p("x",e,t,n),a=r.unique(s);return[a.values,a.indices]}case"UniqueV2":{const s=p("x",e,t,n),a=p("axis",e,t,n),o=r.unique(s,a);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"image":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"ResizeBilinear":{const s=p("images",e,t,n),a=p("size",e,t,n),o=p("alignCorners",e,t,n),i=p("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(s,[a[0],a[1]],o,i)]}case"ResizeNearestNeighbor":{const s=p("images",e,t,n),a=p("size",e,t,n),o=p("alignCorners",e,t,n),i=p("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(s,[a[0],a[1]],o,i)]}case"CropAndResize":{const s=p("image",e,t,n),a=p("boxes",e,t,n),o=p("boxInd",e,t,n),i=p("cropSize",e,t,n),u=p("method",e,t,n),l=p("extrapolationValue",e,t,n);return[r.image.cropAndResize(s,a,o,i,u,l)]}case"ImageProjectiveTransformV3":{const s=p("images",e,t,n),a=p("transforms",e,t,n),o=p("outputShape",e,t,n),i=p("fillValue",e,t,n),u=p("interpolation",e,t,n),l=p("fillMode",e,t,n);return[r.image.transform(s,a,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"graph":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=p("default",e,t,n);return[l(e.name,t,n)||s];case"Placeholder":return[l(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[y(p("x",e,t,n))];case"IdentityN":return p("x",e,t,n).map((e=>y(e)));case"Shape":return[r.tensor1d(p("x",e,t,n).shape,"int32")];case"ShapeN":return p("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(p("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(p("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const a=p("x",e,t,n),o=p("data",e,t,n),i=p("message",e,t,n),u=p("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e((e,t,n,r=Di)=>{switch(e.op){case"Equal":return[r.equal(p("a",e,t,n),p("b",e,t,n))];case"NotEqual":return[r.notEqual(p("a",e,t,n),p("b",e,t,n))];case"Greater":return[r.greater(p("a",e,t,n),p("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(p("a",e,t,n),p("b",e,t,n))];case"Less":return[r.less(p("a",e,t,n),p("b",e,t,n))];case"LessEqual":return[r.lessEqual(p("a",e,t,n),p("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(p("a",e,t,n),p("b",e,t,n))];case"LogicalNot":return[r.logicalNot(p("a",e,t,n))];case"LogicalOr":return[r.logicalOr(p("a",e,t,n),p("b",e,t,n))];case"Select":case"SelectV2":return[r.where(p("condition",e,t,n),p("a",e,t,n),p("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(p("a",e,t,n),p("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"matrices":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(p("a",e,t,n),p("b",e,t,n),p("transposeA",e,t,n),p("transposeB",e,t,n))];case"Einsum":return[r.einsum(p("equation",e,t,n),...p("tensors",e,t,n))];case"Transpose":return[r.transpose(p("x",e,t,n),p("perm",e,t,n))];case"_FusedMatMul":const[s,a]=p("fusedOps",e,t,n),o="biasadd"===s,i="prelu"===a,u=p("numArgs",e,t,n),l=p("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=p("args",e,t,n);return[r.fused.matMul({a:p("a",e,t,n),b:p("b",e,t,n),transposeA:p("transposeA",e,t,n),transposeB:p("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(p("a",e,t,n),p("numLower",e,t,n),p("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"normalization":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(p("x",e,t,n),p("axis",e,t,n),p("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(p("x",e,t,n),p("mean",e,t,n),p("variance",e,t,n),p("offset",e,t,n),p("scale",e,t,n),p("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(p("x",e,t,n),p("radius",e,t,n),p("bias",e,t,n),p("alpha",e,t,n),p("beta",e,t,n))];case"Softmax":return[r.softmax(p("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(p("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"ragged":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:s,outputDenseValues:a}=r.raggedGather(p("paramsNestedSplits",e,t,n),p("paramsDenseValues",e,t,n),p("indices",e,t,n),p("outputRaggedRank",e,t,n));return s.concat(a)}case"RaggedRange":{const{rtNestedSplits:s,rtDenseValues:a}=r.raggedRange(p("starts",e,t,n),p("limits",e,t,n),p("splits",e,t,n));return[s,a]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(p("shape",e,t,n),p("values",e,t,n),p("defaultValue",e,t,n),p("rowPartitionTensors",e,t,n),p("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"reduction":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Max":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.max(p("x",e,t,n),s,a)]}case"Mean":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.mean(p("x",e,t,n),s,a)]}case"Min":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.min(p("x",e,t,n),s,a)]}case"Sum":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.sum(p("x",e,t,n),s,a)]}case"All":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.all(p("x",e,t,n),s,a)]}case"Any":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.any(p("x",e,t,n),s,a)]}case"ArgMax":{const s=p("axis",e,t,n);return[r.argMax(p("x",e,t,n),s)]}case"ArgMin":{const s=p("axis",e,t,n);return[r.argMin(p("x",e,t,n),s)]}case"Prod":{const s=p("axis",e,t,n),a=p("keepDims",e,t,n);return[r.prod(p("x",e,t,n),s,a)]}case"Cumprod":{const s=p("axis",e,t,n),a=p("exclusive",e,t,n),o=p("reverse",e,t,n);return[r.cumprod(p("x",e,t,n),s,a,o)]}case"Cumsum":{const s=p("axis",e,t,n),a=p("exclusive",e,t,n),o=p("reverse",e,t,n);return[r.cumsum(p("x",e,t,n),s,a,o)]}case"Bincount":const s=p("x",e,t,n),a=p("weights",e,t,n),o=p("size",e,t,n);return[r.bincount(s,a,o)];case"DenseBincount":{const s=p("x",e,t,n),a=p("weights",e,t,n),o=p("size",e,t,n),i=p("binaryOutput",e,t,n);return[r.denseBincount(s,a,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"slice_join":return o((()=>((e,n,r,s=Di)=>{switch(e.op){case"ConcatV2":case"Concat":{const t=p("n",e,n,r),a=p("axis",e,n,r);let o=p("tensors",e,n,r);return o=o.slice(0,t),[s.concat(o,a)]}case"Gather":{const t=p("x",e,n,r),a=p("indices",e,n,r);return[s.gather(t,s.cast(a,"int32"),0)]}case"GatherV2":{const t=p("axis",e,n,r),a=p("batchDims",e,n,r),o=p("x",e,n,r),i=p("indices",e,n,r);return[s.gather(o,s.cast(i,"int32"),t,a)]}case"Reverse":{const t=p("dims",e,n,r),a=[];for(let e=0;e{const a=p("axis",e,n,r),o=p("tensors",e,n,r),i=o[0].shape,u=s.squeeze(o[0]).shape,l=o.map((e=>{const n=t.util.arraysEqual(e.shape,i);if(!n&&!t.util.arraysEqual(s.squeeze(e).shape,u))throw new Error("the input tensors shape does not match");return n?e:s.reshape(e,i)}));return[s.stack(l,a)]}));case"Unpack":{const t=p("axis",e,n,r),a=p("tensor",e,n,r);return s.unstack(a,t)}case"Tile":{const t=p("reps",e,n,r);return[s.tile(p("x",e,n,r),t)]}case"Split":case"SplitV":{const t=p("axis",e,n,r),a=p("numOrSizeSplits",e,n,r),o=p("x",e,n,r);return s.split(o,a,t)}case"ScatterNd":{const t=p("indices",e,n,r),a=p("values",e,n,r),o=p("shape",e,n,r);return[s.scatterND(t,a,o)]}case"GatherNd":{const t=p("x",e,n,r),a=p("indices",e,n,r);return[s.gatherND(t,a)]}case"SparseToDense":{const t=p("sparseIndices",e,n,r),a=p("outputShape",e,n,r),o=p("sparseValues",e,n,r),i=p("defaultValue",e,n,r);return[s.sparseToDense(t,o,a,o.dtype===i.dtype?i:s.cast(i,o.dtype))]}case"TensorScatterUpdate":{const t=p("indices",e,n,r),a=p("values",e,n,r),o=p("tensor",e,n,r);return[s.tensorScatterUpdate(o,t,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"sparse":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:s,outputValues:a,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(p("indices",e,t,n),p("values",e,t,n),p("denseShape",e,t,n),p("defaultValue",e,t,n));return[s,a,o,i]}case"SparseReshape":{const{outputIndices:s,outputShape:a}=r.sparse.sparseReshape(p("inputIndices",e,t,n),p("inputShape",e,t,n),p("newShape",e,t,n));return[s,a]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(p("data",e,t,n),p("indices",e,t,n),p("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(p("data",e,t,n),p("indices",e,t,n),p("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"spectral":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"FFT":return[r.fft(p("x",e,t,n))];case"IFFT":return[r.ifft(p("x",e,t,n))];case"RFFT":return[r.rfft(p("x",e,t,n))];case"IRFFT":return[r.irfft(p("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"string":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(p("input",e,t,n),p("pattern",e,t,n),p("rewrite",e,t,n),p("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:s,nGramsSplits:a}=r.string.stringNGrams(p("data",e,t,n),p("dataSplits",e,t,n),p("separator",e,t,n),p("nGramWidths",e,t,n),p("leftPad",e,t,n),p("rightPad",e,t,n),p("padWidth",e,t,n),p("preserveShortSequences",e,t,n));return[s,a]}case"StringSplit":{const{indices:s,values:a,shape:o}=r.string.stringSplit(p("input",e,t,n),p("delimiter",e,t,n),p("skipEmpty",e,t,n));return[s,a,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(p("input",e,t,n),p("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));case"transformation":return o((()=>((e,t,n,r=Di)=>{switch(e.op){case"Cast":return[r.cast(p("x",e,t,n),p("dtype",e,t,n))];case"ExpandDims":{const s=p("axis",e,t,n);return[r.expandDims(p("x",e,t,n),s)]}case"Squeeze":{const s=p("axis",e,t,n);return[r.squeeze(p("x",e,t,n),s)]}case"Reshape":return[r.reshape(p("x",e,t,n),p("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(p("x",e,t,n),p("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(p("x",e,t,n),p("padding",e,t,n),p("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(p("x",e,t,n),p("padding",e,t,n),p("constantValue",e,t,n))];case"SpaceToBatchND":{const s=p("blockShape",e,t,n),a=p("paddings",e,t,n);return[r.spaceToBatchND(p("x",e,t,n),s,a)]}case"BatchToSpaceND":{const s=p("blockShape",e,t,n),a=p("crops",e,t,n);return[r.batchToSpaceND(p("x",e,t,n),s,a)]}case"DepthToSpace":{const s=p("blockSize",e,t,n),a=p("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(p("x",e,t,n),s,a)]}case"BroadcastTo":return[r.broadcastTo(p("x",e,t,n),p("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(p("s0",e,t,n),p("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r)));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=p("keyDType",e,t,n),a=p("valueDType",e,t,n),o=new Pi(s,a);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const s=p("tableHandle",e,t,n,r),a=p("keys",e,t,n),o=p("values",e,t,n),i=r.getHashTableById(s.id);return[await i.import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{const s=p("tableHandle",e,t,n,r),a=p("keys",e,t,n),o=p("defaultValue",e,t,n),i=r.getHashTableById(s.id);return[await i.find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=p("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,n,r,a);case"custom":const s=u(e.op);if(s&&s.customExecutor)return s.customExecutor(new Y(e,n,r));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,n,r);return s.util.isPromise(i)?i.then((e=>[].concat(e))):[].concat(i)}class qi{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;t0===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 Ui(e,t,n,r){const s=new Set,a=[];let o=null,i=null;const u=new Set,p=new Set(Object.keys(e).map((e=>m(e)[0])));r=r||[];const l=new Set(r.map((e=>m(e.name)[0]))),c=[...t];for(;c.length>0;){const e=c.pop();(Qi(e)||Yi(e)||Xi(e))&&null==o&&(o=e,i=o.children.map((e=>e.name)).filter((e=>s.has(e)))),s.add(e.name),null==n[e.name]&&(p.has(e.name)||l.has(e.name)||(0!==e.inputs.length?e.inputs.forEach((e=>{u.has(e.name)||(u.add(e.name),c.push(e))})):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:o,syncInputs:i}}function ji(e,t){const{usedNodes:n,inputs:r}=t,s=Object.keys(r).map((e=>m(e)[0])).map((t=>e.nodes[t])),a=e.initNodes||[],o=e=>n.has("string"==typeof e?e:e.name);function i(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const u=i([...s,...e.weights,...a]).filter(o),p=i([...u,...Object.values(e.nodes)]).filter(o),l=new Map(p.map((e=>[e.name,e]))),c={};for(const e of p){c[e.name]=c[e.name]||0;for(const t of e.children)o(t)||(c[t.name]=Number.POSITIVE_INFINITY),c[t.name]=(c[t.name]||0)+1}const h=Object.entries(c).filter((([,e])=>0===e)).map((([e])=>e)),d=[...h];for(;h.length>0;){const e=h.pop(),t=l.get(e);for(const e of t.children.filter(o))0==--c[e.name]&&(d.push(e.name),h.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)))}(d.map((e=>l.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))),o=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(o)){if(!n.has(e.name))throw new Wi(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new Wi(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!s(t))for(const e of t.inputs){if(!n.has(e.name))throw new Wi(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new Wi(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}class Wi extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const Gi=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Hi=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),Zi=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Qi(e){return Gi.has(e.op)}function Yi(e){return Hi.has(e.op)}function Xi(e){return Zi.has(e.op)}class Ji{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 Ji(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=Ui(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 o=ji(this.graph,n),i=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,r=e.map(((e,t)=>Qi(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]))),o=new Map;for(let t=0;tthis.cloneAndKeepTensor(e)));return t}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,n){this.disposeIntermediateTensors(),e=this.mapInputs(e);const r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),n=this.mapOutputs(n),this.checkOutputs(n);const s=r.map((e=>this.graph.nodes[m(e)[0]])),a=n.map((e=>m(e)[0])),o=new Set(a);let i=a.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const u=this.getCompilationKey(s,i);let p=this.compiledMap.get(u);null==p&&(p=this.compile(e,i),this.compiledMap.set(u,p));try{this.keepIntermediateTensors=t.env().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const c={},h={};return t.tidy((()=>{const r=new qi(this.weightMap,c,h,this.functionExecutorMap,this.parseNodeNameCache),s=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[n,a]=m(t,r),o=[];o[a]=e[t],s[n]=o,this.keepIntermediateTensors&&(this.clonedTensorsMap[n]=this.cloneTensorList(o))}));const a=this.getFrozenTensorIds(s),{orderedNodes:i,nodeLiveUntilMap:u}=p;for(const e of i){if(s[e.name])continue;const n=Ki(e,s,r,this._resourceManager);if(t.util.isPromise(n))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);s[e.name]=n,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(n)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,s,r,a,o,u.get(e.name))}return null==this.parent&&r.dispose(a),n.map((e=>l(e,s,r)))}))}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,o){if(!Qi(t)&&!a.has(e)){for(const r of n[e])null!=r&&(o[r.id]=(o[r.id]||0)+t.children.length);for(const e of t.inputs){if(Qi(e))continue;const t=c(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||s.has(e.id))continue;const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,s,a){function o(e){return Qi(e)||s.has(e.name)}if(!Qi(e)&&null!=a)for(const e of a){if(o(e))continue;const s=c(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,n,r=!1,s={},a={}){this.disposeIntermediateTensors(),r||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),n=this.mapOutputs(n),this.checkOutputs(n));try{this.keepIntermediateTensors=t.env().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const o=new qi(this.weightMap,s,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,o,n,r),u=n.map((e=>l(e,i,o))),p=u.map((e=>e.id)),c=Object.keys(e).map((t=>e[t].id)),h=new Set([...p,...c,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||h.has(e.id)||e.dispose()}))})),null==this.parent&&o.dispose(h),u}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[m(e)[0]])),o=n.map((e=>m(e)[0])),i=new Set(o);let u=o.map((e=>this.graph.nodes[e]));0===u.length&&(u=this._outputs);const{usedNodes:p,missingInputs:c,dynamicNode:h,syncInputs:d}=Ui(e,u,this.weightMap,this._initNodes),f=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),y=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=m(t),s=[];s[r]=e[t],y[n]=s}));const g={},b=this.getFrozenTensorIds(y),x={};for(;f.length>0;){const e=this.processStack(a,f,t,y,x,b,i,g,p);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 N=u.filter((e=>!Qi(e)&&!l(e.name,y,t))).map((e=>e.name));if(N.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 [${N}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${e}`)}return y}processStack(e,n,r,s,a,o,i,u,l){const c=[];for(;n.length>0;){const e=n.pop();r.currentContext=e.contexts;let d="";if("Enter"===e.node.op&&p("isConstant",e.node,s,r)&&([d]=h(e.node.name,r)),null==s[e.node.name]){const p=Ki(e.node,s,r,this._resourceManager);d||([d]=h(e.node.name,r));const m=r.currentContext;t.util.isPromise(p)?c.push(p.then((t=>(s[d]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(t)),r.currentContext=m,this.checkTensorForDisposal(d,e.node,s,r,o,i,u),this.processChildNodes(e.node,n,r,s,a,l),t)))):(s[d]=p,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(p)),this.checkTensorForDisposal(d,e.node,s,r,o,i,u),this.processChildNodes(e.node,n,r,s,a,l))}else this.processChildNodes(e.node,n,r,s,a,l)}return c}processChildNodes(e,t,n,r,s,a){e.children.forEach((e=>{const[o]=h(e.name,n);!s[o]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!l(e,r,n)))&&(s[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!l(e,r,n)))&&(s[o]=!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((n=>{const r=e[n],[s]=m(n),a=this.graph.nodes[s];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value,n=e.length===r.shape.length&&r.shape.every(((t,n)=>-1===e[n]||e[n]===t));t.util.assert(n,(()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${r.shape}]`))}a.attrParams.dtype&&a.attrParams.dtype.value&&t.util.assert(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,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]=m(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]=m(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class eu{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 tu={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};async function nu(e,t){const n=ne(e.shape);let r;if("quantization"in e){const t=e.quantization;r=tu[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r{let t=e<<13,n=0;for(;0==(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>10]+(1023&o)]+t[o>>10];a[s]=i}return new Float32Array(s)}}();o=e(p)}}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.`);o=new Int32Array(p.length);for(let e=0;e1)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 t.util.isPromise(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 async function(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await nu(e,(async(e,t)=>(s=await su(r,s,t),s.slice(e,t))));s=await su(r,s,t);const a=s.slice(0,t);s=s.slice(t);const o=ru(e,a);if(n[e.name]=o,"webgpu"===Qt.backendName){const e=Qt.backend;"uploadToGPU"in e&&ne(o.shape)>=ke().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}(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 Ji(R.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=R.Instance.transformGraph(e.modelInitializer);this.initializer=new Ji(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 n=e instanceof t.Tensor?[e]:e,r={};return n.forEach(((e,t)=>r[this.structuredOutputKeys[t]]=e)),r}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 n;if(!(e instanceof t.Tensor||Array.isArray(e))){const t=null===(n=this.signature)||void 0===n?void 0:n.inputs;if(null!=t)for(const n in t){const r=t[n];null!=r.resourceId&&(e[n]=this.resourceIdToCapturedInput[r.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(((t,n)=>{var r,a,o;const i=null===(o=null===(a=null===(r=this.signature)||void 0===r?void 0:r.inputs)||void 0===a?void 0:a[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[s++],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;r1?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&&t.dispose(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}e.GraphModel=au,e.deregisterOp=function(e){delete i[e]},e.loadGraphModel=async function(e,n={},r=t.io){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==n&&(n={}),n.fromTFHub&&"string"==typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}model.json?tfjs-format=file`}(e));const s=new au(e,n,r);return await s.load(),s},e.loadGraphModelSync=function(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 n;if(e instanceof Array){const[r,s]=e;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'");if(!("weightsManifest"in r))throw new Error("Model JSON is missing 'weightsManifest'");const a=t.io.getWeightSpecs(r.weightsManifest),o=t.io.getModelArtifactsForJSONSync(r,a,s);n=t.io.fromMemorySync(o)}else if("load"in e)n=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");n=t.io.fromMemorySync(e)}const r=new au(n);return r.load(),r},e.registerOp=function(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};i[e]=n},e.version_converter="4.15.0"})); //# sourceMappingURL=tf-converter.es2017.min.js.map