diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..cd49efe --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# AR Photobooth diff --git a/index.html b/index.html new file mode 100644 index 0000000..f41ac90 --- /dev/null +++ b/index.html @@ -0,0 +1,72 @@ + + + + + + Google I/O Extended Hanoi 2024 | AR Photobooth + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/css/style.css b/static/css/style.css new file mode 100644 index 0000000..5c0cce4 --- /dev/null +++ b/static/css/style.css @@ -0,0 +1,28 @@ +@import url("https://fonts.googleapis.com/css2?family=Inter&display=swap"); + +body { + font-family: -apple-system, BlinkMacSystemFont, "Inter", sans-serif; +} + +a { + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +#screenshot { + border-radius: 50%; + width: 25%; + max-width: 48px; + aspect-ratio: 1; + position: fixed; + z-index: 2; + bottom: 2rem; + cursor: pointer; + right: 50dvw; + left: 50dvw; + border: 5px solid; + transform: translateX(-50%); +} diff --git a/static/gifs/firebase.gif b/static/gifs/firebase.gif new file mode 100644 index 0000000..91ad8d9 Binary files /dev/null and b/static/gifs/firebase.gif differ diff --git a/static/gifs/flutter.gif b/static/gifs/flutter.gif new file mode 100644 index 0000000..48eb36a Binary files /dev/null and b/static/gifs/flutter.gif differ diff --git a/static/gifs/gdg.gif b/static/gifs/gdg.gif new file mode 100644 index 0000000..b9a8c40 Binary files /dev/null and b/static/gifs/gdg.gif differ diff --git a/static/gifs/io.gif b/static/gifs/io.gif new file mode 100644 index 0000000..8ba3814 Binary files /dev/null and b/static/gifs/io.gif differ diff --git a/static/gifs/random.gif b/static/gifs/random.gif new file mode 100644 index 0000000..ba6e485 Binary files /dev/null and b/static/gifs/random.gif differ diff --git a/static/js/build/aframe-gif-shader.js b/static/js/build/aframe-gif-shader.js new file mode 100644 index 0000000..d27d93b --- /dev/null +++ b/static/js/build/aframe-gif-shader.js @@ -0,0 +1,680 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + + var _gifsparser = __webpack_require__(1); + + if (typeof AFRAME === 'undefined') { + throw 'Component attempted to register before AFRAME was available.'; + } + + /* get util from AFRAME */ + var parseUrl = AFRAME.utils.srcLoader.parseUrl; + var debug = AFRAME.utils.debug; + // debug.enable('shader:gif:*') + + debug.enable('shader:gif:warn'); + var warn = debug('shader:gif:warn'); + var log = debug('shader:gif:debug'); + + /* store data so that you won't load same data */ + var gifData = {}; + + /* create error message */ + function createError(err, src) { + return { status: 'error', src: src, message: err, timestamp: Date.now() }; + } + + AFRAME.registerShader('gif', { + + /** + * For material component: + * @see https://github.com/aframevr/aframe/blob/60d198ef8e2bfbc57a13511ae5fca7b62e01691b/src/components/material.js + * For example of `registerShader`: + * @see https://github.com/aframevr/aframe/blob/41a50cd5ac65e462120ecc2e5091f5daefe3bd1e/src/shaders/flat.js + * For MeshBasicMaterial + * @see http://threejs.org/docs/#Reference/Materials/MeshBasicMaterial + */ + + schema: { + + /* For material */ + color: { type: 'color' }, + fog: { default: true }, + + /* For texuture */ + src: { default: null }, + autoplay: { default: true } + + }, + + /** + * Initialize material. Called once. + * @protected + */ + init: function init(data) { + log('init', data); + log(this.el.components); + this.__cnv = document.createElement('canvas'); + this.__cnv.width = 2; + this.__cnv.height = 2; + this.__ctx = this.__cnv.getContext('2d'); + this.__texture = new THREE.Texture(this.__cnv); //renders straight from a canvas + this.__material = {}; + this.__reset(); + this.material = new THREE.MeshBasicMaterial({ map: this.__texture }); + this.el.sceneEl.addBehavior(this); + this.__addPublicFunctions(); + return this.material; + }, + + + /** + * Update or create material. + * @param {object|null} oldData + */ + update: function update(oldData) { + log('update', oldData); + this.__updateMaterial(oldData); + this.__updateTexture(oldData); + return this.material; + }, + + + /** + * Called on each scene tick. + * @protected + */ + tick: function tick(t) { + if (!this.__frames || this.paused()) return; + if (Date.now() - this.__startTime >= this.__nextFrameTime) { + this.nextFrame(); + } + }, + + + /*================================ + = material = + ================================*/ + + /** + * Updating existing material. + * @param {object} data - Material component data. + */ + __updateMaterial: function __updateMaterial(data) { + var material = this.material; + + var newData = this.__getMaterialData(data); + Object.keys(newData).forEach(function (key) { + material[key] = newData[key]; + }); + }, + + + /** + * Builds and normalize material data, normalizing stuff along the way. + * @param {Object} data - Material data. + * @return {Object} data - Processed material data. + */ + __getMaterialData: function __getMaterialData(data) { + return { + fog: data.fog, + color: new THREE.Color(data.color) + }; + }, + + + /*============================== + = texure = + ==============================*/ + + /** + * set texure + * @private + * @param {Object} data + * @property {string} status - success / error + * @property {string} src - src url + * @property {array} times - array of time length of each image + * @property {number} cnt - total counts of gif images + * @property {array} frames - array of each image + * @property {Date} timestamp - created at the texure + */ + + __setTexure: function __setTexure(data) { + log('__setTexure', data); + if (data.status === 'error') { + warn('Error: ' + data.message + '\nsrc: ' + data.src); + this.__reset(); + } else if (data.status === 'success' && data.src !== this.__textureSrc) { + this.__reset(); + /* Texture added or changed */ + this.__ready(data); + } + }, + + + /** + * Update or create texure. + * @param {Object} data - Material component data. + */ + __updateTexture: function __updateTexture(data) { + var src = data.src; + var autoplay = data.autoplay; + + /* autoplay */ + + if (typeof autoplay === 'boolean') { + this.__autoplay = autoplay; + } else if (typeof autoplay === 'undefined') { + this.__autoplay = true; + } + if (this.__autoplay && this.__frames) { + this.play(); + } + + /* src */ + if (src) { + this.__validateSrc(src, this.__setTexure.bind(this)); + } else { + /* Texture removed */ + this.__reset(); + } + }, + + + /*============================================= + = varidation for texure = + =============================================*/ + + __validateSrc: function __validateSrc(src, cb) { + + /* check if src is a url */ + var url = parseUrl(src); + if (url) { + this.__getImageSrc(url, cb); + return; + } + + var message = void 0; + + /* check if src is a query selector */ + var el = this.__validateAndGetQuerySelector(src); + if (!el || (typeof el === 'undefined' ? 'undefined' : _typeof(el)) !== 'object') { + return; + } + if (el.error) { + message = el.error; + } else { + var tagName = el.tagName.toLowerCase(); + if (tagName === 'video') { + src = el.src; + message = 'For video, please use `aframe-video-shader`'; + } else if (tagName === 'img') { + this.__getImageSrc(el.src, cb); + return; + } else { + message = 'For <' + tagName + '> element, please use `aframe-html-shader`'; + } + } + + /* if there is message, create error data */ + if (message) { + (function () { + var srcData = gifData[src]; + var errData = createError(message, src); + /* callbacks */ + if (srcData && srcData.callbacks) { + srcData.callbacks.forEach(function (cb) { + return cb(errData); + }); + } else { + cb(errData); + } + /* overwrite */ + gifData[src] = errData; + })(); + } + }, + + + /** + * Validate src is a valid image url + * @param {string} src - url that will be tested + * @param {function} cb - callback with the test result + */ + __getImageSrc: function __getImageSrc(src, cb) { + var _this = this; + + /* if src is same as previous, ignore this */ + if (src === this.__textureSrc) { + return; + } + + /* check if we already get the srcData */ + var srcData = gifData[src]; + if (!srcData || !srcData.callbacks) { + /* create callback */ + srcData = gifData[src] = { callbacks: [] }; + srcData.callbacks.push(cb); + } else if (srcData.src) { + cb(srcData); + return; + } else if (srcData.callbacks) { + /* add callback */ + srcData.callbacks.push(cb); + return; + } + var tester = new Image(); + tester.crossOrigin = 'Anonymous'; + tester.addEventListener('load', function (e) { + /* check if it is gif */ + _this.__getUnit8Array(src, function (arr) { + if (!arr) { + onError('This is not gif. Please use `shader:flat` instead'); + return; + } + /* parse data */ + (0, _gifsparser.parseGIF)(arr, function (times, cnt, frames) { + /* store data */ + var newData = { status: 'success', src: src, times: times, cnt: cnt, frames: frames, timestamp: Date.now() }; + /* callbacks */ + if (srcData.callbacks) { + srcData.callbacks.forEach(function (cb) { + return cb(newData); + }); + /* overwrite */ + gifData[src] = newData; + } + }, function (err) { + return onError(err); + }); + }); + }); + tester.addEventListener('error', function (e) { + return onError('Could be the following issue\n - Not Image\n - Not Found\n - Server Error\n - Cross-Origin Issue'); + }); + function onError(message) { + /* create error data */ + var errData = createError(message, src); + /* callbacks */ + if (srcData.callbacks) { + srcData.callbacks.forEach(function (cb) { + return cb(errData); + }); + /* overwrite */ + gifData[src] = errData; + } + } + tester.src = src; + }, + + + /** + * + * get mine type + * + */ + __getUnit8Array: function __getUnit8Array(src, cb) { + if (typeof cb !== 'function') { + return; + } + + var xhr = new XMLHttpRequest(); + xhr.open('GET', src); + xhr.responseType = 'arraybuffer'; + xhr.addEventListener('load', function (e) { + var uint8Array = new Uint8Array(e.target.response); + var arr = uint8Array.subarray(0, 4); + // const header = arr.map(value => value.toString(16)).join('') + var header = ''; + for (var i = 0; i < arr.length; i++) { + header += arr[i].toString(16); + } + if (header === '47494638') { + cb(uint8Array); + } else { + cb(); + } + }); + xhr.addEventListener('error', function (e) { + log(e); + cb(); + }); + xhr.send(); + }, + + + /** + * Query and validate a query selector, + * + * @param {string} selector - DOM selector. + * @return {object} Selected DOM element | error message object. + */ + __validateAndGetQuerySelector: function __validateAndGetQuerySelector(selector) { + try { + var el = document.querySelector(selector); + if (!el) { + return { error: 'No element was found matching the selector' }; + } + return el; + } catch (e) { + // Capture exception if it's not a valid selector. + return { error: 'no valid selector' }; + } + }, + + + /*================================ + = playback = + ================================*/ + + /** + * add public functions + * @private + */ + __addPublicFunctions: function __addPublicFunctions() { + this.el.gif = { + play: this.play.bind(this), + pause: this.pause.bind(this), + togglePlayback: this.togglePlayback.bind(this), + paused: this.paused.bind(this), + nextFrame: this.nextFrame.bind(this) + }; + }, + + + /** + * Pause gif + * @public + */ + pause: function pause() { + log('pause'); + this.__paused = true; + }, + + + /** + * Play gif + * @public + */ + play: function play() { + log('play'); + this.__paused = false; + }, + + + /** + * Toggle playback. play if paused and pause if played. + * @public + */ + + togglePlayback: function togglePlayback() { + + if (this.paused()) { + this.play(); + } else { + this.pause(); + } + }, + + + /** + * Return if the playback is paused. + * @public + * @return {boolean} + */ + paused: function paused() { + return this.__paused; + }, + + + /** + * Go to next frame + * @public + */ + nextFrame: function nextFrame() { + // Tusss fix + // https://github.com/mayognaise/aframe-gif-shader/issues/14#issuecomment-1344277706 + this.__clearCanvas(); + this.__draw(); + + /* update next frame time */ + while (Date.now() - this.__startTime >= this.__nextFrameTime) { + + this.__nextFrameTime += this.__delayTimes[this.__frameIdx++]; + if ((this.__infinity || this.__loopCnt) && this.__frameCnt <= this.__frameIdx) { + /* go back to the first */ + this.__frameIdx = 0; + } + } + }, + + + /*============================== + = canvas = + ==============================*/ + + /** + * clear canvas + * @private + */ + __clearCanvas: function __clearCanvas() { + this.__ctx.clearRect(0, 0, this.__width, this.__height); + this.__texture.needsUpdate = true; + }, + + + /** + * draw + * @private + */ + __draw: function __draw() { + this.__ctx.drawImage(this.__frames[this.__frameIdx], 0, 0, this.__width, this.__height); + this.__texture.needsUpdate = true; + }, + + + /*============================ + = ready = + ============================*/ + + /** + * setup gif animation and play if autoplay is true + * @private + * @property {string} src - src url + * @param {array} times - array of time length of each image + * @param {number} cnt - total counts of gif images + * @param {array} frames - array of each image + */ + __ready: function __ready(_ref) { + var src = _ref.src; + var times = _ref.times; + var cnt = _ref.cnt; + var frames = _ref.frames; + + log('__ready'); + this.__textureSrc = src; + this.__delayTimes = times; + cnt ? this.__loopCnt = cnt : this.__infinity = true; + this.__frames = frames; + this.__frameCnt = times.length; + this.__startTime = Date.now(); + this.__width = THREE.Math.floorPowerOfTwo(frames[0].width); + this.__height = THREE.Math.floorPowerOfTwo(frames[0].height); + this.__cnv.width = this.__width; + this.__cnv.height = this.__height; + this.__draw(); + if (this.__autoplay) { + this.play(); + } else { + this.pause(); + } + }, + + + /*============================= + = reset = + =============================*/ + + /** + * @private + */ + + __reset: function __reset() { + this.pause(); + this.__clearCanvas(); + this.__startTime = 0; + this.__nextFrameTime = 0; + this.__frameIdx = 0; + this.__frameCnt = 0; + this.__delayTimes = null; + this.__infinity = false; + this.__loopCnt = 0; + this.__frames = null; + this.__textureSrc = null; + } + }); + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + 'use strict'; + + /** + * + * Gif parser by @gtk2k + * https://github.com/gtk2k/gtk2k.github.io/tree/master/animation_gif + * + */ + + exports.parseGIF = function (gif, successCB, errorCB) { + + var pos = 0; + var delayTimes = []; + var loadCnt = 0; + var graphicControl = null; + var imageData = null; + var frames = []; + var loopCnt = 0; + if (gif[0] === 0x47 && gif[1] === 0x49 && gif[2] === 0x46 && // 'GIF' + gif[3] === 0x38 && gif[4] === 0x39 && gif[5] === 0x61) { + // '89a' + pos += 13 + +!!(gif[10] & 0x80) * Math.pow(2, (gif[10] & 0x07) + 1) * 3; + var gifHeader = gif.subarray(0, pos); + while (gif[pos] && gif[pos] !== 0x3b) { + var offset = pos, + blockId = gif[pos]; + if (blockId === 0x21) { + var label = gif[++pos]; + if ([0x01, 0xfe, 0xf9, 0xff].indexOf(label) !== -1) { + label === 0xf9 && delayTimes.push((gif[pos + 3] + (gif[pos + 4] << 8)) * 10); + label === 0xff && (loopCnt = gif[pos + 15] + (gif[pos + 16] << 8)); + while (gif[++pos]) { + pos += gif[pos]; + }label === 0xf9 && (graphicControl = gif.subarray(offset, pos + 1)); + } else { + errorCB && errorCB('parseGIF: unknown label');break; + } + } else if (blockId === 0x2c) { + pos += 9; + pos += 1 + +!!(gif[pos] & 0x80) * (Math.pow(2, (gif[pos] & 0x07) + 1) * 3); + while (gif[++pos]) { + pos += gif[pos]; + }var imageData = gif.subarray(offset, pos + 1); + frames.push(URL.createObjectURL(new Blob([gifHeader, graphicControl, imageData]))); + } else { + errorCB && errorCB('parseGIF: unknown blockId');break; + } + pos++; + } + } else { + errorCB && errorCB('parseGIF: no GIF89a'); + } + if (frames.length) { + + var cnv = document.createElement('canvas'); + var loadImg = function loadImg() { + frames.forEach(function (src, i) { + var img = new Image(); + img.onload = function (e, i) { + if (i === 0) { + cnv.width = img.width; + cnv.height = img.height; + } + loadCnt++; + frames[i] = this; + if (loadCnt === frames.length) { + loadCnt = 0; + imageFix(1); + } + }.bind(img, null, i); + img.src = src; + }); + }; + var imageFix = function imageFix(i) { + var img = new Image(); + img.onload = function (e, i) { + loadCnt++; + frames[i] = this; + if (loadCnt === frames.length) { + cnv = null; + successCB && successCB(delayTimes, loopCnt, frames); + } else { + imageFix(++i); + } + }.bind(img); + img.src = cnv.toDataURL('image/gif'); + }; + loadImg(); + } + }; + +/***/ } +/******/ ]); diff --git a/static/js/build/mindar-image-aframe.prod.js b/static/js/build/mindar-image-aframe.prod.js new file mode 100644 index 0000000..4542eef --- /dev/null +++ b/static/js/build/mindar-image-aframe.prod.js @@ -0,0 +1,20756 @@ +(function(){"use strict";function YI(n,t){for(var e=0;es[o]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QI=1e-7,JI=1e-4;class lf{constructor(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}get(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)}set(t,e){this.dataIdsCount++,this.data.set(t,e)}has(t){return this.data.has(t)}delete(t){return this.dataIdsCount--,this.data.delete(t)}numDataIds(){return this.dataIdsCount}}class Zl{refCount(t){return Ze("refCount")}incRef(t){return Ze("incRef")}timerAvailable(){return!0}time(t){return Ze("time")}read(t){return Ze("read")}readSync(t){return Ze("readSync")}readToGPU(t,e){return Ze("readToGPU")}numDataIds(){return Ze("numDataIds")}disposeData(t,e){return Ze("disposeData")}write(t,e,s){return Ze("write")}move(t,e,s,o,r){return Ze("move")}createTensorFromGPUData(t,e,s){return Ze("createTensorFromGPUData")}memory(){return Ze("memory")}floatPrecision(){return Ze("floatPrecision")}epsilon(){return this.floatPrecision()===32?QI:JI}dispose(){return Ze("dispose")}}function Ze(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jI(n){let t=n.length,e=0;for(;t>0;)e=Math.random()*t|0,t--,Eo(n,t,e)}function Ks(n,t,e){return Math.max(n,Math.min(t,e))}function Bl(n){return n%2===0?n:n+1}function Eo(n,t,e){const s=n[t];n[t]=n[e],n[e]=s}function qI(n){let t=0;for(let e=0;ee+` Shapes ${n} and ${t} must match`)}function _l(n){v(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Z(n){if(n.length===0)return 1;let t=n[0];for(let e=1;e0,e,s){return new Promise((o,r)=>{let i=0;const a=()=>{if(n()){o();return}i++;const c=t(i);if(e!=null&&i>=e){r();return}s!=null?s(a,c):setTimeout(a,c)};a()})}function df(n,t){let e=1,s=-1;for(let r=0;r=0)e*=n[r];else if(n[r]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${r}`);s=r}else if(n[r]<0)throw Error(`Shapes can not be < 0. Found ${n[r]} at dim ${r}`);if(s===-1){if(t>0&&t!==e)throw Error(`Size(${t}) must match the product of shape ${n}`);return n}if(e===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(t%e!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);const o=n.slice();return o[s]=t/e,o}function It(n,t){const e=t.length;return n=n==null?t.map((s,o)=>o):[].concat(n),v(n.every(s=>s>=-e&&s`All values in axis param must be in range [-${e}, ${e}) but got axis ${n}`),v(n.every(s=>Do(s)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(s=>s<0?e+s:s)}function fs(n,t){const e=[],s=[],o=t!=null&&Array.isArray(t)&&t.length===0,r=t==null||o?null:It(t,n).sort();let i=0;for(let a=0;aa)&&n[a]===1&&(e.push(n[a]),s.push(a)),r[i]<=a&&i++}n[a]!==1&&(e.push(n[a]),s.push(a))}return{newShape:e,keptDims:s}}function Se(n,t){return qt(n,t)}function qt(n,t){let e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else if(n==="string")e=new Array(t);else throw new Error(`Unknown data type ${n}`);return e}function tw(n,t){for(let e=0;et+=e.length),t}function Cr(n){return typeof n=="string"||n instanceof String}function sw(n){return typeof n=="boolean"}function Yl(n){return typeof n=="number"}function Mo(n){return Array.isArray(n)?Mo(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":Yl(n)?"float32":Cr(n)?"string":sw(n)?"bool":"float32"}function Ql(n){return!!(n&&n.constructor&&n.call&&n.apply)}function Jl(n,t){for(let e=t;e=0;--s)e[s]=e[s+1]*n[s+1];return e}function pf(n,t,e,s=!1){const o=new Array;if(t.length===1){const r=t[0]*(s?2:1);for(let i=0;ic*l)*(s?2:1);for(let c=0;co*r)*(e?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${n}] does not match the input size ${t.length}${e?" for a complex tensor":""}.`);return pf(0,n,t,e)}function ow(n,t){if(Array.isArray(n))return n;if(t==="float32")return n instanceof Float32Array?n:new Float32Array(n);if(t==="int32")return n instanceof Int32Array?n:new Int32Array(n);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${t}`)}function jl(n,t){const e=ke(n,t);for(let s=0;ss*o,1);if(t==null||t==="float32")return vn(n,new Float32Array(e));if(t==="int32")return vn(n,new Int32Array(e));if(t==="bool")return vn(n,new Uint8Array(e));throw new Error(`Unknown data type ${t}`)}function es(n){n.forEach(t=>{v(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Fn(n,t,e){if(t===0)return 0;if(t===1)return n[0];let s=n[n.length-1];for(let o=0;o"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const t=this.getQueryParams(this.global.location.search);mf in t&&t[mf].split(",").forEach(s=>{const[o,r]=s.split(":");this.urlFlags[o]=cw(o,r)})}}function iw(n){const t={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...s)=>(aw(t,s[0],s[1]),s.join("="))),t}function aw(n,t,e){n[decodeURIComponent(t)]=decodeURIComponent(e||"")}function cw(n,t){const e=t.toLowerCase();return e==="true"||e==="false"?e==="true":`${+e}`===e?+e:t}function z(){return gf}let gf=null;function lw(n){gf=n}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let tu;function bf(){if(tu==null){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else if(typeof self<"u")n=self;else throw new Error("Could not find a global object");tu=n}return tu}function uw(){const n=bf();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function eu(n,t){const e=uw();if(e.has(n))return e.get(n);{const s=t();return e.set(n,s),e.get(n)}}const ya="Abs",vr="Acos",Sr="Acosh",Fo="Add",nu="AddN",su="All",ou="Any",Ia="ArgMax",wa="ArgMin",kr="Asin",Tr="Asinh",Nr="Atan",Rr="Atanh",$r="Atan2",Ca="AvgPool",ru="AvgPoolGrad",va="AvgPool3D",iu="AvgPool3DGrad",Sa="BatchMatMul",ka="BatchToSpaceND",au="Bincount",cu="BitwiseAnd",dw="BroadcastTo",xf="BroadcastArgs",Gr="Cast",Lr="Ceil",Er="ClipByValue",lu="Complex",Ta="ComplexAbs",Na="Concat",Ra="Conv2D",uu="Conv2DBackpropFilter",$a="Conv2DBackpropInput",Ga="Conv3D",du="Conv3DBackpropFilterV2",hu="Conv3DBackpropInputV2",Dr="Cos",Wr="Cosh",pu="Cumprod",La="Cumsum",fu="CropAndResize",mu="DenseBincount",gu="DepthToSpace",Ea="DepthwiseConv2dNative",bu="DepthwiseConv2dNativeBackpropFilter",xu="DepthwiseConv2dNativeBackpropInput",yf="Diag",Da="Dilation2D",yu="Dilation2DBackpropInput",Iu="Dilation2DBackpropFilter",hw="Draw",Mr="RealDiv",wu="Einsum",Vr="Elu",Cu="EluGrad",Fr="Erf",Wa="Equal",zr="Exp",Ma="ExpandDims",Xr="Expm1",vu="FFT",Su="Fill",ku="FlipLeftRight",Ar="Floor",Pr="FloorDiv",Va="FusedBatchNorm",Fa="GatherV2",If="GatherNd",za="Greater",Or="GreaterEqual",Kr="Identity",Tu="IFFT",Nu="Imag",Zr="IsFinite",Br="IsInf",Hr="IsNan",Xa="LeakyRelu",Aa="Less",Pa="LessEqual",wf="LinSpace",_r="Log",Ur="Log1p",Oa="LogicalAnd",Ka="LogicalNot",Za="LogicalOr",pw="LogSoftmax",Ba="LRN",Ru="LRNGrad",Ha="Max",Yr="Maximum",_a="MaxPool",$u="MaxPoolGrad",Ua="MaxPool3D",Gu="MaxPool3DGrad",Cf="MaxPoolWithArgmax",Ya="Mean",Qa="Min",Qr="Minimum",Ja="MirrorPad",Jr="Mod",vf="Multinomial",jr="Multiply",ja="Neg",qa="NotEqual",Lu="NonMaxSuppressionV3",Eu="NonMaxSuppressionV4",Du="NonMaxSuppressionV5",tc="OnesLike",ec="OneHot",nc="Pack",sc="PadV2",qr="Pow",oc="Prelu",rc="Prod",Sf="RaggedGather",kf="RaggedRange",Tf="RaggedTensorToTensor",Wu="Range",Mu="Real",ti="Reciprocal",ei="Relu",ic="Reshape",ac="ResizeNearestNeighbor",Vu="ResizeNearestNeighborGrad",cc="ResizeBilinear",Fu="ResizeBilinearGrad",ni="Relu6",lc="Reverse",si="Round",oi="Rsqrt",Nf="ScatterNd",Rf="TensorScatterUpdate",$f="SearchSorted",uc="Select",ri="Selu",dc="Slice",ii="Sin",ai="Sinh",ci="Sign",li="Sigmoid",ui="Softplus",di="Sqrt",hc="Sum",pc="SpaceToBatchND",fc="SplitV",mc="Softmax",Gf="SparseFillEmptyRows",Lf="SparseReshape",Ef="SparseSegmentMean",Df="SparseSegmentSum",Wf="SparseToDense",hi="SquaredDifference",zu="Square",Xu="StaticRegexReplace",Au="StridedSlice",Mf="StringNGrams",Vf="StringSplit",Ff="StringToHashBucketFast",pi="Sub",fi="Tan",mi="Tanh",gi="Tile",Pu="TopK",Ou="Transform",zo="Transpose",Ku="Unique",gc="Unpack",bc="UnsortedSegmentSum",xc="ZerosLike",bi="Step",Zu="FromPixels",Bu="RotateWithOffset",yc="_FusedMatMul",Ic="FusedConv2D",zf="FusedDepthwiseConv2D";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function je(...n){z().getBool("IS_TEST")||z().getBool("PROD")||console.warn(...n)}function fw(...n){z().getBool("IS_TEST")||z().getBool("PROD")||console.log(...n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wc=eu("kernelRegistry",()=>new Map),Hu=eu("gradRegistry",()=>new Map);function _u(n,t){const e=Pf(n,t);return wc.get(e)}function Xf(n){return Hu.get(n)}function Af(n){const t=wc.entries(),e=[];for(;;){const{done:s,value:o}=t.next();if(s)break;const[r,i]=o,[a]=r.split("_");a===n&&e.push(i)}return e}function qe(n){const{kernelName:t,backendName:e}=n,s=Pf(t,e);wc.has(s)&&je(`The kernel '${t}' for backend '${e}' is already registered`),wc.set(s,n)}function mw(n){const{kernelName:t}=n;Hu.has(t)&&z().getBool("DEBUG")&&je(`Overriding the gradient for '${t}'`),Hu.set(t,n)}function Pf(n,t){return`${t}_${n}`}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Of(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var Zs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gw(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function bw(n){if(n.__esModule)return n;var t=n.default;if(typeof t=="function"){var e=function s(){return this instanceof s?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};e.prototype=t.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(n).forEach(function(s){var o=Object.getOwnPropertyDescriptor(n,s);Object.defineProperty(e,s,o.get?o:{enumerable:!0,get:function(){return n[s]}})}),e}var Kf=Kt,ln=null;try{ln=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Kt(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}Kt.prototype.__isLong__,Object.defineProperty(Kt.prototype,"__isLong__",{value:!0});function Be(n){return(n&&n.__isLong__)===!0}Kt.isLong=Be;var Zf={},Bf={};function Bs(n,t){var e,s,o;return t?(n>>>=0,(o=0<=n&&n<256)&&(s=Bf[n],s)?s:(e=Zt(n,(n|0)<0?-1:0,!0),o&&(Bf[n]=e),e)):(n|=0,(o=-128<=n&&n<128)&&(s=Zf[n],s)?s:(e=Zt(n,n<0?-1:0,!1),o&&(Zf[n]=e),e))}Kt.fromInt=Bs;function un(n,t){if(isNaN(n))return t?Hs:dn;if(t){if(n<0)return Hs;if(n>=_f)return jf}else{if(n<=-Uf)return He;if(n+1>=Uf)return Jf}return n<0?un(-n,t).neg():Zt(n%Xo|0,n/Xo|0,t)}Kt.fromNumber=un;function Zt(n,t,e){return new Kt(n,t,e)}Kt.fromBits=Zt;var Cc=Math.pow;function Uu(n,t,e){if(n.length===0)throw Error("empty string");if(n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return dn;if(typeof t=="number"?(e=t,t=!1):t=!!t,e=e||10,e<2||360)throw Error("interior hyphen");if(s===0)return Uu(n.substring(1),t,e).neg();for(var o=un(Cc(e,8)),r=dn,i=0;i>>0:this.low},et.toNumber=function(){return this.unsigned?(this.high>>>0)*Xo+(this.low>>>0):this.high*Xo+(this.low>>>0)},et.toString=function(t){if(t=t||10,t<2||36>>0,u=l.toString(t);if(i=c,i.isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},et.getHighBits=function(){return this.high},et.getHighBitsUnsigned=function(){return this.high>>>0},et.getLowBits=function(){return this.low},et.getLowBitsUnsigned=function(){return this.low>>>0},et.getNumBitsAbs=function(){if(this.isNegative())return this.eq(He)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0},et.isOdd=function(){return(this.low&1)===1},et.isEven=function(){return(this.low&1)===0},et.equals=function(t){return Be(t)||(t=Sn(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},et.eq=et.equals,et.notEquals=function(t){return!this.eq(t)},et.neq=et.notEquals,et.ne=et.notEquals,et.lessThan=function(t){return this.comp(t)<0},et.lt=et.lessThan,et.lessThanOrEqual=function(t){return this.comp(t)<=0},et.lte=et.lessThanOrEqual,et.le=et.lessThanOrEqual,et.greaterThan=function(t){return this.comp(t)>0},et.gt=et.greaterThan,et.greaterThanOrEqual=function(t){return this.comp(t)>=0},et.gte=et.greaterThanOrEqual,et.ge=et.greaterThanOrEqual,et.compare=function(t){if(Be(t)||(t=Sn(t)),this.eq(t))return 0;var e=this.isNegative(),s=t.isNegative();return e&&!s?-1:!e&&s?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},et.comp=et.compare,et.negate=function(){return!this.unsigned&&this.eq(He)?He:this.not().add(Ao)},et.neg=et.negate,et.add=function(t){Be(t)||(t=Sn(t));var e=this.high>>>16,s=this.high&65535,o=this.low>>>16,r=this.low&65535,i=t.high>>>16,a=t.high&65535,c=t.low>>>16,l=t.low&65535,u=0,d=0,h=0,p=0;return p+=r+l,h+=p>>>16,p&=65535,h+=o+c,d+=h>>>16,h&=65535,d+=s+a,u+=d>>>16,d&=65535,u+=e+i,u&=65535,Zt(h<<16|p,u<<16|d,this.unsigned)},et.subtract=function(t){return Be(t)||(t=Sn(t)),this.add(t.neg())},et.sub=et.subtract,et.multiply=function(t){if(this.isZero())return dn;if(Be(t)||(t=Sn(t)),ln){var e=ln.mul(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}if(t.isZero())return dn;if(this.eq(He))return t.isOdd()?He:dn;if(t.eq(He))return this.isOdd()?He:dn;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Yf)&&t.lt(Yf))return un(this.toNumber()*t.toNumber(),this.unsigned);var s=this.high>>>16,o=this.high&65535,r=this.low>>>16,i=this.low&65535,a=t.high>>>16,c=t.high&65535,l=t.low>>>16,u=t.low&65535,d=0,h=0,p=0,f=0;return f+=i*u,p+=f>>>16,f&=65535,p+=r*u,h+=p>>>16,p&=65535,p+=i*l,h+=p>>>16,p&=65535,h+=o*u,d+=h>>>16,h&=65535,h+=r*l,d+=h>>>16,h&=65535,h+=i*c,d+=h>>>16,h&=65535,d+=s*u+o*l+r*c+i*a,d&=65535,Zt(p<<16|f,d<<16|h,this.unsigned)},et.mul=et.multiply,et.divide=function(t){if(Be(t)||(t=Sn(t)),t.isZero())throw Error("division by zero");if(ln){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?ln.div_u:ln.div_s)(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Hs:dn;var s,o,r;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Hs;if(t.gt(this.shru(1)))return Qf;r=Hs}else{if(this.eq(He)){if(t.eq(Ao)||t.eq(Yu))return He;if(t.eq(He))return Ao;var i=this.shr(1);return s=i.div(t).shl(1),s.eq(dn)?t.isNegative()?Ao:Yu:(o=this.sub(t.mul(s)),r=s.add(o.div(t)),r)}else if(t.eq(He))return this.unsigned?Hs:dn;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();r=dn}for(o=this;o.gte(t);){s=Math.max(1,Math.floor(o.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(s)/Math.LN2),c=a<=48?1:Cc(2,a-48),l=un(s),u=l.mul(t);u.isNegative()||u.gt(o);)s-=c,l=un(s,this.unsigned),u=l.mul(t);l.isZero()&&(l=Ao),r=r.add(l),o=o.sub(u)}return r},et.div=et.divide,et.modulo=function(t){if(Be(t)||(t=Sn(t)),ln){var e=(this.unsigned?ln.rem_u:ln.rem_s)(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},et.mod=et.modulo,et.rem=et.modulo,et.not=function(){return Zt(~this.low,~this.high,this.unsigned)},et.and=function(t){return Be(t)||(t=Sn(t)),Zt(this.low&t.low,this.high&t.high,this.unsigned)},et.or=function(t){return Be(t)||(t=Sn(t)),Zt(this.low|t.low,this.high|t.high,this.unsigned)},et.xor=function(t){return Be(t)||(t=Sn(t)),Zt(this.low^t.low,this.high^t.high,this.unsigned)},et.shiftLeft=function(t){return Be(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Zt(this.low<>>32-t,this.unsigned):Zt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):Zt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},et.shr=et.shiftRight,et.shiftRightUnsigned=function(t){if(Be(t)&&(t=t.toInt()),t&=63,t===0)return this;var e=this.high;if(t<32){var s=this.low;return Zt(s>>>t|e<<32-t,e>>>t,this.unsigned)}else return t===32?Zt(e,0,this.unsigned):Zt(e>>>t-32,0,this.unsigned)},et.shru=et.shiftRightUnsigned,et.shr_u=et.shiftRightUnsigned,et.toSigned=function(){return this.unsigned?Zt(this.low,this.high,!1):this},et.toUnsigned=function(){return this.unsigned?this:Zt(this.low,this.high,!0)},et.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},et.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},et.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]},Kt.fromBytes=function(t,e,s){return s?Kt.fromBytesLE(t,e):Kt.fromBytesBE(t,e)},Kt.fromBytesLE=function(t,e){return new Kt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},Kt.fromBytesBE=function(t,e){return new Kt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};const qf=gw(Kf),yw=YI({__proto__:null,default:qf},[Kf]);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _s=qf||yw;function vc(n){return _s.fromString(n,!0,16)}const tm=vc("c3a5c85c97cb3127"),Us=vc("b492b66fbe98f273"),Re=vc("9ae16a3b2f90404f");function Qu(n){return n.xor(n.shru(47))}function em(n,t,e){const s=n.slice(t,t+e);return _s.fromBytes(Array.from(s),!0,!0)}function Ft(n,t){return em(n,t,8)}function nm(n,t){return em(n,t,4)}function fe(n,t){return t===0?n:n.shru(t).or(n.shl(64-t))}function ms(n,t,e=vc("9ddfea08eb382d69")){let s=n.xor(t).mul(e);s=s.xor(s.shru(47));let o=t.xor(s).mul(e);return o=o.xor(o.shru(47)),o=o.mul(e),o}function Iw(n,t,e,s,o,r){o=o.add(n),r=fe(r.add(o).add(s),21);const i=o;return o=o.add(t),o=o.add(e),r=r.add(fe(o,44)),[o.add(s),r.add(i)]}function Sc(n,t,e,s){return Iw(Ft(n,t),Ft(n,t+8),Ft(n,t+16),Ft(n,t+24),e,s)}function ww(n,t=n.length){if(t>=8){const e=Re.add(t*2),s=Ft(n,0).add(Re),o=Ft(n,t-8),r=fe(o,37).mul(e).add(s),i=fe(s,25).add(o).mul(e);return ms(r,i,e)}if(t>=4){const e=Re.add(t*2),s=nm(n,0);return ms(s.shl(3).add(t),nm(n,t-4),e)}if(t>0){const e=n[0],s=n[t>>1],o=n[t-1],r=e+(s<<8),i=t+(o<<2);return Qu(Re.mul(r).xor(tm.mul(i))).mul(Re)}return Re}function Cw(n,t=n.length){const e=Re.add(t*2),s=Ft(n,0).mul(Us),o=Ft(n,8),r=Ft(n,t-8).mul(e),i=Ft(n,t-16).mul(Re);return ms(fe(s.add(o),43).add(fe(r,30)).add(i),s.add(fe(o.add(Re),18)).add(r),e)}function vw(n,t=n.length){const e=Re.add(t*2),s=Ft(n,0).mul(Re),o=Ft(n,8),r=Ft(n,t-8).mul(e),i=Ft(n,t-16).mul(Re),a=fe(s.add(o),43).add(fe(r,30)).add(i),c=ms(a,s.add(fe(o.add(Re),18)).add(r),e),l=Ft(n,16).mul(e),u=Ft(n,24),d=a.add(Ft(n,t-32)).mul(e),h=c.add(Ft(n,t-24)).mul(e);return ms(fe(l.add(u),43).add(fe(d,30)).add(h),l.add(fe(u.add(s),18)).add(d),e)}function Sw(n,t=n.length){const e=_s.fromNumber(81,!0);if(t<=32)return t<=16?ww(n,t):Cw(n,t);if(t<=64)return vw(n,t);let s=e,o=e.mul(Us).add(113),r=Qu(o.mul(Re).add(113)).mul(Re),i=[_s.UZERO,_s.UZERO],a=[_s.UZERO,_s.UZERO];s=s.mul(Re).add(Ft(n,0));let c=0;const l=(t-1>>6)*64,u=l+(t-1&63)-63;do s=fe(s.add(o).add(i[0]).add(Ft(n,c+8)),37).mul(Us),o=fe(o.add(i[1]).add(Ft(n,c+48)),42).mul(Us),s=s.xor(a[1]),o=o.add(i[0]).add(Ft(n,c+40)),r=fe(r.add(a[0]),33).mul(Us),i=Sc(n,c,i[1].mul(Us),s.add(a[0])),a=Sc(n,c+32,r.add(a[1]),o.add(Ft(n,c+16))),[r,s]=[s,r],c+=64;while(c!==l);const d=Us.add(r.and(255).shl(1));return c=u,a[0]=a[0].add(t-1&63),i[0]=i[0].add(a[0]),a[0]=a[0].add(i[0]),s=fe(s.add(o).add(i[0]).add(Ft(n,c+8)),37).mul(d),o=fe(o.add(i[1]).add(Ft(n,c+48)),42).mul(d),s=s.xor(a[1].mul(9)),o=o.add(i[0].mul(9).add(Ft(n,c+40))),r=fe(r.add(a[0]),33).mul(d),i=Sc(n,c,i[1].mul(d),s.add(a[0])),a=Sc(n,c+32,r.add(a[1]),o.add(Ft(n,c+16))),[r,s]=[s,r],ms(ms(i[0],a[0],d).add(Qu(o).mul(tm)).add(r),ms(i[1],a[1],d).add(s),d)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gs(n,t){return t==="string"?bs(n):Ys([n],t)}function kw(n,t){return n instanceof Float32Array&&t==="float32"||n instanceof Int32Array&&t==="int32"||n instanceof Uint8Array&&t==="bool"}function Ys(n,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Qs(n)),z().getBool("DEBUG")&&tw(n,t),kw(n,t))return n;if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool"){const e=new Uint8Array(n.length);for(let s=0;s{o=s()};let i;const a=Ve();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(r);else{r();for(const l of o)l.dataSync();i=Promise.resolve({kernelMs:Ve()-a})}if(z().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{Nw(d,u.dtype,t)})}return{kernelName:t,outputs:o,inputs:e,timeMs:i.then(l=>l.kernelMs),extraInfo:i.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(t){const{kernelName:e,outputs:s,timeMs:o,inputs:r,extraInfo:i}=t;s.forEach(a=>{Promise.all([a.data(),o,i]).then(c=>{this.logger.logKernelProfile(e,a,c[0],c[1],r,c[2])})})}}function Nw(n,t,e){if(t!=="float32")return!1;for(let s=0;s0?m:""} `}}console.log(`%c${c} %c${a} %c${l}D ${d} %c${u} %c${h} %c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $w(n,t,e){const s={},o={};for(let c=0;cs[m.id]=!0),p=!0,o[l.id]=!0;break}if(p)break}}const r={};r[e.id]=!0;const i={};for(let c=n.length-1;c>=0;c--){const l=n[c],u=l.inputs;for(let d=0;d=0;o--){const r=t[o],i=[];if(r.outputs.forEach(c=>{const l=n[c.id];l!=null?i.push(l):i.push(null)}),r.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const a=r.gradient(i);for(const c in r.inputs){if(!(c in a))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(a)}.`);const l=e(()=>a[c]());if(l.dtype!=="float32")throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${l.dtype}'`);const u=r.inputs[c];if(!Rt(l.shape,u.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${c}' has shape '${l.shape}', which does not match the shape of the input '${u.shape}'`);if(n[u.id]==null)n[u.id]=l;else{const d=n[u.id];n[u.id]=s(d,l),d.dispose()}}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sm=20,xi=3,Ju=7;function Lw(n,t,e,s){const o=ct(t),r=Ew(n,t,e,o),i=t.length,a=kc(n,t,e,o,r),c=["Tensor"];return s&&(c.push(` dtype: ${e}`),c.push(` rank: ${i}`),c.push(` shape: [${t}]`),c.push(" values:")),c.push(a.map(l=>" "+l).join(` +`)),c.join(` +`)}function Ew(n,t,e,s){const o=Z(t),r=s[s.length-1],i=new Array(r).fill(0),a=t.length,c=e==="complex64"?Ii(n):n;if(a>1)for(let l=0;lsm){const g=xi*i;let b=Array.from(n.slice(0,g)),x=Array.from(n.slice((a-xi)*i,a*i));return e==="complex64"&&(b=Ii(b),x=Ii(x)),["["+b.map((I,y)=>yi(I,o[y],e)).join(", ")+", ..., "+x.map((I,y)=>yi(I,o[a-xi+y],e)).join(", ")+"]"]}return["["+(e==="complex64"?Ii(n):Array.from(n)).map((g,b)=>yi(g,o[b],e)).join(", ")+"]"]}const l=t.slice(1),u=s.slice(1),d=s[0]*i,h=[];if(a>sm){for(let m=0;m0?h[0]+p:"");for(let m=1;m`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=s||qt(e,this.size),this.strides=ct(t)}set(t,...e){e.length===0&&(e=[0]),v(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);const s=this.locToIndex(e);this.values[s]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(const o of t){if(o<0||o>=this.shape[e]){const r=`Requested out of range element at ${t}. Buffer shape=${this.shape}`;throw new Error(r)}e++}let s=t[t.length-1];for(let o=0;oxs(s))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataToGPU(t){return this.throwIfDisposed(),kn().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();const t=kn().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>xs(e))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();const t=await kn().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),kn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return Po.print(this,t)}clone(){return this.throwIfDisposed(),Po.clone(this)}toString(t=!1){const e=this.dataSync();return Lw(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),Po.cast(this,t)}variable(t=!0,e,s){return this.throwIfDisposed(),kn().makeVariable(this,t,e,s)}}Object.defineProperty(ae,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function O(){return eu("Tensor",()=>ae)}O();class Tc extends ae{constructor(t,e,s,o){super(t.shape,t.dtype,t.dataId,o),this.trainable=e,this.name=s}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!Rt(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);kn().disposeTensor(this),this.dataId=t.dataId,kn().incRef(this,null)}dispose(){kn().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Tc,Symbol.hasInstance,{value:n=>n instanceof ae&&n.assign!=null&&n.assign instanceof Function});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var rm;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})(rm||(rm={}));var ju;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(ju||(ju={}));var qu;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(qu||(qu={}));var td;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(td||(td={}));var ed;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(ed||(ed={}));const Mw={float32:td,int32:ju,bool:qu,complex64:ed};function _e(n,t){if(n==="string"||t==="string"){if(n==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${n} with ${t}`)}return Mw[n][t]}function nd(n){return _e(n,"int32")}function im(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function am(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function te(n,t){if(n.dtype===t.dtype)return[n,t];const e=_e(n.dtype,t.dtype);return[n.cast(e),t.cast(e)]}function cm(n){const t=[];return lm(n,t,new Set),t}function lm(n,t,e){if(n==null)return;if(n instanceof ae){t.push(n);return}if(!Vw(n))return;const s=n;for(const o in s){const r=s[o];e.has(r)||(e.add(r),lm(r,t,e))}}function Vw(n){return Array.isArray(n)||typeof n=="object"}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sd(n){return n.kernelName!=null}class um{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(t=>t.name)))}}}dispose(){for(const t in this.registeredVariables)this.registeredVariables[t].dispose()}}class Oo{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new um}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const t=this.getSortedBackends();for(let e=0;e{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){Af(t).forEach(s=>{s.disposeFunc!=null&&s.disposeFunc(this.registry[t])})}initializeBackend(t){const e=this.registryFactory[t];if(e==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{const s=e.factory();if(s&&!(s instanceof Zl)&&typeof s.then=="function"){const o=++this.pendingBackendInitId,r=s.then(i=>o(othis.registryFactory[e].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){const t=this.getSortedBackends();for(let e=0;ethis.startScope(s),()=>this.endScope(o),()=>(o=e(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(t,e,s){t();try{const o=s();return e(),o}catch(o){throw e(),o}}nextTensorId(){return Oo.nextTensorId++}nextVariableId(){return Oo.nextVariableId++}clone(t){const e=G.runKernel(Kr,{x:t}),s={x:t},o=i=>({x:()=>{const a="float32",c={x:i},l={dtype:a};return G.runKernel(Gr,c,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,s,[e],o,r,{}),e}runKernel(t,e,s){if(this.backendName==null&&this.backend,!(_u(t,this.backendName)!=null))throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:e,attrs:s})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,e,s){const o=this.backend.numDataIds();let r=0;s.forEach(c=>{r+=c.dtype==="complex64"?3:1});const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-e-r-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`)}runKernelFunc(t){let e,s=[];const o=this.isTapeOn(),r=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let c;const l=sd(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(sd(t)){const{kernelName:f,inputs:m,attrs:g}=t;this.backendName==null&&this.backend;const b=_u(f,this.backendName);v(b!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),a=()=>{const x=this.backend.numDataIds();c=b.kernelFunc({inputs:m,attrs:g,backend:this.backend});const I=Array.isArray(c)?c:[c];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,x,I);const y=I.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(o){const w=this.getTensorsForGradient(f,m,y);s=this.saveTensorsForBackwardMode(w)}return y}}else{const{forwardFunc:f}=t,m=g=>{o&&(s=g.map(b=>this.keep(this.clone(b))))};a=()=>{const g=this.backend.numDataIds();c=this.tidy(()=>f(this.backend,m));const b=Array.isArray(c)?c:[c];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,g,b),b}}const{inputs:u,attrs:d}=t,h=sd(t)?null:t.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?e=a():(p=this.profiler.profileKernel(l,u,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),e=p.outputs)}),o&&this.addTapeNode(l,u,e,h,s,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(f=>u[f]!=null?u[f].shape:null),outputShapes:e.map(f=>f.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(c)?e:e[0]}saveTensorsForBackwardMode(t){return t.map(s=>this.keep(this.clone(s)))}getTensorsForGradient(t,e,s){const o=Xf(t);if(o!=null){const r=o.inputsToSave||[],i=o.outputsToSave||[];let a;o.saveAllInputs?(v(Array.isArray(e),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(e).map(l=>e[l])):a=r.map(l=>e[l]);const c=s.filter((l,u)=>i[u]);return a.concat(c)}return[]}makeTensor(t,e,s,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",o=o||this.backend;let r=t;s==="string"&&Cr(t[0])&&(r=t.map(c=>bs(c)));const i=o.write(r,e,s),a=new ae(e,s,i,this.nextTensorId());if(this.trackTensor(a,o),s==="string"){const c=this.state.tensorInfo.get(i),l=nw(r);this.state.numBytes+=l-c.bytes,c.bytes=l}return a}makeTensorFromDataId(t,e,s,o){s=s||"float32";const r={dataId:t,shape:e,dtype:s};return this.makeTensorFromTensorInfo(r,o)}makeTensorFromTensorInfo(t,e){const{dataId:s,shape:o,dtype:r}=t,i=new ae(o,r,s,this.nextTensorId());return this.trackTensor(i,e),i}makeVariable(t,e=!0,s,o){s=s||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.cast(o));const r=new Tc(t,e,s,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(t,e){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let s=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(s=t.size*xa(t.dtype)),this.state.numBytes+=s,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:s})),t instanceof Tc||this.track(t)}incRef(t,e){this.trackTensor(t,e),this.backend.incRef(t.dataId)}removeDataId(t,e){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===e&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;const e=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=e.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){const s=t.size*xa(t.dtype);this.state.numBytes-=s}e.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,e.backend)}disposeVariables(){for(const t in this.state.registeredVariables){const e=this.state.registeredVariables[t];this.disposeVariable(e)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){const t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;const e=this.state.numBytes,s=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,e,s,o,r,i){const a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:s,saved:r},c=Xf(t);c!=null&&(o=c.gradFunc),o!=null&&(a.gradient=l=>(l=l.map((u,d)=>{if(u==null){const h=s[d],p=ke(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),o(l.length>1?l:l[0],r,i))),this.state.activeTape.push(a)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){const e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e}endScope(t){const e=cm(t),s=new Set(e.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===o.id&&this.track(r)})}gradients(t,e,s,o=!1){if(v(e.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));v(r instanceof ae,()=>"The result y returned by f() must be a tensor.");const i=$w(this.state.activeTape,e,r);if(!o&&i.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const a={};a[r.id]=s??Fw(r.shape),Gw(a,i,l=>this.tidy(l),zw);const c=e.map(l=>a[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(const u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:c}})}customGrad(t){return v(Ql(t),()=>"The f passed in customGrad(f) must be a function."),(...e)=>{v(e.every(a=>a instanceof ae),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const o={};e.forEach((a,c)=>{o[c]=a});const r=(a,c)=>(s=t(...e,c),v(s.value instanceof ae,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),v(Ql(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),i=(a,c)=>{const l=s.gradFunc(a,c),u=Array.isArray(l)?l:[l];v(u.length===e.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(...)."),v(u.every(h=>h instanceof ae),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:r,backwardsFunc:i,inputs:o})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,e){return this.state.tensorInfo.get(t).backend.readToGPU(t,e)}async time(t){const e=Ve(),s=await this.backend.time(t);return s.wallMs=Ve()-e,s}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new um;for(const t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}Oo.nextTensorId=0,Oo.nextVariableId=0;function Fw(n){const t=jl(Z(n),"float32");return G.makeTensor(t,n,"float32")}function dm(){const n=bf();if(n._tfengine==null){const t=new rw(n);n._tfengine=new Oo(t)}return lw(n._tfengine.ENV),Dw(()=>n._tfengine),n._tfengine}const G=dm();function zw(n,t){const e={a:n,b:t};return G.runKernel(Fo,e)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xw(){return typeof navigator<"u"&&navigator!=null}function hm(n){if(n||Xw()){if(n||(n=navigator),n.product==="ReactNative")return!0;const t=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");if(!t){const e=n;return e.userAgentData&&e.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function pm(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fe=z();Fe.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),Fe.registerFlag("IS_BROWSER",()=>pm()),Fe.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"),Fe.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Fe.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Fe.registerFlag("PROD",()=>!1),Fe.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Fe.getBool("DEBUG")),Fe.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Fe.registerFlag("IS_TEST",()=>!1),Fe.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Fe.getBool("DEBUG")),Fe.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Fe.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Fe.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wi(n,t){let e=n;if(hn(n))return t==="string"?[]:[n.length];if(im(n)){const o=n.channels||"RGBA";return[n.height,n.width*o.length]}else if(am(n))return[n.buffer.size/(t==null?4:xa(t))];if(!Array.isArray(n))return[];const s=[];for(;Array.isArray(e)||hn(e)&&t!=="string";)s.push(e.length),e=e[0];return Array.isArray(n)&&z().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&fm(n,s,[]),s}function fm(n,t,e){if(e=e||[],!Array.isArray(n)&&!hn(n)){v(t.length===0,()=>`Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}v(t.length>0,()=>`Element arr[${e.join("][")}] should be a primitive, but is an array of ${n.length} elements`),v(n.length===t[0],()=>`Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${n.length} elements`);const s=t.slice(1);for(let o=0;o=0&&(o=s),mm(s,o,t,e),n==null||!hn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const c=n==null?"null":n.constructor.name;throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${c}'`)}const r=wi(n,o);!hn(n)&&!Array.isArray(n)&&(n=[n]);const a=o!=="string"?Ys(n,o):Qs(n,[],!0);return G.makeTensor(a,r,o)}function gm(n,t,e,s="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${t} passed to ${e} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((r,i)=>N(r,`${t}[${i}]`,e,s))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Aw="__op";function D(n){const t=Object.keys(n);if(t.length!==1)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 e=t[0];const s=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+Aw;const o=(...r)=>{G.startScope(e);try{const i=s(...r);return ql(i)&&console.error("Cannot return a Promise inside of tidy."),G.endScope(i),i}catch(i){throw G.endScope(null),i}};return Object.defineProperty(o,"name",{value:e,configurable:!0}),o}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pw(n,t){const e=N(n,"real","complex"),s=N(t,"imag","complex");Hl(e.shape,s.shape,`real and imag shapes, ${e.shape} and ${s.shape}, must match in call to tf.complex().`);const o={real:e,imag:s};return G.runKernel(lu,o)}const Ko=D({complex_:Pw});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ci(n,t,e,s){if(s==null)s=Mo(n);else if(s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(am(n)||im(n)){if(s!=="float32"&&s!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return G.backend.createTensorFromGPUData(n,t||e,s)}if(!hn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){es(t);const o=Z(t),r=Z(e);v(o===r,()=>`Based on the provided shape, [${t}], the tensor should have ${o} values but has ${r}`);for(let i=0;i`Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `)}}return!hn(n)&&!Array.isArray(n)&&(n=[n]),t=t||e,n=s!=="string"?Ys(n,s):Qs(n,[],!0),G.makeTensor(n,t,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tn(n,t,e){const s=wi(n,e);return Ci(n,t,s,e)}class Zo{static join(t){return new Zo(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(s=>hn(s)?s.buffer:s),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let e=0;for(let s=0;s=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function e(o){return t=o.end?1:0}if(e(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const s=Ow(this.shards,e);return s===-1?-1:(this.previousShardIndex=s,this.previousShardIndex)}}function Ow(n,t){let e=0,s=n.length;for(;e<=s;){const o=Math.floor((s-e)/2)+e,r=t(n[o]);if(r===0)return o;r<0?s=o:e=o+1}return-1}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zt(){return G}function Nc(){return G.memory()}function M(n,t){return G.tidy(n,t)}function vt(n){cm(n).forEach(e=>e.dispose())}function en(n){return G.keep(n)}function bm(n,t,e=1){return G.registerBackend(n,t,e)}function ys(){return G.backend}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xm=4;async function ym(n,t){const e=[],s=[],o=Array.isArray(n)?n.map(i=>i.name):Object.keys(n);for(let i=0;i{const h=await c.bytes(),p=h.reduce((g,b)=>g+b.length,0)+xm*h.length,f=new Uint8Array(p);let m=0;for(let g=0;g{if(t+=r.byteLength,e.push(r.byteLength===r.buffer.byteLength?r:new r.constructor(r)),!(r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${r.constructor.name}`)});const s=new Uint8Array(t);let o=0;return e.forEach(r=>{s.set(new Uint8Array(r.buffer),o),o+=r.byteLength}),s.buffer}const od=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function Im(n){return od?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function Zw(n){if(od)return Buffer.from(n).toString("base64");const t=new Uint8Array(n);let e="";for(let s=0,o=t.length;s{const a=i(t,s);a!==null&&o.push(a)}),o}}const _w=n=>$e.getSaveHandlers(n);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rd="tensorflowjs",id=1,Js="models_store",Is="model_info_store";function Cm(){if(!z().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ad(n){const t=n.result;t.createObjectStore(Js,{keyPath:"modelPath"}),t.createObjectStore(Is,{keyPath:"modelPath"})}class js{constructor(t){if(this.indexedDB=Cm(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,t)}async load(){return this.databaseAction(this.modelPath)}databaseAction(t,e){return new Promise((s,o)=>{const r=this.indexedDB.open(rd,id);r.onupgradeneeded=()=>ad(r),r.onsuccess=()=>{const i=r.result;if(e==null){const a=i.transaction(Js,"readonly"),l=a.objectStore(Js).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return i.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));s(l.result.modelArtifacts)},l.onerror=u=>(i.close(),o(l.error)),a.oncomplete=()=>i.close()}else{e.weightData=Zo.join(e.weightData);const a=wm(e),c=i.transaction(Is,"readwrite");let l=c.objectStore(Is),u;try{u=l.put({modelPath:this.modelPath,modelArtifactsInfo:a})}catch(h){return o(h)}let d;u.onsuccess=()=>{d=i.transaction(Js,"readwrite");const h=d.objectStore(Js);let p;try{p=h.put({modelPath:this.modelPath,modelArtifacts:e,modelArtifactsInfo:a})}catch(f){return o(f)}p.onsuccess=()=>s({modelArtifactsInfo:a}),p.onerror=f=>{l=c.objectStore(Is);const m=l.delete(this.modelPath);m.onsuccess=()=>(i.close(),o(p.error)),m.onerror=g=>(i.close(),o(p.error))}},u.onerror=h=>(i.close(),o(u.error)),c.oncomplete=()=>{d==null?i.close():d.oncomplete=()=>i.close()}}},r.onerror=i=>o(r.error)})}}js.URL_SCHEME="indexeddb://";const vm=n=>z().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(js.URL_SCHEME)?Uw(n.slice(js.URL_SCHEME.length)):null;$e.registerSaveRouter(vm),$e.registerLoadRouter(vm);function Uw(n){return new js(n)}function Yw(n){return n.startsWith(js.URL_SCHEME)?n.slice(js.URL_SCHEME.length):n}class Qw{constructor(){this.indexedDB=Cm()}async listModels(){return new Promise((t,e)=>{const s=this.indexedDB.open(rd,id);s.onupgradeneeded=()=>ad(s),s.onsuccess=()=>{const o=s.result,r=o.transaction(Is,"readonly"),a=r.objectStore(Is).getAll();a.onsuccess=()=>{const c={};for(const l of a.result)c[l.modelPath]=l.modelArtifactsInfo;t(c)},a.onerror=c=>(o.close(),e(a.error)),r.oncomplete=()=>o.close()},s.onerror=o=>e(s.error)})}async removeModel(t){return t=Yw(t),new Promise((e,s)=>{const o=this.indexedDB.open(rd,id);o.onupgradeneeded=()=>ad(o),o.onsuccess=()=>{const r=o.result,i=r.transaction(Is,"readwrite"),a=i.objectStore(Is),c=a.get(t);let l;c.onsuccess=()=>{if(c.result==null)return r.close(),s(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{const u=a.delete(t),d=()=>{l=r.transaction(Js,"readwrite");const p=l.objectStore(Js).delete(t);p.onsuccess=()=>e(c.result.modelArtifactsInfo),p.onerror=f=>s(c.error)};u.onsuccess=d,u.onerror=h=>(d(),r.close(),s(c.error))}},c.onerror=u=>(r.close(),s(c.error)),i.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},o.onerror=r=>s(o.error)})}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ns="/",Bo="tensorflowjs_models",Sm="info",Jw="model_topology",jw="weight_specs",qw="weight_data",tC="model_metadata";function km(n){return{info:[Bo,n,Sm].join(ns),topology:[Bo,n,Jw].join(ns),weightSpecs:[Bo,n,jw].join(ns),weightData:[Bo,n,qw].join(ns),modelMetadata:[Bo,n,tC].join(ns)}}function Tm(n){for(const t of Object.values(n))window.localStorage.removeItem(t)}function eC(n){const t=n.split(ns);if(t.length<3)throw new Error(`Invalid key format: ${n}`);return t.slice(1,t.length-1).join(ns)}function nC(n){return n.startsWith(qs.URL_SCHEME)?n.slice(qs.URL_SCHEME.length):n}class qs{constructor(t){if(!z().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=km(this.modelPath)}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const e=JSON.stringify(t.modelTopology),s=JSON.stringify(t.weightSpecs),o=wm(t),r=Zo.join(t.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,s),this.LS.setItem(this.keys.weightData,Zw(r));const i={format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,signature:t.signature!=null?t.signature:void 0,userDefinedMetadata:t.userDefinedMetadata!=null?t.userDefinedMetadata:void 0,modelInitializer:t.modelInitializer!=null?t.modelInitializer:void 0,initializerSignature:t.initializerSignature!=null?t.initializerSignature:void 0,trainingConfig:t.trainingConfig!=null?t.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(i)),{modelArtifactsInfo:o}}catch{throw Tm(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`)}}}async load(){const t=JSON.parse(this.LS.getItem(this.keys.info));if(t==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(t.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const e={},s=JSON.parse(this.LS.getItem(this.keys.topology));if(s==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);e.modelTopology=s;const o=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(o==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);e.weightSpecs=o;const r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){const a=JSON.parse(r);e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy,a.signature!=null&&(e.signature=a.signature),a.userDefinedMetadata!=null&&(e.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(e.modelInitializer=a.modelInitializer),a.initializerSignature!=null&&(e.initializerSignature=a.initializerSignature),a.trainingConfig!=null&&(e.trainingConfig=a.trainingConfig)}const i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return e.weightData=Bw(i),e}}qs.URL_SCHEME="localstorage://";const Nm=n=>z().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(qs.URL_SCHEME)?sC(n.slice(qs.URL_SCHEME.length)):null;$e.registerSaveRouter(Nm),$e.registerLoadRouter(Nm);function sC(n){return new qs(n)}class oC{constructor(){v(z().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),v(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const t={},e=Bo+ns,s=ns+Sm;for(let o=0;o"scheme must not be undefined or null."),t.endsWith(Rm)&&(t=t.slice(0,t.indexOf(Rm))),v(t.length>0,()=>"scheme must not be an empty string.");const s=zn.getInstance();v(s.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),s.managers[t]=e}static getManager(t){const e=zn.getInstance().managers[t];if(e==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys(zn.getInstance().managers)}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rC{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}setTimeoutCustom(t,e){if(typeof window>"u"||!z().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(t,e);return}this.functionRefs.push(t),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},e),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",s=>{if(s.source===window&&s.data.name===this.messageName){s.stopPropagation();const o=this.functionRefs[s.data.index];o(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(t){return Of(t)}}if(z().get("IS_BROWSER")){z().setPlatform("browser",new rC);try{zn.registerManager(qs.URL_SCHEME,new oC)}catch{}try{zn.registerManager(js.URL_SCHEME,new Qw)}catch{}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iC={importFetch:()=>require("node-fetch")};let cd;class aC{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(t,e){return z().global.fetch!=null?z().global.fetch(t,e):(cd==null&&(cd=iC.importFetch()),cd(t,e))}now(){const t=process.hrtime();return t[0]*1e3+t[1]/1e6}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(t)}decode(t,e){return t.length===0?"":new this.util.TextDecoder(e).decode(t)}isTypedArray(t){return this.util.types.isFloat32Array(t)||this.util.types.isInt32Array(t)||this.util.types.isUint8Array(t)||this.util.types.isUint8ClampedArray(t)}}z().get("IS_NODE")&&!z().get("IS_BROWSER")&&z().setPlatform("node",new aC);/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wt(n,t="float32",e){return t=t||"float32",es(n),new xe(n,t,e)}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cC(n,t){const e=N(n,"x","cast");if(!ew(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:e},o={dtype:t};return G.runKernel(Gr,s,o)}const st=D({cast_:cC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lC(n){const e={x:N(n,"x","clone","string_or_numeric")};return G.runKernel(Kr,e)}const to=D({clone_:lC});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uC(n,t=!1){console.log(n.toString(t))}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */dm(),Ww({buffer:wt,cast:st,clone:to,print:uC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dC(n,t){let e=N(n,"a","add"),s=N(t,"b","add");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Fo,o)}const Q=D({add_:dC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hC(n,t){let e=N(n,"a","floorDiv"),s=N(t,"b","floorDiv");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Pr,o)}const $m=D({floorDiv_:hC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pC(n,t){let e=N(n,"a","div"),s=N(t,"b","div");if([e,s]=te(e,s),e.dtype==="int32"&&s.dtype==="int32")return $m(e,s);const o={a:e,b:s},r={};return G.runKernel(Mr,o,r)}const dt=D({div_:pC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fC(n,t){let e=N(n,"a","mul"),s=N(t,"b","mul");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(jr,o)}const E=D({mul_:fC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mC(n){const t=N(n,"x","abs");if(t.dtype==="complex64"){const e={x:t};return G.runKernel(Ta,e)}else{const e={x:t};return G.runKernel(ya,e)}}const Ge=D({abs_:mC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gC(n){const e={x:N(n,"x","acos")};return G.runKernel(vr,e)}const bC=D({acos_:gC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xC(n){const e={x:N(n,"x","acosh")};return G.runKernel(Sr,e)}const yC=D({acosh_:xC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IC(n,t=null,e=!1){const o={x:N(n,"x","all","bool")},r={axis:t,keepDims:e};return G.runKernel(su,o,r)}const Gm=D({all_:IC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wC(n,t=null,e=!1){const o={x:N(n,"x","any","bool")},r={axis:t,keepDims:e};return G.runKernel(ou,o,r)}const ld=D({any_:wC});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CC(n,t=0){const s={x:N(n,"x","argMax")},o={axis:t};return G.runKernel(Ia,s,o)}const vi=D({argMax_:CC});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vC(n,t=0){const s={x:N(n,"x","argMin")},o={axis:t};return G.runKernel(wa,s,o)}const SC=D({argMin_:vC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kC(n){const e={x:N(n,"x","asin")};return G.runKernel(kr,e)}const TC=D({asin_:kC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NC(n){const e={x:N(n,"x","asinh")};return G.runKernel(Tr,e)}const RC=D({asinh_:NC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $C(n){const e={x:N(n,"x","atan")};return G.runKernel(Nr,e)}const GC=D({atan_:$C});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LC(n,t){let e=N(n,"a","atan2"),s=N(t,"b","atan2");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel($r,o)}const EC=D({atan2_:LC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DC(n){const e={x:N(n,"x","atanh")};return G.runKernel(Rr,e)}const WC=D({atanh_:DC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Si(n,t,e,s,o="NHWC",r){const i=n[3],a=[...t,i],c=os(o);return ye(n,a,e,r,s,null,null,c)}function pn(n,t,e,s,o,r,i="channelsLast"){const[a,c]=ki(t);let l;if(i==="channelsLast")l=[a,c,n[3],n[3]];else if(i==="channelsFirst")l=[a,c,n[1],n[1]];else throw new Error(`Unknown dataFormat ${i}`);return ye(n,l,e,s,o,r,!1,i)}function ss(n,t,e,s,o,r,i="NDHWC"){const[a,c,l]=dd(t);let u,d;if(i==="NDHWC")d="channelsLast",u=[a,c,l,n[4],n[4]];else if(i==="NCDHW")d="channelsFirst",u=[a,c,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${i}`);return ws(n,u,e,s,o,!1,d,r)}function ye(n,t,e,s,o,r,i=!1,a="channelsLast"){let[c,l,u,d]=[-1,-1,-1,-1];if(a==="channelsLast")[c,l,u,d]=n;else if(a==="channelsFirst")[c,d,l,u]=n;else throw new Error(`Unknown dataFormat ${a}`);const[h,p,,f]=t,[m,g]=ki(e),[b,x]=ki(s),I=Ho(h,b),y=Ho(p,x),{padInfo:w,outHeight:C,outWidth:k}=FC(o,l,u,m,g,I,y,r,a),S=i?f*d:f;let T;return a==="channelsFirst"?T=[c,S,C,k]:a==="channelsLast"&&(T=[c,C,k,S]),{batchSize:c,dataFormat:a,inHeight:l,inWidth:u,inChannels:d,outHeight:C,outWidth:k,outChannels:S,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:p,effectiveFilterHeight:I,effectiveFilterWidth:y,dilationHeight:b,dilationWidth:x,inShape:n,outShape:T,filterShape:t}}function ws(n,t,e,s,o,r=!1,i="channelsLast",a){let[c,l,u,d,h]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[c,l,u,d,h]=n;else if(i==="channelsFirst")[c,h,l,u,d]=n;else throw new Error(`Unknown dataFormat ${i}`);const[p,f,m,,g]=t,[b,x,I]=dd(e),[y,w,C]=dd(s),k=Ho(p,y),S=Ho(f,w),T=Ho(m,C),{padInfo:R,outDepth:L,outHeight:V,outWidth:F}=zC(o,l,u,d,b,x,I,k,S,T,a),X=r?g*h:g;let A;return i==="channelsFirst"?A=[c,X,L,V,F]:i==="channelsLast"&&(A=[c,L,V,F,X]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:u,inWidth:d,inChannels:h,outDepth:L,outHeight:V,outWidth:F,outChannels:X,padInfo:R,strideDepth:b,strideHeight:x,strideWidth:I,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:k,effectiveFilterHeight:S,effectiveFilterWidth:T,dilationDepth:y,dilationHeight:w,dilationWidth:C,inShape:n,outShape:A,filterShape:t}}function MC(n,t,e,s,o){s==null&&(s=ud(n,t,e));const r=n[0],i=n[1],a=Ti((r-t+2*s)/e+1,o),c=Ti((i-t+2*s)/e+1,o);return[a,c]}function VC(n,t,e,s,o,r){o==null&&(o=ud(n,t[0],s[0]));const i=[0,0,0,e];for(let a=0;a<3;a++)n[a]+2*o>=t[a]&&(i[a]=Ti((n[a]-t[a]+2*o)/s[a]+1,r));return i}function ud(n,t,e,s=1){const o=Ho(t,s);return Math.floor((n[0]*(e-1)-e+o)/2)}function ki(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function dd(n){return typeof n=="number"?[n,n,n]:n}function Ho(n,t){return t<=1?n:n+(n-1)*(t-1)}function FC(n,t,e,s,o,r,i,a,c){let l,u,d;if(typeof n=="number"){l={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};const p=MC([t,e],r,s,n,a);u=p[0],d=p[1]}else if(n==="same"){u=Math.ceil(t/s),d=Math.ceil(e/o);const h=Math.max(0,(u-1)*s+r-t),p=Math.max(0,(d-1)*o+i-e),f=Math.floor(h/2),m=h-f,g=Math.floor(p/2),b=p-g;l={top:f,bottom:m,left:g,right:b,type:"SAME"}}else if(n==="valid")l={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-r+1)/s),d=Math.ceil((e-i+1)/o);else if(typeof n=="object"){const h=c==="channelsLast"?n[1][0]:n[2][0],p=c==="channelsLast"?n[1][1]:n[2][1],f=c==="channelsLast"?n[2][0]:n[3][0],m=c==="channelsLast"?n[2][1]:n[3][1];l={top:h,bottom:p,left:f,right:m,type:h===0&&p===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Ti((t-r+h+p)/s+1,a),d=Ti((e-i+f+m)/o+1,a)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:l,outHeight:u,outWidth:d}}function zC(n,t,e,s,o,r,i,a,c,l,u){let d,h,p,f;if(n==="valid"&&(n=0),typeof n=="number"){d={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};const g=VC([t,e,s,1],[a,c,l],1,[o,r,i],n,u);h=g[0],p=g[1],f=g[2]}else if(n==="same"){h=Math.ceil(t/o),p=Math.ceil(e/r),f=Math.ceil(s/i);const m=(h-1)*o+a-t,g=(p-1)*r+c-e,b=(f-1)*i+l-s,x=Math.floor(m/2),I=m-x,y=Math.floor(g/2),w=g-y,C=Math.floor(b/2),k=b-C;d={top:y,bottom:w,left:C,right:k,front:x,back:I,type:"SAME"}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:d,outDepth:h,outHeight:p,outWidth:f}}function Ti(n,t){if(!t)return Math.trunc(n);switch(t){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${t}`)}}function eo(n){const[t,e,s]=ki(n);return t===1&&e===1&&s===1}function Te(n,t){return eo(n)||eo(t)}function no(n){return ki(n).every(t=>t>0)}function os(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function ze(n,t,e){if(e!=null){if(typeof t=="string")throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);if(typeof t=="number")v(Do(t),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);else if(typeof t=="object")t.forEach(s=>{s.forEach(o=>{v(Do(o),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${o}.`)})});else throw Error(`Error in ${n}: Unknown padding parameter: ${t}`)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XC(n,t){const s={x:N(n,"x","reshape","string_or_numeric")},o={shape:t};return G.runKernel(ic,s,o)}const W=D({reshape_:XC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AC(n,t,e,s,o){const r=N(n,"x","avgPool","float32"),i=1;v(Te(e,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`);let a=r,c=!1;r.rank===3&&(c=!0,a=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),ze("avgPool",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o};let d=G.runKernel(Ca,l,u);return d=st(d,r.dtype),c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const hd=D({avgPool_:AC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PC(n,t,e,s,o,r="NDHWC"){const i=N(n,"x","avgPool3d","float32");let a=i,c=!1;i.rank===4&&(c=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),v(r==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),v(typeof e=="number"&&e>0||Array.isArray(e)&&e[0]>0&&e[1]>0&&e[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${e}'`),ze("avgPool3d",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o,dataFormat:r};let d=G.runKernel(va,l,u);return d=st(d,a.dtype),c?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const OC=D({avgPool3d_:PC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KC(n,t=0){v(n.length>=1,()=>"Pass at least one tensor to concat");const e=gm(n,"tensors","concat","string_or_numeric");if(e[0].dtype==="complex64"&&e.forEach(r=>{if(r.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype ${r.dtype}. `)}),e.length===1)return to(e[0]);const s=e,o={axis:t};return G.runKernel(Na,s,o)}const Xe=D({concat_:KC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZC(n,t,e=!1,s=!1){let o=N(n,"a","matMul"),r=N(t,"b","matMul");[o,r]=te(o,r);const i={a:o,b:r},a={transposeA:e,transposeB:s};return G.runKernel(Sa,i,a)}const $t=D({matMul_:ZC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BC(n){const e={x:N(n,"x","sigmoid","float32")};return G.runKernel(li,e)}const _o=D({sigmoid_:BC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HC(n,t,e){const s=N(n,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");const o={x:s},r={begin:t,size:e};return G.runKernel(dc,o,r)}const Xt=D({slice_:HC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _C(n){const e={x:N(n,"x","tanh","float32")};return G.runKernel(mi,e)}const pd=D({tanh_:_C});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UC(n,t,e){const s=N(n,"x","batchToSpaceND"),o=t.reduce((a,c)=>a*c);v(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),v(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`),v(s.shape[0]%o===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);const r={x:s},i={blockShape:t,crops:e};return G.runKernel(ka,r,i)}const fd=D({batchToSpaceND_:UC});function YC(n){let t;return n.rank===0||n.rank===1?t=W(n,[1,1,1,n.size]):n.rank===2?t=W(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QC(n,t,e,s,o,r){r==null&&(r=.001);const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;s!=null&&(u=N(s,"offset","batchNorm")),v(a.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(u==null||a.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(l==null||a.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h={x:YC(i),scale:l,offset:u,mean:a,variance:c},p={varianceEpsilon:r},f=G.runKernel(Va,h,p);return W(f,i.shape)}const Rc=D({batchNorm_:QC});function JC(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),v(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),v(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const jC=D({batchNorm2d_:JC});function qC(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),v(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),v(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const t2=D({batchNorm3d_:qC});function e2(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),v(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),v(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const n2=D({batchNorm4d_:e2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s2(n,t,e){const s=N(n,"x","bincount"),o=N(t,"weights","bincount");v(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),v(e>=0,()=>`size must be non-negative, but got ${e}.`),v(o.size===s.size||o.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${o.shape}.`);const r={x:s,weights:o},i={size:e};return G.runKernel(au,r,i)}const o2=D({bincount_:s2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function r2(n,t){let e=N(n,"broadcastTo","x");const s=e.shape;if(es(t),t.lengthe.rank){const l=e.shape.slice();for(;l.length=0;l--)if(o[l]===t[l])r[l]=1;else if(e.shape[l]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(r.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return to(e);const a={x:e},c={reps:r};return G.runKernel(gi,a,c)}const Ni=D({broadcastTo_:r2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i2(n){const e={x:N(n,"x","ceil","float32")};return G.runKernel(Lr,e)}const a2=D({ceil_:i2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $c(n,t,e){es(n),e=e||Mo(t);const s={shape:n,value:t,dtype:e};return G.runKernel(Su,{},s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function c2(n,t,e){const s=N(n,"x","clipByValue");if(v(t<=e,()=>`Error in clip: min (${t}) must be less than or equal to max (${e}).`),t===e)return $c(s.shape,t,s.dtype);const o={x:s},r={clipValueMin:t,clipValueMax:e};return G.runKernel(Er,o,r)}const nn=D({clipByValue_:c2});function l2(n){return Xe(n,0)}const u2=D({concat1d_:l2});function d2(n,t){return Xe(n,t)}const h2=D({concat2d_:d2});function p2(n,t){return Xe(n,t)}const f2=D({concat3d_:p2});function m2(n,t){return Xe(n,t)}const g2=D({concat4d_:m2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function b2(n,t,e,s,o="NHWC",r=[1,1],i){const a=N(n,"x","conv2d","float32"),c=N(t,"filter","conv2d","float32");let l=a,u=!1;a.rank===3&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(l.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),ze("conv2d",s,i);const d=o==="NHWC"?l.shape[3]:l.shape[1];v(d===c.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${c.shape[2]}.`),v(Te(e,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`),v(no(r),()=>"Error in conv2D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv2D: Strides should be larger than 0.");const h={x:l,filter:c},p={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i},f=G.runKernel(Ra,h,p);return u?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const so=D({conv2d_:b2});function x2(n,t,e,s,o="NWC",r=1,i){const a=N(n,"x","conv1d"),c=N(t,"filter","conv1d");let l=a,u=!1;a.rank===2&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1]])),v(l.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`),v(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),ze("conv1d",s,i),v(l.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${c.shape[1]}.`),v(Te(e,r),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${e} and dilation '${r}'`),v(no(r),()=>"Error in conv1D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv1D: Stride should be larger than 0."),v(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);const d=W(c,[1,c.shape[0],c.shape[1],c.shape[2]]),h=W(l,[l.shape[0],1,l.shape[1],l.shape[2]]),g=so(h,d,[1,e],s,"NHWC",[1,r],i);return u?W(g,[g.shape[2],g.shape[3]]):W(g,[g.shape[0],g.shape[2],g.shape[3]])}const Lm=D({conv1d_:x2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function y2(n,t,e,s,o,r="NHWC",i){v(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let a=n,c=t,l=!1;t.rank===3&&(l=!0,c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),a=[1,n[0],n[1],n[2]]),v(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),v(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),v(e.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${e.rank}`);const u=r==="NHWC"?a[3]:a[1],d=r==="NHWC"?c.shape[3]:c.shape[1];v(u===e.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${e.shape[2]}.`),v(d===e.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${e.shape[3]}.`),ze("conv2dDerInput",o,i);const h={dy:c,filter:e},p={strides:s,pad:o,dataFormat:r,dimRoundingMode:i,inputShape:a},f=G.runKernel($a,h,p);return l?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const md=D({conv2DBackpropInput_:y2});function I2(n,t,e,s,o,r){const i=N(n,"x","conv2dTranspose"),a=N(t,"filter","conv2dTranspose");return md(e,i,a,s,o,"NHWC",r)}const Em=D({conv2dTranspose_:I2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w2(n,t,e,s,o="NDHWC",r=[1,1,1]){const i=N(n,"x","conv3d"),a=N(t,"filter","conv3d");let c=i,l=!1;i.rank===4&&(l=!0,c=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),v(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),v(c.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${a.shape[3]}.`),v(Te(e,r),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`),v(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`),v(no(r),()=>"Error in conv3D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv3D: Strides should be larger than 0.");const u={x:c,filter:a},d={strides:e,pad:s,dataFormat:o,dilations:r},h=G.runKernel(Ga,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const C2=D({conv3d_:w2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v2(n,t,e,s,o){v(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let r=n,i=t,a=!1;t.rank===4&&(a=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),r=[1,n[0],n[1],n[2],n[3]]);const c=r[4],l=i.shape[4];v(r.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`),v(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),v(e.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${e.rank}`),v(c===e.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${e.shape[3]}.`),v(l===e.shape[4],()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${e.shape[4]}.`);const u={dy:i,filter:e},d={pad:o,strides:s,inputShape:r},h=G.runKernel(hu,u,d);return a?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const Dm=D({conv3DBackpropInput_:v2});function S2(n,t,e,s,o){const r=N(n,"x","conv3dTranspose"),i=N(t,"filter","conv3dTranspose");return Dm(e,r,i,s,o)}const k2=D({conv3dTranspose_:S2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function T2(n){const e={x:N(n,"x","cos","float32")};return G.runKernel(Dr,e)}const gd=D({cos_:T2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N2(n){const e={x:N(n,"x","cosh","float32")};return G.runKernel(Wr,e)}const Wm=D({cosh_:N2});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function R2(n,t=0,e=!1,s=!1){const r={x:N(n,"x","cumprod")},i={axis:t,exclusive:e,reverse:s};return G.runKernel(pu,r,i)}const bd=D({cumprod_:R2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $2(n,t=0,e=!1,s=!1){const r={x:N(n,"x","cumsum")},i={axis:t,exclusive:e,reverse:s};return G.runKernel(La,r,i)}const Mm=D({cumsum_:$2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function G2(n,t,e,s=!1){const o=N(n,"x","denseBincount"),r=N(t,"weights","denseBincount");v(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),v(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),v(e>=0,()=>`size must be non-negative, but got ${e}.`),v(r.size===o.size||r.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${r.shape}.`);const i={x:o,weights:r},a={size:e,binaryOutput:s};return G.runKernel(mu,i,a)}const Vm=D({denseBincount_:G2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function L2(n,t,e="NHWC"){const s=N(n,"x","depthToSpace","float32"),o=e==="NHWC"?s.shape[1]:s.shape[2],r=e==="NHWC"?s.shape[2]:s.shape[3],i=e==="NHWC"?s.shape[3]:s.shape[1];v(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),v(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying + ${o} and ${t} for depthToSpace with input shape + ${s.shape}`),v(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying + ${r} and ${t} for depthToSpace with input shape + ${s.shape}`),v(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`);const a={x:s},c={blockSize:t,dataFormat:e};return G.runKernel(gu,a,c)}const E2=D({depthToSpace_:L2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D2(n,t,e,s,o="NHWC",r=[1,1],i){const a=N(n,"x","depthwiseConv2d","float32"),c=N(t,"filter","depthwiseConv2d","float32");let l=a,u=!1;a.rank===3&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`);const d=o==="NHWC"?l.shape[3]:l.shape[1];v(d===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${c.shape[2]}.`),ze("depthwiseConv2d",s,i);const h={x:l,filter:c},p={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i},f=G.runKernel(Ea,h,p);return u?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const xd=D({depthwiseConv2d_:D2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function W2(n,t,e,s,o=[1,1],r="NHWC"){const i=N(n,"x","dilation2d"),a=N(t,"filter","dilation2d");v(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),v(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),v(r==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);let c=i,l=!1;i.rank===3&&(c=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0),v(c.shape[3]===a.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${c.shape[3]} vs ${a.shape[2]}`);const u={x:c,filter:a},d={strides:e,pad:s,dilations:o},h=G.runKernel(Da,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const M2=D({dilation2d_:W2});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Uo(n,t){const e=n.length,s=[];for(let o=0;o1&&i===1&&s.unshift(r)}return s}function ce(n,t){const e=[];for(let s=0;s1)&&e.unshift(r)}return e}function gt(n,t){const e=Math.max(n.length,t.length),s=new Array(e);for(let o=0;o`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${s.rank}.`);const o=e.rank===1?e.size:e.shape[1],r=s.rank===1?s.size:s.shape[0];if(v(o===r,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${r}.`),e.rank===1&&s.rank===1){const i=W(e,[1,-1]),a=W(s,[-1,1]),c=$t(i,a);return W(c,[])}else if(e.rank===1&&s.rank===2){const i=W(e,[1,-1]),a=W(s,[s.shape[0],s.shape[1]]),c=$t(i,a);return W(c,[c.size])}else if(e.rank===2&&s.rank===1){const i=W(s,[-1,1]),a=$t(e,i);return W(a,[a.size])}else{const i=W(s,[s.shape[0],s.shape[1]]);return $t(e,i)}}const O2=D({dot_:P2});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function K2(n,...t){const e=t.map((o,r)=>N(o,`tensors${r}`,"einsum")),s={equation:n};return G.runKernel(wu,e,s)}const Ri=D({einsum_:K2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Z2(n){const e={x:N(n,"x","elu","float32")};return G.runKernel(Vr,e)}const Gc=D({elu_:Z2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function B2(n){let t=N(n,"x","erf");v(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=st(t,"float32"));const e={x:t};return G.runKernel(Fr,e)}const H2=D({erf_:B2});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yd(n,t){for(let e=0;en[r]);return[e,o]}function re(n,t){const e=t.map(s=>1);return Fm(n,e,t)}function Ie(n,t,e){v(yd(t,e),()=>`${n} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function Yt(n,t){if(yd(n,t))return null;const e=[];for(let s=0;se.push(s)),e}function Cs(n){return n.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function ee(n,t){const e=[];for(let s=t-n;s"Axis must be <= rank of the tensor");const s={input:e},o={dim:t};return G.runKernel(Ma,s,o)}const Ae=D({expandDims_:sv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ov(n){const e={x:N(n,"x","expm1")};return G.runKernel(Xr,e)}const rv=D({expm1_:ov});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iv(n,t){const e=N(n,"x","tile","string_or_numeric");v(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`);const s={x:e},o={reps:t};return G.runKernel(gi,s,o)}const Nn=D({tile_:iv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function av(n,t,e,s="float32"){t==null&&(t=n);const o=wt([n,t],s),r=n<=t?n:t;for(let a=0;a`Error in localResponseNormalization: x must be rank 3 or 4 but got + rank ${r.rank}.`),v(Do(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=r,a=!1;r.rank===3&&(a=!0,i=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const c={x:i},l={depthRadius:t,bias:e,alpha:s,beta:o},u=G.runKernel(Ba,c,l);return a?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const vv=D({localResponseNormalization_:Cv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sv(n){const e={x:N(n,"x","log","float32")};return G.runKernel(_r,e)}const Pn=D({log_:Sv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kv(n){const e={x:N(n,"x","log1p")};return G.runKernel(Ur,e)}const Am=D({log1p_:kv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tv(n,t){v(Ql(n),()=>"The f passed in variableGrads(f) must be a function"),v(t==null||Array.isArray(t)&&t.every(l=>l instanceof Tc),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const e=t!=null;if(!e){t=[];for(const l in G.registeredVariables)t.push(G.registeredVariables[l])}const s=e?t.filter(l=>!l.trainable):null,o=t.length;t=t.filter(l=>l.trainable),v(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);const r=!0,{value:i,grads:a}=G.gradients(n,t,null,r);v(a.some(l=>l!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),v(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);const c={};return t.forEach((l,u)=>{a[u]!=null&&(c[l.name]=a[u])}),s!=null&&s.forEach(l=>c[l.name]=null),{value:i,grads:c}}function Jo(n){return G.customGrad(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Nv(n){const e={x:N(n,"x","neg")};return G.runKernel(ja,e)}const ne=D({neg_:Nv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rv(n){const e={x:N(n,"x","softplus")};return G.runKernel(ui,e)}const $i=D({softplus_:Rv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $v(n){const t=N(n,"x","logSigmoid");return Jo(s=>({value:ne($i(ne(s))),gradFunc:i=>E(i,_o(ne(s)))}))(t)}const Gv=D({logSigmoid_:$v});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lv(n,t){let e=N(n,"a","sub"),s=N(t,"b","sub");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(pi,o)}const pt=D({sub_:Lv});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ev(n,t=-1){const e=N(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);return Jo((o,r)=>{const a=Tn(o,t,!0),c=pt(o,a),l=pt(st(c,"float32"),Pn(ut(An(c),t,!0)));return r([l]),{value:l,gradFunc:(d,h)=>{const[p]=h,f=!0,m=An(p);return pt(d,E(ut(d,t,f),m))}}})(e)}const Pm=D({logSoftmax_:Ev});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dv(n,t=null,e=!1){const s=N(n,"x","logSumExp"),o=It(t,s.shape),r=Tn(s,o,!0),i=pt(s,r),a=An(i),c=ut(a,o),l=Pn(c),u=Q(W(r,l.shape),l);if(e){const d=re(u.shape,o);return W(u,d)}return u}const Om=D({logSumExp_:Dv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wv(n,t){const e=N(n,"a","logicalAnd","bool"),s=N(t,"b","logicalAnd","bool");gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Oa,o)}const rs=D({logicalAnd_:Wv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mv(n){const e={x:N(n,"x","logicalNot","bool")};return G.runKernel(Ka,e)}const vd=D({logicalNot_:Mv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vv(n,t){const e=N(n,"a","logicalOr","bool"),s=N(t,"b","logicalOr","bool");gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Za,o)}const Km=D({logicalOr_:Vv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fv(n,t){const e=N(n,"a","logicalXor","bool"),s=N(t,"b","logicalXor","bool");return gt(e.shape,s.shape),rs(Km(n,t),vd(rs(n,t)))}const zv=D({logicalXor_:Fv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xv(n,t,e,s,o){const r=N(n,"x","maxPool"),i=1;let a=r,c=!1;r.rank===3&&(c=!0,a=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),v(Te(e,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),ze("maxPool",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o},d=G.runKernel(_a,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Sd=D({maxPool_:Xv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Av(n,t=[1,1,1],e,s,o,r="NDHWC"){const i=N(n,"x","maxPool3d");let a=i,c=!1;i.rank===4&&(c=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),v(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),ze("maxPool3d",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o,dataFormat:r},d=G.runKernel(Ua,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Pv=D({maxPool3d_:Av});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ov(n,t){let e=N(n,"a","maximum"),s=N(t,"b","maximum");[e,s]=te(e,s),e.dtype==="bool"&&(e=st(e,"int32"),s=st(s,"int32")),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Yr,o)}const vs=D({maximum_:Ov});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kv(n,t=null,e=!1){const o={x:N(n,"x","mean")},r={axis:t,keepDims:e};return G.runKernel(Ya,o,r)}const ie=D({mean_:Kv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ge(n,t="float32"){if(es(n),t==="complex64"){const s=ge(n,"float32"),o=ge(n,"float32");return Ko(s,o)}const e=ke(Z(n),t);return G.makeTensor(e,n,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ss(n,t="float32"){if(es(n),t==="complex64"){const s=Ss(n,"float32"),o=ge(n,"float32");return Ko(s,o)}const e=jl(Z(n),t);return G.makeTensor(e,n,t)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zv(n,t){let e=N(n,"a","minimum"),s=N(t,"b","minimum");[e,s]=te(e,s),e.dtype==="bool"&&(e=st(e,"int32"),s=st(s,"int32")),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Qr,o)}const Gi=D({minimum_:Zv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bv(n,t,e){v(e==="reflect"||e==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${e}.`);const s=N(n,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");v(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);const o=e==="reflect"?1:0;for(let a=0;a"Invalid number of paddings. Must be length of 2 each."),v(t[a][0]>=0&&t[a][0]<=s.shape[a]-o&&t[a][1]>=0&&t[a][1]<=s.shape[a]-o,()=>`Padding in dimension ${a} cannot be greater than or equal to ${s.shape[a]-o} or less than 0 for input of shape ${s.shape}`);const r={paddings:t,mode:e},i={x:s};return G.runKernel(Ja,i,r)}const Hv=D({mirrorPad_:Bv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _v(n,t){let e=N(n,"a","mod"),s=N(t,"b","mod");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Jr,o)}const Uv=D({mod_:_v});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yv(n,t=null,e=!1){n=N(n,"x","moments");const s=It(t,n.shape),o=ie(n,s,e);let r=o.shape;e||(r=re(o.shape,s));const i=Bt(pt(st(n,"float32"),W(o,r))),a=ie(i,s,e);return{mean:o,variance:a}}const kd=D({moments_:Yv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qv(n,t){let e=N(n,"a","notEqual","string_or_numeric"),s=N(t,"b","notEqual","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(qa,o)}const Mc=D({notEqual_:Qv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jv(n,t,e=1,s=0,o="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i={indices:N(n,"indices","oneHot","int32")},a={dtype:o,depth:t,onValue:e,offValue:s};return G.runKernel(ec,i,a)}const Zm=D({oneHot_:Jv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jv(n){const e={x:N(n,"x","onesLike")};return G.runKernel(tc,e)}const fn=D({onesLike_:jv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qv(n,t,e=0){const s=N(n,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o={paddings:t,constantValue:e},r={x:s};return G.runKernel(sc,r,o)}const Td=D({pad_:qv});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tS(n,t,e){const s=N(n,"x","spaceToBatchND");v(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),v(e.length===t.length,()=>`paddings.shape[0] ${e.length} must be equal to [blockShape] ${t.length}`),v(s.shape.reduce((i,a,c)=>c>0&&c<=t.length?i&&(a+e[c-1][0]+e[c-1][1])%t[c-1]===0:i,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${e.toString()} must be divisible by blockShapes ${t.toString()}`);const o={x:s},r={blockShape:t,paddings:e};return G.runKernel(pc,o,r)}const Nd=D({spaceToBatchND_:tS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eS(n,t,e,s,o,r,i){o==null&&(o=[1,1]),r==null&&(r=1),s===0&&(s="valid");const a=N(n,"x","maxPool");let c=a,l=!1;a.rank===3&&(l=!0,c=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(Te(r,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'`);const u=pn(c.shape,t,r,o,s),d=[u.dilationHeight,u.dilationWidth];let h;s==="same"?h=sS([u.filterHeight,u.filterWidth],d):h=[[0,0],[0,0]];const p=d[0]===1&&d[1]===1,[f,m]=nS([u.inHeight,u.inWidth],d,h),g=p?s:"valid",b=p?c:Nd(c,d,f),I=(e==="avg"?()=>hd(b,t,r,g,i):()=>Sd(b,t,r,g,i))(),y=p?I:fd(I,d,m);return l?W(y,[y.shape[1],y.shape[2],y.shape[3]]):y}function nS(n,t,e){const s=e.map(u=>u[0]),o=e.map(u=>u[1]),r=n.concat(s,o),i=t.map((u,d)=>(u-r[d]%u)%u),a=o.map((u,d)=>u+i[d]),c=t.map((u,d)=>[s[d],a[d]]),l=t.map((u,d)=>[0,i[d]]);return[c,l]}function sS(n,t){const s=n.map((i,a)=>i+(i-1)*(t[a]-1)).map(i=>i-1),o=s.map(i=>Math.floor(i/2)),r=s.map((i,a)=>i-o[a]);return s.map((i,a)=>[o[a],r[a]])}const oS=D({pool_:eS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rS(n,t){const e=N(n,"x","prelu"),s=N(t,"alpha","prelu"),o={x:e,alpha:s};return G.runKernel(oc,o)}const Rd=D({prelu_:rS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iS(n,t=null,e=!1){let s=N(n,"x","prod");s.dtype==="bool"&&(s=st(s,"int32"));const o={x:s},r={axis:t,keepDims:e};return G.runKernel(rc,o,r)}const aS=D({prod_:iS});var $d={exports:{}};$d.exports,function(n){(function(t,e,s){function o(c){var l=this,u=a();l.next=function(){var d=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=d-(l.c=d|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(c),l.s0<0&&(l.s0+=1),l.s1-=u(c),l.s1<0&&(l.s1+=1),l.s2-=u(c),l.s2<0&&(l.s2+=1),u=null}function r(c,l){return l.c=c.c,l.s0=c.s0,l.s1=c.s1,l.s2=c.s2,l}function i(c,l){var u=new o(c),d=l&&l.state,h=u.next;return h.int32=function(){return u.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&r(d,u),h.state=function(){return r(u,{})}),h}function a(){var c=4022871197,l=function(u){u=String(u);for(var d=0;d>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.alea=i})(Zs,n,!1)}($d);var cS=$d.exports,Gd={exports:{}};Gd.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var d=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^d^d>>>8},a===(a|0)?c.x=a:l+=a;for(var u=0;u>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xor128=i})(Zs,n,!1)}(Gd);var lS=Gd.exports,Ld={exports:{}};Ld.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.next=function(){var d=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(d^d<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,a===(a|0)?c.x=a:l+=a;for(var u=0;u>>4),c.next()}function r(a,c){return c.x=a.x,c.y=a.y,c.z=a.z,c.w=a.w,c.v=a.v,c.d=a.d,c}function i(a,c){var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xorwow=i})(Zs,n,!1)}(Ld);var uS=Ld.exports,Ed={exports:{}};Ed.exports,function(n){(function(t,e,s){function o(a){var c=this;c.next=function(){var u=c.x,d=c.i,h,p;return h=u[d],h^=h>>>7,p=h^h<<24,h=u[d+1&7],p^=h^h>>>10,h=u[d+3&7],p^=h^h>>>3,h=u[d+4&7],p^=h^h<<7,h=u[d+7&7],h=h^h<<13,p^=h^h<<9,u[d]=p,c.i=d+1&7,p};function l(u,d){var h,p=[];if(d===(d|0))p[0]=d;else for(d=""+d,h=0;h0;--h)u.next()}l(c,a)}function r(a,c){return c.x=a.x.slice(),c.i=a.i,c}function i(a,c){a==null&&(a=+new Date);var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(u.x&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xorshift7=i})(Zs,n,!1)}(Ed);var dS=Ed.exports,Dd={exports:{}};Dd.exports,function(n){(function(t,e,s){function o(a){var c=this;c.next=function(){var u=c.w,d=c.X,h=c.i,p,f;return c.w=u=u+1640531527|0,f=d[h+34&127],p=d[h=h+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=d[h]=f^p,c.i=h,f+(u^u>>>16)|0};function l(u,d){var h,p,f,m,g,b=[],x=128;for(d===(d|0)?(p=d,d=null):(d=d+"\0",p=0,x=Math.max(x,d.length)),f=0,m=-32;m>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,h=b[m&127]^=p+g,f=h==0?f+1:0);for(f>=128&&(b[(d&&d.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=b[f+34&127],h=b[f=f+1&127],p^=p<<13,h^=h<<17,p^=p>>>15,h^=h>>>12,b[f]=p^h;u.w=g,u.X=b,u.i=f}l(c,a)}function r(a,c){return c.i=a.i,c.w=a.w,c.X=a.X.slice(),c}function i(a,c){a==null&&(a=+new Date);var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(u.X&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xor4096=i})(Zs,n,!1)}(Dd);var hS=Dd.exports,Wd={exports:{}};Wd.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.next=function(){var d=c.b,h=c.c,p=c.d,f=c.a;return d=d<<25^d>>>7^h,h=h-p|0,p=p<<24^p>>>8^f,f=f-d|0,c.b=d=d<<20^d>>>12^h,c.c=h=h-p|0,c.d=p<<16^h>>>16^f,c.a=f-d|0},c.a=0,c.b=0,c.c=-1640531527,c.d=1367130551,a===Math.floor(a)?(c.a=a/4294967296|0,c.b=a|0):l+=a;for(var u=0;u>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.tychei=i})(Zs,n,!1)}(Wd);var pS=Wd.exports,Bm={exports:{}};const fS=bw(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));(function(n){(function(t,e,s){var o=256,r=6,i=52,a="random",c=s.pow(o,r),l=s.pow(2,i),u=l*2,d=o-1,h;function p(y,w,C){var k=[];w=w==!0?{entropy:!0}:w||{};var S=b(g(w.entropy?[y,I(e)]:y??x(),3),k),T=new f(k),R=function(){for(var L=T.g(r),V=c,F=0;L=u;)L/=2,V/=2,F>>>=1;return(L+F)/V};return R.int32=function(){return T.g(4)|0},R.quick=function(){return T.g(4)/4294967296},R.double=R,b(I(T.S),e),(w.pass||C||function(L,V,F,X){return X&&(X.S&&m(X,T),L.state=function(){return m(T,{})}),F?(s[a]=L,V):L})(R,S,"global"in w?w.global:this==s,w.state)}function f(y){var w,C=y.length,k=this,S=0,T=k.i=k.j=0,R=k.S=[];for(C||(y=[C++]);S=1||i===0);const a=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*o*a,e=this.mean+this.stdDev*r*a,(!this.truncated||this.isValidTruncated(t))&&(s=!0)}return(!this.truncated||this.isValidTruncated(e))&&(this.nextVal=this.convertValue(e)),this.convertValue(t)}convertValue(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)}isValidTruncated(t){return t<=this.upper&&t>=this.lower}}class CS{constructor(t=0,e=1,s,o){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=t,this.range=e-t,this.dtype=s,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${t} - ${e} <= 1 and dtype is not float`);this.random=Md.alea(o)}convertValue(t){return this.canReturnFloat()?t:Math.round(t)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vS(n,t=0,e=1,s,o){if(es(n),s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const r=new Hm(t,e,s,!1,o),i=wt(n,s);for(let a=0;a`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),v(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),v(l.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`),v(l.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);const h=c.shape[2],p=c.shape[3];v(l.shape[2]===h*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*p}, but got ${l.shape[2]}.`);const f=xd(u,c,s,o,i,r),g=so(f,l,1,"valid",i);return d?W(g,[g.shape[1],g.shape[2],g.shape[3]]):g}const Jm=D({separableConv2d_:MS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VS(n){const e={x:N(n,"x","sign")};return G.runKernel(ci,e)}const FS=D({sign_:VS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zS(n){const e={x:N(n,"x","sin","float32")};return G.runKernel(ii,e)}const jm=D({sin_:zS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XS(n){const e={x:N(n,"x","sinh")};return G.runKernel(ai,e)}const qm=D({sinh_:XS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AS(n,t,e){const s=N(n,"x","slice1d");return v(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Xt(s,[t],[e])}const Vd=D({slice1d_:AS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PS(n,t,e){const s=N(n,"x","slice2d");return v(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const tg=D({slice2d_:PS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OS(n,t,e){const s=N(n,"x","slice3d");return v(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const Fd=D({slice3d_:OS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KS(n,t,e){const s=N(n,"x","slice4d");return v(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const Fc=D({slice4d_:KS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZS(n,t=-1){const e=N(n,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and dim was ${t}`);const s={logits:e},o={dim:t};return G.runKernel(mc,s,o)}const zd=D({softmax_:ZS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BS(n){v(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const t={input:n};return G.runKernel(vu,t)}const eg=D({fft_:BS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HS(n){v(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const t={input:n};return G.runKernel(Tu,t)}const Xd=D({ifft_:HS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _S(n){const t=n.shape[n.shape.length-1],e=n.size/t;let s;if(t<=2){const o=W(n,[e,t]);s=Xd(o)}else{const o=[e,2*(t-1)],r=W(Vc(n),[e,t]),i=W(wd(n),[e,t]),a=ao(Xt(r,[0,1],[e,t-2]),1),c=E(ao(Xt(i,[0,1],[e,t-2]),1),Gt(-1)),l=Xe([r,a],1),u=Xe([i,c],1),d=W(Ko(l,u),[o[0],o[1]]);s=Xd(d)}if(s=Vc(s),n.rank===3&&n.shape[0]!==0){const o=s,r=n.shape[0];s=W(s,[r,s.shape[0]/r,s.shape[1]]),o.dispose()}return s}const US=D({irfft_:_S});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YS(n,t,e=0){const o={x:N(n,"x","split")},r={numOrSizeSplits:t,axis:e};return G.runKernel(fc,o,r)}const on=D({split_:YS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QS(n,t){v(n.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let e=n.shape[n.shape.length-1];const s=n.size/e;let o;if(t!=null&&t0),m=n.shape.map(g=>g);m[n.shape.length-1]=t,o=Xt(n,f,m),e=t}else if(t!=null&&t>e){const f=n.shape.map(m=>m);f[n.shape.length-1]=t-e,o=Xe([n,ge(f)],n.shape.length-1),e=t}else o=n;const r=St(o),i=W(Ko(o,r),[s,e]),a=eg(i),c=Math.floor(e/2)+1,l=Vc(a),u=wd(a),d=on(l,[c,e-c],l.shape.length-1),h=on(u,[c,e-c],u.shape.length-1),p=o.shape.slice();return p[o.shape.length-1]=c,W(Ko(d[0],h[0]),p)}const JS=D({rfft_:QS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jS(n,t){let e=N(n,"a","squaredDifference"),s=N(t,"b","squaredDifference");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s},r={};return G.runKernel(hi,o,r)}const qS=D({squaredDifference_:jS});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tk(n,t){const e=N(n,"x","squeeze","string_or_numeric");return W(e,fs(e.shape,t).newShape)}const Di=D({squeeze_:tk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ek(n,t=0){const e=gm(n,"tensors","stack","string_or_numeric");v(e.length>=1,()=>"Pass at least one tensor to tf.stack"),e.length>0&&v(t<=e[0].rank,()=>"Axis must be <= rank of the tensor");const s=e,o={axis:t};return G.runKernel(nc,s,o)}const On=D({stack_:ek});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nk(n,t=0){const s={x:N(n,"x","step")},o={alpha:t};return G.runKernel(bi,s,o)}const Wi=D({step_:nk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sk(n,t,e,s,o=0,r=0,i=0,a=0,c=0){const u={x:N(n,"x","stridedSlice","string_or_numeric")},d={begin:t,end:e,strides:s,beginMask:o,endMask:r,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:c};return G.runKernel(Au,u,d)}const ok=D({stridedSlice_:sk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rk(n){const e={x:N(n,"x","tan","float32")};return G.runKernel(fi,e)}const ik=D({tan_:rk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ue(n,t){_l(n);const e=wi(n,t);if(e.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ci(n,null,e,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ad(n,t,e){if(_l(n),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=wi(n,e);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ci(n,t,s,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ak(n,t,e){if(_l(n),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const s=wi(n,e);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ci(n,t,s,e)}function ng(n,t,e){const s=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,r=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${n}, sliceDim: ${s}, and batchDim: ${o}.`;if(e.rank1?t.shape[s-1]:1,r=e.length;let i=1;for(let d=o;d= 0 but got ${t}`);if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const r={x:s},i={k:t,sorted:e},[a,c]=G.runKernel(Pu,r,i);return{values:a,indices:c}}const uk=D({topk_:lk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dk(n,t=0,e=1,s,o){if(es(n),s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const r=new Hm(t,e,s,!0,o),i=wt(n,s);for(let a=0;a0,()=>"The input tensor must be at least 1D");const s={x:e},o={axis:t},[r,i]=G.runKernel(Ku,s,o);return{values:r,indices:i}}const pk=D({unique_:hk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fk(n,t,e){const s=N(n,"x","unsortedSegmentSum"),o=N(t,"segmentIds","unsortedSegmentSum","int32");v(Do(e),()=>"numSegments must be of dtype int");const r={x:s,segmentIds:o},i={numSegments:e};return G.runKernel(bc,r,i)}const og=D({unsortedSegmentSum_:fk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mk(n,t=0){const e=N(n,"x","unstack","string_or_numeric");v(t>=-e.shape.length&&t`Axis = ${t} is not in [-${e.shape.length}, ${e.shape.length})`);const s={value:e},o={axis:t};return G.runKernel(gc,s,o)}const lo=D({unstack_:mk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gk(n,t=!0,e,s){return G.makeVariable(n,t,e,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rg(n,t){const e=[];for(let r=0;ra).reverse()),v(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(i=>{v(i>=0&&i`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();const o={x:s},r={perm:t};return s.dtype==="complex64"?M(()=>{let i=Vc(s),a=wd(s);return i=G.runKernel(zo,{x:i},r),a=G.runKernel(zo,{x:a},r),e&&(a=ne(a)),Ko(i,a)}):G.runKernel(zo,o,r)}const kt=D({transpose_:bk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xk(n,t){if(t==null)return n.shape.slice();if(Rt(n.shape,t))return t;if(n.shape.length===t.length){const e=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),v(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return n instanceof ae?o.clone():o;const r=xk(o,e),i=1-t,a=dt(Dc(Q(Li(r,0,1,"float32",s),i)),i);return E(o,a)}const Ik=D({dropout_:yk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wk(n,t,e,s,o,r="NHWC",i){let a=n;n.rank===3&&(a=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let c=t;c.rank===3&&(c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),v(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),v(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),v(e.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${e}.`);const l=r==="NHWC"?a.shape[3]:a.shape[1],u=r==="NHWC"?c.shape[3]:c.shape[1];v(l===e[2],()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${e[2]}.`),v(u===e[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${e[3]}).`),ze("conv2dDerFilter",o,i);const d={x:a,dy:c},h={strides:s,pad:o,dataFormat:r,dimRoundingMode:i,filterShape:e};return G.runKernel(uu,d,h)}const Pd=D({conv2DBackpropFilter_:wk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Od(n,t,e){if(e==null||e==="linear")return n;if(e==="relu")return E(n,Wi(t));throw new Error(`Cannot compute gradient for fused activation ${e}.`)}function Kd(n,t){let e=t;const s=ce(n.shape,t.shape);return s.length>0&&(e=ut(e,s)),W(e,n.shape)}function Zd(n,t,e,s){if(t==="linear")return n;if(t==="relu")return io(n);if(t==="elu")return Gc(n);if(t==="relu6")return _m(n);if(t==="prelu")return Rd(n,e);if(t==="leakyrelu")return Cd(n,s);if(t==="sigmoid")return _o(n);throw new Error(`Unknown fused activation ${t}.`)}const Bd=(n,t)=>!(n>0)||t==="linear";/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ck({x:n,filter:t,strides:e,pad:s,dataFormat:o="NHWC",dilations:r=[1,1],dimRoundingMode:i,bias:a,activation:c="linear",preluActivationWeights:l,leakyreluAlpha:u}){if(c=c||"linear",Bd(G.state.gradientDepth,c)===!1){v(o==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${o} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let C=so(n,t,e,s,o,r,i);return a!=null&&(C=Q(C,a)),Zd(C,c,l,u)}const d=N(n,"x","conv2d","float32"),h=N(t,"filter","conv2d","float32");let p=d,f=!1;d.rank===3&&(f=!0,p=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),v(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),v(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),ze("fused conv2d",s,i);const m=o==="NHWC"?p.shape[3]:p.shape[1];v(h.shape[2]===m,()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`),v(Te(e,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`);const g=ye(p.shape,h.shape,e,r,s,i);let b;a!=null&&(b=N(a,"bias","fused conv2d"),[b]=te(b,d),o==="NHWC"?gt(g.outShape,b.shape):(v(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),v(b.shape.length===0||b.shape[0]===g.outChannels||b.shape[0]===1,()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let x;if(l!=null){const C=l.shape;if(v(C.length<=1||C.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${C.length}.`),C.length===1)v(C[0]===1||C[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the number of output channels (${g.outChannels}).`);else if(C.length===3)try{gt(C,g.outShape)}catch{const S=`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(S)}x=N(l,"prelu weights","fused conv2d")}const I=(C,k)=>{v(o==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${o} but only NHWC is currently supported.`);const[S,T,R,L]=k,V=Od(C,R,c);v(eo(r),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const F=md(T.shape,V,S,e,s),X=Pd(T,V,S.shape,e,s),A=[F,X];if(L!=null){const P=Kd(L,V);A.push(P)}return A},y={x:p,filter:h,bias:b,preluActivationWeights:x},w={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i,activation:c,leakyreluAlpha:u};return a==null?Jo((k,S,T)=>{let R=G.runKernel(Ic,y,w);return T([S,k,R]),f&&(R=W(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:I}})(p,h):Jo((k,S,T,R)=>{let L=G.runKernel(Ic,y,w);return R([S,k,L,T]),f&&(L=W(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:I}})(p,h,b)}const vk=D({fusedConv2d_:Ck});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sk(n,t,e,s,o,r=[1,1],i){let a=n;n.rank===3&&(a=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let c=t;c.rank===3&&(c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:a,dy:c},u={strides:s,pad:o,dimRoundingMode:i,dilations:r,filterShape:e};return G.runKernel(bu,l,u)}const kk=D({depthwiseConv2dNativeBackpropFilter_:Sk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tk(n,t,e,s,o,r=[1,1],i){let a=t,c=!1;t.rank===3&&(c=!0,a=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:a,filter:e},u={strides:s,pad:o,dimRoundingMode:i,dilations:r,inputShape:n},d=G.runKernel(xu,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Nk=D({depthwiseConv2dNativeBackpropInput_:Tk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rk({a:n,b:t,transposeA:e=!1,transposeB:s=!1,bias:o,activation:r="linear",preluActivationWeights:i,leakyreluAlpha:a=.2}){if(Bd(G.state.gradientDepth,r)===!1){let L=$t(n,t,e,s);return o!=null&&(L=Q(L,o)),Zd(L,r,i,a)}let c=N(n,"a","fused matMul"),l=N(t,"b","fused matMul");[c,l]=te(c,l);const u=e?c.shape[c.rank-2]:c.shape[c.rank-1],d=s?l.shape[l.rank-1]:l.shape[l.rank-2],h=e?c.shape[c.rank-1]:c.shape[c.rank-2],p=s?l.shape[l.rank-2]:l.shape[l.rank-1],f=c.shape.slice(0,-2),m=l.shape.slice(0,-2),g=Z(f),b=Z(m);v(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${c.shape} and ${l.shape} and transposeA=${e} and transposeB=${s} must match.`);const I=gt(c.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,p]),y=e?W(c,[g,u,h]):W(c,[g,h,u]),w=s?W(l,[b,p,d]):W(l,[b,d,p]);let C;o!=null&&(C=N(o,"bias","fused matMul"),[C]=te(C,c),gt(I,C.shape));let k;i!=null&&(k=N(i,"prelu weights","fused matMul"));const S=(L,V)=>{const[F,X,A,P]=V,B=Od(W(L,A.shape),A,r);let K,H;if(!e&&!s?(K=$t(B,X,!1,!0),H=$t(F,B,!0,!1)):!e&&s?(K=$t(B,X,!1,!1),H=$t(B,F,!0,!1)):e&&!s?(K=$t(X,B,!1,!0),H=$t(F,B,!1,!1)):(K=$t(X,B,!0,!0),H=$t(B,F,!0,!0)),o!=null){const U=Kd(P,B);return[K,H,U]}else return[K,H]},T={a:y,b:w,bias:C,preluActivationWeights:k},R={transposeA:e,transposeB:s,activation:r,leakyreluAlpha:a};return o==null?Jo((V,F,X)=>{const A=G.runKernel(yc,T,R);return X([V,F,A]),{value:W(A,I),gradFunc:S}})(y,w):Jo((V,F,X,A)=>{const P=G.runKernel(yc,T,R);return A([V,F,P,X]),{value:W(P,I),gradFunc:S}})(y,w,C)}const ig=D({fusedMatMul_:Rk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $k(n,t,e,s,o="bilinear",r=0){const i=N(n,"image","cropAndResize"),a=N(t,"boxes","cropAndResize","float32"),c=N(e,"boxInd","cropAndResize","int32"),l=a.shape[0];v(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),v(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${a.shape}.`),v(c.rank===1&&c.shape[0]===l,()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${a.shape}.`),v(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),v(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),v(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);const u={image:i,boxes:a,boxInd:c},d={method:o,extrapolationValue:r,cropSize:s};return G.runKernel(fu,u,d)}const Gk=D({cropAndResize_:$k});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lk(n){const t=N(n,"image","flipLeftRight","float32");v(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const e={image:t};return G.runKernel(ku,e,{})}const Ek=D({flipLeftRight_:Lk});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dk(n){const t=N(n,"image","grayscaleToRGB"),e=t.rank-1,s=t.shape[e];v(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),v(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);const o=new Array(t.rank);return o.fill(1,0,e),o[e]=3,Nn(t,o)}const Wk=D({grayscaleToRGB_:Dk});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mk(n){const t=N(n,"image","RGBToGrayscale"),e=t.rank-1,s=t.shape[e];v(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),v(s===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);const o=t.dtype,r=st(t,"float32"),i=Ue([.2989,.587,.114]);let a;switch(t.rank){case 2:a=Ri("ij,j->i",r,i);break;case 3:a=Ri("ijk,k->ij",r,i);break;case 4:a=Ri("ijkl,l->ijk",r,i);break;case 5:a=Ri("ijklm,m->ijkl",r,i);break;case 6:a=Ri("ijklmn,n->ijklm",r,i);break;default:throw new Error("Not a valid tensor rank.")}return a=Ae(a,-1),st(a,o)}const Vk=D({rgbToGrayscale_:Mk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fk(n,t,e=0,s=.5){const o=N(n,"image","rotateWithOffset","float32");v(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);const r={image:o},i={radians:t,fillValue:e,center:s};return G.runKernel(Bu,r,i)}const zk=D({rotateWithOffset_:Fk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jo(n,t,e,s,o,r){s==null&&(s=.5),o==null&&(o=Number.NEGATIVE_INFINITY),r==null&&(r=0);const i=n.shape[0];return e=Math.min(e,i),v(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),v(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),v(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),v(t.rank===1,()=>"scores must be a 1D tensor"),v(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),v(0<=r&&r<=1,()=>`softNmsSigma must be in [0, 1], but was '${r}'`),{maxOutputSize:e,iouThreshold:s,scoreThreshold:o,softNmsSigma:r}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY){const r=N(n,"boxes","nonMaxSuppression","float32"),i=N(t,"scores","nonMaxSuppression","float32"),a=jo(r,i,e,s,o);e=a.maxOutputSize,s=a.iouThreshold,o=a.scoreThreshold;const c={maxOutputSize:e,iouThreshold:s,scoreThreshold:o};return G.runKernel(Lu,{boxes:r,scores:i},c)}const Ak=D({nonMaxSuppression_:Xk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pk(n,t,e){const s=Ok(n,t,e),o=s<0?-(s+1):s;n.splice(o,0,t)}function Ok(n,t,e){return Zk(n,t,e||Kk)}function Kk(n,t){return n>t?1:n>>1);const a=e(t,n[r]);a>0?s=r+1:(o=r,i=!a)}return i?s:-s-1}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hd(n,t,e,s,o){return Yd(n,t,e,s,o,0)}function _d(n,t,e,s,o,r){return Yd(n,t,e,s,o,0,!1,r,!0)}function Ud(n,t,e,s,o,r){return Yd(n,t,e,s,o,r,!0)}function Yd(n,t,e,s,o,r,i=!1,a=!1,c=!1){const l=[];for(let g=0;go&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(ag);const u=r>0?-.5/r:0,d=[],h=[];for(;d.length0;){const g=l.pop(),{score:b,boxIndex:x,suppressBeginIndex:I}=g;if(b=I;--w){const C=Bk(n,x,d[w]);if(C>=s){y=!0;break}if(g.score=g.score*Hk(s,u,C),g.score<=o)break}g.suppressBeginIndex=d.length,y||(g.score===b?(d.push(x),h.push(g.score)):g.score>o&&Pk(l,g,ag))}const p=d.length,f=e-p;a&&f>0&&(d.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));const m={selectedIndices:d};return i&&(m.selectedScores=h),c&&(m.validOutputs=p),m}function Bk(n,t,e){const s=n.subarray(t*4,t*4+4),o=n.subarray(e*4,e*4+4),r=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),a=Math.max(s[0],s[2]),c=Math.max(s[1],s[3]),l=Math.min(o[0],o[2]),u=Math.min(o[1],o[3]),d=Math.max(o[0],o[2]),h=Math.max(o[1],o[3]),p=(a-r)*(c-i),f=(d-l)*(h-u);if(p<=0||f<=0)return 0;const m=Math.max(r,l),g=Math.max(i,u),b=Math.min(a,d),x=Math.min(c,h),I=Math.max(b-m,0)*Math.max(x-g,0);return I/(p+f-I)}function Hk(n,t,e){const s=Math.exp(t*e*e);return e<=n?s:0}function ag(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function _k(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY){const r=N(n,"boxes","nonMaxSuppressionAsync"),i=N(t,"scores","nonMaxSuppressionAsync"),a=jo(r,i,e,s,o);e=a.maxOutputSize,s=a.iouThreshold,o=a.scoreThreshold;const c=await Promise.all([r.data(),i.data()]),l=c[0],u=c[1],{selectedIndices:d}=Hd(l,u,e,s,o);return r!==n&&r.dispose(),i!==t&&i.dispose(),Ue(d,"int32")}const Uk=_k;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=0){const i=N(n,"boxes","nonMaxSuppression"),a=N(t,"scores","nonMaxSuppression"),c=jo(i,a,e,s,o,r);e=c.maxOutputSize,s=c.iouThreshold,o=c.scoreThreshold,r=c.softNmsSigma;const l={boxes:i,scores:a},u={maxOutputSize:e,iouThreshold:s,scoreThreshold:o,softNmsSigma:r},d=G.runKernel(Du,l,u);return{selectedIndices:d[0],selectedScores:d[1]}}const Qk=D({nonMaxSuppressionWithScore_:Yk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function Jk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=0){const i=N(n,"boxes","nonMaxSuppressionAsync"),a=N(t,"scores","nonMaxSuppressionAsync"),c=jo(i,a,e,s,o,r);e=c.maxOutputSize,s=c.iouThreshold,o=c.scoreThreshold,r=c.softNmsSigma;const l=await Promise.all([i.data(),a.data()]),u=l[0],d=l[1],{selectedIndices:h,selectedScores:p}=Ud(u,d,e,s,o,r);return i!==n&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ue(h,"int32"),selectedScores:Ue(p)}}const jk=Jk;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=!1){const i=N(n,"boxes","nonMaxSuppression"),a=N(t,"scores","nonMaxSuppression"),c=jo(i,a,e,s,o,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,h={boxes:i,scores:a},p={maxOutputSize:l,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:r},f=G.runKernel(Eu,h,p);return{selectedIndices:f[0],validOutputs:f[1]}}const tT=D({nonMaxSuppressionPadded_:qk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function eT(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=!1){const i=N(n,"boxes","nonMaxSuppressionAsync"),a=N(t,"scores","nonMaxSuppressionAsync"),c=jo(i,a,e,s,o,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,[h,p]=await Promise.all([i.data(),a.data()]),{selectedIndices:f,validOutputs:m}=_d(h,p,l,u,d,r);return i!==n&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ue(f,"int32"),validOutputs:Gt(m,"int32")}}const nT=eT;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sT(n,t,e=!1,s=!1){const o=N(n,"images","resizeBilinear");v(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),v(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),v(s===!1||e===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let r=o,i=!1;o.rank===3&&(i=!0,r=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const a={images:r},c={alignCorners:e,halfPixelCenters:s,size:t},l=G.runKernel(cc,a,c);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const cg=D({resizeBilinear_:sT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oT(n,t,e=!1,s=!1){const o=N(n,"images","resizeNearestNeighbor");v(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),v(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),v(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),v(s===!1||e===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let r=o,i=!1;o.rank===3&&(i=!0,r=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const a={images:r},c={alignCorners:e,halfPixelCenters:s,size:t},l=G.runKernel(ac,a,c);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const lg=D({resizeNearestNeighbor_:oT});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rT(n,t="binary",e=!1,s=.5){const o=N(n,"image","threshold"),r=.2989,i=.587,a=.114,c=o.shape[0]*o.shape[1];let l=E(Ue([s]),255),u,d,h,p;if(v(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),v(o.shape[2]===3||o.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`),v(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),v(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),o.shape[2]===3){[u,d,h]=on(o,[1,1,1],-1);const g=E(u,r),b=E(d,i),x=E(h,a);p=Q(Q(g,b),x)}else p=n;if(t==="otsu"){const g=o2(st(Um(p),"int32"),tn([]),256);l=iT(g,c)}const f=e?Qo(p,l):sn(p,l);return st(E(f,255),"int32")}function iT(n,t){let e=Ue([-1]),s=Ue([0]),o=Ue([0]),r,i,a,c,l,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${i.rank}.`),v(a.rank===2&&(a.shape[0]===i.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),v(r==null||r.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${r}.`);const c={image:i,transforms:a},l={interpolation:e,fillMode:s,fillValue:o,outputShape:r};return G.runKernel(Ou,c,l)}const lT=D({transform_:cT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uT(n,t,e){const s=N(n,"a","bandPart");v(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const o=s.shape,[r,i]=s.shape.slice(-2);let a,c;typeof t=="number"?(v(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),v(t<=r,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`),a=N(t<0?r:t,"numLower","bandPart")):(v(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),a=Le(Wc(t,0),r,Gi(t,r))),typeof e=="number"?(v(e%1===0,()=>`bandPart(): numUpper must be an integer, got ${e}.`),v(e<=i,()=>`bandPart(): numUpper (${e}) must not be greater than the number of columns (${i}).`),c=N(e<0?i:e,"numUpper","bandPart")):(v(e.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),c=Le(Wc(e,0),i,Gi(e,i)));const l=W(Ei(0,r,1,"int32"),[-1,1]),u=Ei(0,i,1,"int32"),d=pt(l,u),h=rs(Qo(d,a),oo(d,ne(c))),p=ge([r,i],s.dtype);return W(On(lo(W(s,[-1,r,i])).map(f=>Le(h,f,p))),o)}const dT=D({bandPart_:uT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hT(n){let t;if(Array.isArray(n)){t=!1,v(n!=null&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const o=n[0].shape[0];for(let r=1;r`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[r].shape[0]} vs. ${o})`)}else t=!0,n=on(n,n.shape[0],0).map(o=>Di(o,[0]));v(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const e=[],s=n;for(let o=0;o{let r=s[o];if(o>0)for(let i=0;i=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return ug(n,t);{const e=n.shape.slice(0,n.shape.length-2).reduce((c,l)=>c*l),s=lo(W(n,[e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),o=[],r=[];s.forEach(c=>{const[l,u]=ug(c,t);o.push(l),r.push(u)});const i=W(On(o,0),n.shape),a=W(On(r,0),n.shape);return[i,a]}}function ug(n,t=!1){return G.tidy(()=>{v(n.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const e=n.shape[0],s=n.shape[1];let o=Xm(e),r=to(n);const i=Ad([[1]],[1,1]);let a=to(i);const c=e>=s?s:e;for(let l=0;l{const p=Xt(r,[l,l],[e-l,1]),f=Ec(p),m=Xt(r,[l,l],[1,1]),g=Le(sn(m,0),Ad([[-1]]),Ad([[1]])),b=pt(m,E(g,f)),x=dt(p,b);x.shape[0]===1?a=to(i):a=Xe([i,Xt(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);const I=ne(dt($t(g,b),f)),y=Xt(r,[l,0],[e-l,s]),w=E(I,a),C=kt(a);if(l===0)r=pt(y,$t(w,$t(C,y)));else{const T=pt(y,$t(w,$t(C,y)));r=Xe([Xt(r,[0,0],[l,s]),T],0)}const k=kt(w),S=Xt(o,[0,l],[e,o.shape[1]-l]);if(l===0)o=pt(S,$t($t(S,a),k));else{const T=pt(S,$t($t(S,a),k));o=Xe([Xt(o,[0,0],[e,l]),T],1)}return[a,r,o]}),vt([u,d,h])}return!t&&e>s&&(o=Xt(o,[0,0],[e,s]),r=Xt(r,[0,0],[s,s])),[o,r]})}const mT=D({qr_:fT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const is={flipLeftRight:Ek,grayscaleToRGB:Wk,resizeNearestNeighbor:lg,resizeBilinear:cg,rgbToGrayscale:Vk,rotateWithOffset:zk,cropAndResize:Gk,nonMaxSuppression:Ak,nonMaxSuppressionAsync:Uk,nonMaxSuppressionWithScore:Qk,nonMaxSuppressionWithScoreAsync:jk,nonMaxSuppressionPadded:tT,nonMaxSuppressionPaddedAsync:nT,threshold:aT,transform:lT},gT={bandPart:dT,gramSchmidt:pT,qr:mT};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bT=new Map,xT=new Map;class qo{getClassName(){return this.constructor.className}static fromConfig(t,e){return new t(e)}}class mn{constructor(){this.classNameMap={}}static getMap(){return mn.instance==null&&(mn.instance=new mn),mn.instance}static register(t){mn.getMap().classNameMap[t.className]=[t,t.fromConfig]}}function _(n,t,e){v(n.className!=null,()=>"Class being registered does not have the static className property defined."),v(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),v(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof t>"u"&&(t="Custom"),typeof e>"u"&&(e=n.className);const s=e,o=t+">"+s;return mn.register(n),bT.set(o,n),xT.set(n,o),n}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ks extends qo{minimize(t,e=!1,s){const{value:o,grads:r}=this.computeGradients(t,s);if(s!=null){const i=s.map(a=>({name:a.name,tensor:r[a.name]}));this.applyGradients(i)}else this.applyGradients(r);return vt(r),e?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(t,e){return Tv(t,e)}dispose(){this.iterations_!=null&&vt(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Gt(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(t){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(t){return this.iterations_=(await t[0].tensor.data())[0],t.slice(1)}}Object.defineProperty(ks,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class dg extends ks{static get className(){return"Adadelta"}constructor(t,e,s=null){super(),this.learningRate=t,this.rho=e,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${s}/accum_grad`,variable:M(()=>St(r).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${s}/accum_var`,variable:M(()=>St(r).variable(i))});const a=Array.isArray(t)?t[o].tensor:t[s];if(a==null)return;const c=this.accumulatedGrads[o].variable,l=this.accumulatedUpdates[o].variable;M(()=>{const u=Q(E(c,this.rho),E(Bt(a),1-this.rho)),d=E(dt(Ee(Q(l,this.epsilon)),Ee(Q(c,this.epsilon))),a),h=Q(E(l,this.rho),E(Bt(d),1-this.rho));c.assign(u),l.assign(h);const p=Q(E(d,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(vt(this.accumulatedGrads.map(t=>t.variable)),vt(this.accumulatedUpdates.map(t=>t.variable)))}async getWeights(){const t=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=t.length/2,s=!1;this.accumulatedGrads=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedUpdates=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.rho,e.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class hg extends ks{static get className(){return"Adagrad"}constructor(t,e=.1){super(),this.learningRate=t,this.initialAccumulatorValue=e,this.accumulatedGrads=[]}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s];this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${s}/accumulator`,variable:M(()=>$c(r.shape,this.initialAccumulatorValue).variable(!1))});const i=Array.isArray(t)?t[o].tensor:t[s];if(i==null)return;const a=this.accumulatedGrads[o].variable;M(()=>{const c=Q(a,Bt(i));a.assign(c);const l=Q(E(dt(i,Ee(Q(c,G.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&vt(this.accumulatedGrads.map(t=>t.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=!1;this.accumulatedGrads=t.map(s=>({originalName:s.name,variable:s.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(t,e){return new t(e.learningRate,e.initialAccumulatorValue)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pg extends ks{static get className(){return"Adam"}constructor(t,e,s,o=null){super(),this.learningRate=t,this.beta1=e,this.beta2=s,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],M(()=>{this.accBeta1=Gt(e).variable(),this.accBeta2=Gt(s).variable()}),o==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);M(()=>{const s=pt(1,this.accBeta1),o=pt(1,this.accBeta2);e.forEach((r,i)=>{const a=G.registeredVariables[r],c=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:M(()=>St(a).variable(c))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${r}/v`,variable:M(()=>St(a).variable(c))});const l=Array.isArray(t)?t[i].tensor:t[r];if(l==null)return;const u=this.accumulatedFirstMoment[i].variable,d=this.accumulatedSecondMoment[i].variable,h=Q(E(u,this.beta1),E(l,1-this.beta1)),p=Q(E(d,this.beta2),E(Bt(l),1-this.beta2)),f=dt(h,s),m=dt(p,o);u.assign(h),d.assign(p);const g=Q(E(dt(f,Q(Ee(m),this.epsilon)),-this.learningRate),a);a.assign(g)}),this.accBeta1.assign(E(this.accBeta1,this.beta1)),this.accBeta2.assign(E(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&vt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedSecondMoment!=null&&vt(this.accumulatedSecondMoment.map(t=>t.variable))}async getWeights(){const t=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t),M(()=>{this.accBeta1.assign(Yo(this.beta1,this.iterations_+1)),this.accBeta2.assign(Yo(this.beta2,this.iterations_+1))});const e=t.length/2,s=!1;this.accumulatedFirstMoment=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedSecondMoment=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fg extends ks{static get className(){return"Adamax"}constructor(t,e,s,o=null,r=0){super(),this.learningRate=t,this.beta1=e,this.beta2=s,this.epsilon=o,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],M(()=>{this.iteration=Gt(0).variable(),this.accBeta1=Gt(e).variable()}),o==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);M(()=>{const s=pt(1,this.accBeta1),o=dt(-this.learningRate,Q(E(this.iteration,this.decay),1));e.forEach((r,i)=>{const a=G.registeredVariables[r],c=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:St(a).variable(c)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${r}/v`,variable:St(a).variable(c)});const l=Array.isArray(t)?t[i].tensor:t[r];if(l==null)return;const u=this.accumulatedFirstMoment[i].variable,d=this.accumulatedWeightedInfNorm[i].variable,h=Q(E(u,this.beta1),E(l,1-this.beta1)),p=E(d,this.beta2),f=Ge(l),m=vs(p,f);u.assign(h),d.assign(m);const g=Q(E(dt(o,s),dt(h,Q(m,this.epsilon))),a);a.assign(g)}),this.iteration.assign(Q(this.iteration,1)),this.accBeta1.assign(E(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&vt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedWeightedInfNorm!=null&&vt(this.accumulatedWeightedInfNorm.map(t=>t.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(t){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Qd extends ks{static get className(){return"SGD"}constructor(t){super(),this.learningRate=t,this.setLearningRate(t)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=Array.isArray(t)?t[o].tensor:t[s];if(r==null)return;const i=G.registeredVariables[s];M(()=>{const a=Q(E(this.c,r),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(t){this.learningRate=t,this.c!=null&&this.c.dispose(),this.c=en(Gt(-t))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(t){if(t=await this.extractIterations(t),t.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(t,e){return new t(e.learningRate)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class mg extends Qd{static get className(){return"Momentum"}constructor(t,e,s=!1){super(t),this.learningRate=t,this.momentum=e,this.useNesterov=s,this.accumulations=[],this.m=Gt(this.momentum)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s];this.accumulations[o]==null&&(this.accumulations[o]={originalName:`${s}/momentum`,variable:M(()=>St(r).variable(!1))});const i=this.accumulations[o].variable,a=Array.isArray(t)?t[o].tensor:t[s];a!=null&&M(()=>{let c;const l=Q(E(this.m,i),a);this.useNesterov?c=Q(E(this.c,Q(a,E(l,this.m))),r):c=Q(E(this.c,l),r),i.assign(l),r.assign(c)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&vt(this.accumulations.map(t=>t.variable))}setMomentum(t){this.momentum=t}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=!1;this.accumulations=t.map(s=>({originalName:s.name,variable:s.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class gg extends ks{static get className(){return"RMSProp"}constructor(t,e=.9,s=0,o=null,r=!1){if(super(),this.learningRate=t,this.decay=e,this.momentum=s,this.epsilon=o,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,o==null&&(this.epsilon=G.backend.epsilon()),t==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${s}/rms`,variable:M(()=>St(r).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${s}/momentum`,variable:M(()=>St(r).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${s}/mg`,variable:M(()=>St(r).variable(i))});const a=Array.isArray(t)?t[o].tensor:t[s];if(a==null)return;const c=this.accumulatedMeanSquares[o].variable,l=this.accumulatedMoments[o].variable;M(()=>{const u=Q(E(c,this.decay),E(Bt(a),1-this.decay));if(this.centered){const d=this.accumulatedMeanGrads[o].variable,h=Q(E(d,this.decay),E(a,1-this.decay)),p=dt(E(a,this.learningRate),Ee(pt(u,Q(Bt(h),this.epsilon)))),f=Q(E(l,this.momentum),p);c.assign(u),d.assign(h),l.assign(f);const m=pt(r,f);r.assign(m)}else{const d=Q(E(c,this.decay),E(Bt(a),1-this.decay)),h=Q(E(l,this.momentum),dt(E(a,this.learningRate),Ee(Q(d,this.epsilon))));c.assign(d),l.assign(h);const p=pt(r,h);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&vt(this.accumulatedMeanSquares.map(t=>t.variable)),this.accumulatedMeanGrads!=null&&this.centered&&vt(this.accumulatedMeanGrads.map(t=>t.variable)),this.accumulatedMoments!=null&&vt(this.accumulatedMoments.map(t=>t.variable))}async getWeights(){const t=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&t.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=this.centered?t.length/3:t.length/2,s=!1;this.accumulatedMeanSquares=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedMoments=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=t.slice(e*2,e*3).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yT=[dg,hg,pg,fg,mg,gg,Qd];function IT(){for(const n of yT)_(n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let uo;function wT(n,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let e=!1,s=!1,o=!1,r=!1,i=!1,a=!1;if(n.data instanceof Uint8Array)e=!0;else if(typeof ImageData<"u"&&n instanceof ImageData)s=!0;else if(typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement)r=!0;else if(n.getContext!=null)i=!0;else if(typeof ImageBitmap<"u"&&n instanceof ImageBitmap)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${n.constructor.name}`);if(_u(Zu,G.backendName)!=null){const f={pixels:n},m={numChannels:t};return G.runKernel(Zu,f,m)}const[l,u]=o?[n.videoWidth,n.videoHeight]:[n.width,n.height];let d;if(i)d=n.getContext("2d").getImageData(0,0,l,u).data;else if(s||e)d=n.data;else if(r||o||a){if(uo==null)if(typeof document>"u")if(typeof OffscreenCanvas<"u"&&typeof OffscreenCanvasRenderingContext2D<"u")uo=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else uo=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});uo.canvas.width=l,uo.canvas.height=u,uo.drawImage(n,0,0,l,u),d=uo.getImageData(0,0,l,u).data}let h;if(t===4)h=new Int32Array(d);else{const f=l*u;h=new Int32Array(f*t);for(let m=0;me)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${e}`);if(Z(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const o=t.shape,r=o[o.length-1];let i=1;for(let d=0;dd/l),1].slice(0,r);return[c,i,l,u]}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jd=-2,vT=-1;function qd(n,t,e){const s=n.shape.length;v(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),v(s===e.length,()=>`Error in slice${s}D: Length of size ${e} must match the rank of the array (${s}).`);for(let o=0;o`Error in slice${s}D: begin[${o}] + size[${o}] (${t[o]+e[o]}) would overflow input.shape[${o}] (${n.shape[o]})`)}function ST(n){const t=[];let e=0;for(;n>0;)n&1&&t.push(e),n/=2,e++;return t}function th(n,t,e){const s=[];for(let o=0;o0){const p=t[0],f=e+1;u=Ig(i,p,f,s,n),d=wg(a,p,f,o,n),h=bg(r,p,f,n)}else for(let p=0;p-1)r[a]=0;else{const c=xg(t,e,a);let l=s[c];n&1<-1)r[a]=Number.MAX_SAFE_INTEGER;else{const c=xg(t,e,a);let l=s[c];n&1<0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);const c=s[o];return i<0&&(i+=c),i=Ks(0,i,c-1),i}function Sg(n,t,e,s,o,r){let i=t[o];const a=e[o]||1;(n&1<0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);const c=s[o];return i<0&&(i+=c),a>0?i=Ks(0,i,c):i=Ks(-1,i,c-1),i}function eh(n,t,e){let s=e.length;for(let o=0;o1){s=o;break}for(let o=s+1;o0||e[o]!==n[o])return!1;return!0}function nh(n,t){let e=n.length>0?n[n.length-1]:1;for(let s=0;s{v(i!==-1,()=>"slice() does not support negative begin indexing.")});let r;return e==null?r=new Array(o).fill(-1):typeof e=="number"?r=[e,...new Array(o-1).fill(-1)]:e.lengthi>=0?i:(v(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),n.shape[a]-s[a])),[s,r]}function sh(n,t,e,s,o,r,i,a,c){let l;if(s==null?(l=new Array(t.length),l.fill(1)):l=s,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1;const d={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:e.slice(),strides:l.slice(),beginMask:o,endMask:r,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:c};for(let I=0;I0?0:-1,h.strides[I]>0?w:w-1];if(y&&h.strides[I]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&h.strides[I]===1;const S=!!(h.beginMask&1<=w)throw Error(`slice index ${h.begin[I]} of dimension ${I} out of bounds.`)}else h.begin[I]=kg(h.begin[I],0,h.strides[I],w,C,k),h.end[I]=kg(h.end[I],1,h.strides[I],w,C,k);const L=h.strides[I]===1&&h.begin[I]===0&&h.end[I]===w;p=p&&L,f=f&&(I===0&&h.strides[I]===1||L)}else p=p&&h.strides[I]===1&&S,f=f&&(I===0&&h.strides[I]===1||S);let T,R=!1;if(h.beginValid&&h.endValid?(T=h.end[I]-h.begin[I],R=!0):y?(T=1,R=!0):S&&w>=0&&(h.strides[I]<0?T=-w:T=w,R=!0),R){let L;T===0||T<0!=h.strides[I]<0?L=0:L=Math.trunc(T/h.strides[I])+(T%h.strides[I]!==0?1:0),g.push(L)}else g.push(-1)}for(let I=0;I=0?b.push(g[y]):y===jd&&b.push(1)}return{finalShapeSparse:b.filter((I,y)=>h.finalShapeGatherIndices[y]!==jd),finalShape:b,isIdentity:p,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function TT(n,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let e=0;t.beginValid=n.begin!=null,t.endValid=n.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let s=0;s0?r[t]:r[t+1&1];{const i=n<0?s+n:n;return ir[1]?r[1]:i}}const NT=Object.freeze(Object.defineProperty({__proto__:null,assertParamsValid:qd,computeFlatOffset:nh,computeOutShape:th,getNormalizedAxes:kT,isSliceContinous:eh,maskToAxes:ST,parseSliceParams:zc,sliceInfo:sh,startForAxis:vg,startIndicesWithElidedDims:Ig,stopForAxis:Sg,stopIndicesWithElidedDims:wg,stridesForAxis:Cg,stridesWithElidedDims:bg},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class RT{static sgd(t){return new Qd(t)}static momentum(t,e,s=!1){return new mg(t,e,s)}static rmsprop(t,e=.9,s=0,o=null,r=!1){return new gg(t,e,s,o,r)}static adam(t=.001,e=.9,s=.999,o=null){return new pg(t,e,s,o)}static adadelta(t=.001,e=.95,s=null){return new dg(t,e,s)}static adamax(t=.002,e=.9,s=.999,o=null,r=0){return new fg(t,e,s,o,r)}static adagrad(t,e=.1){return new hg(t,e)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tr=RT;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $T=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function Xc(){return new Promise(n=>$T(()=>n()))}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oh(n,t){const e=n[0].length;n.forEach((o,r)=>{v(o.length===e,()=>`Error in concat${e}D: rank of tensors[${r}] must be the same as the rank of the rest (${e})`)}),v(t>=0&&t`Error in concat${e}D: axis must be between 0 and ${e-1}.`);const s=n[0];n.forEach((o,r)=>{for(let i=0;i`Error in concat${e}D: Shape of tensors[${r}] (${o}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`)})}function Kn(n,t){const e=n[0].slice();for(let s=1;s=0)if(a>=0){if(a!==r)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${o+n}] = ${r} but shape[${o+n}] = ${a}`)}else s[i]=r}return s}function Ng(n){const t={FIRST_DIM_SIZE:Rn.FIRST_DIM_SIZE,VALUE_ROWIDS:Rn.VALUE_ROWIDS,ROW_LENGTHS:Rn.ROW_LENGTHS,ROW_SPLITS:Rn.ROW_SPLITS,ROW_LIMITS:Rn.ROW_LIMITS,ROW_STARTS:Rn.ROW_STARTS},e=[];for(const s of n)if(s in t)e.push(t[s]);else break;return e}function Rg(n){return n.length===0?0:n[0]===Rn.FIRST_DIM_SIZE?n.length-1:n.length}function $g(n,t){if(n==null||t==null)return;const e=n.length,s=t.length;if(e>=s)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${e} must be less than ragged tensor input flatValues.rank = ${s})`);for(let o=0;o=0&&i>=0&&r!==1&&r!==i)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${o-n.length}] = ${r} but ragged tensor input.flatValues.shape[${o-n.length}] = ${i}`)}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rh=30;function Ac(n){return n<=rh?n:Jl(n,Math.floor(Math.sqrt(n)))}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ih(n,t,e){const s=e*(typeof n=="number"?n:n[0]),o=t*(typeof n=="number"?n:n[1]);return[s,o]}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mi(n,t,e,s=!0){let o=[];if(s)o=o.concat(t.slice(0)),o.push(n[0]/e),o=o.concat(n.slice(1));else{o=o.concat(n[0]);const r=t.length;for(let i=0;i=t*2+1||i%2===1?r.push(i):o.push(i);s.push(...o),s.push(0),s.push(...r)}return s}function Fi(n,t,e,s=!0){const o=[];s?o.push(n[0]/e):o.push(n[0]*e);for(let r=1;r/g,Vg=",",Fg="...";function bh(n,t){n=n.replace(/\s/g,"");const e=(n.length-n.replace(GT,"").length)/gh.length;if(e<1)throw new Error("Equations without an arrow are not supported.");if(e>1)throw new Error(`Equation must contain exactly one arrow ("${gh}").`);const[s,o]=n.split(gh);v(s.indexOf(Fg)===-1,()=>`The ellipsis notation ("${Fg}") is not supported yet.`);const r=s.split(Vg),i=r.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const a=[];for(let h=0;hf.indexOf(p)!==-1))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);a.indexOf(p)===-1&&a.push(p)}for(let h=0;ho!==-1),{permutationIndices:e,expandDims:s}}function yh(n,t,e){const s=new Array(n);for(let o=0;o`Expected dimension ${s[t[o][i]]} at axis ${i} of input shaped ${JSON.stringify(r)}, but got dimension ${r[i]}`)}}function Ih(n,t){const e=n,s=[];let o=0;n.length===0&&e.push(-1),o=n.length+1;for(let i=0;it===e)}function LT(n,t){const e=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(n.shape[e]/t);else{const o=t.reduce((i,a)=>(a===-1&&(i+=1),i),0);v(o<=1,()=>"There should be only one negative value in split array.");const r=t.indexOf(-1);if(r!==-1){const i=t.reduce((a,c)=>c>0?a+c:a);t[r]=n.shape[e]-i}v(n.shape[e]===t.reduce((i,a)=>i+a),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zg(n){return`Received SparseTensor with denseShape[0] = 0 but + indices.shape[0] = ${n}`}function Xg(n,t){return`indices(${n}, 0) is invalid: ${t} < 0`}function Ag(n,t,e){return`indices(${n}, 0) is invalid: ${t} >= ${e}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pg(n,t){return`only one output dimension may be -1, not both ${n} and ${t}`}function Og(n,t){return`size ${n} must be non-negative, not ${t}`}function Kg(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function Zg(n,t){const e=Z(n),s=Z(t);return`Input to reshape is a SparseTensor with ${e} + dense values, but the requested shape requires a multiple of ${s}. inputShape=${n} outputShape= ${t}`}function Bg(n,t){const e=Z(n),s=Z(t);return`Input to reshape is a tensor with ${e} dense values, but the requested shape has ${s}. inputShape=${n} outputShape=${t}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vh(){return"segment ids must be >= 0"}function Hg(){return"segment ids are not increasing"}function _g(n,t){return`Segment id ${n} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Ug(n,t,e){return`Bad: indices[${n}] == ${t} out of range [0, ${e})`}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yg(n,t){let e=!1,s;for(n<=rh?(s=n,e=!0):s=Jl(n,Math.floor(Math.sqrt(n)));!e;)s>t||s===n?e=!0:s=Jl(n,s+1);return s}function Qg(n,t,e){const s=[],o=n.length;for(let r=0;ro))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${s}`);if(s<0&&(s+=o),s>r)throw new Error(`batchDims (${s}) must be less than rank(x) ( + ${r}).`);if(exs(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function Jg(n){return n.map(t=>bs(t))}const DT=Object.freeze(Object.defineProperty({__proto__:null,ERF_A1:uh,ERF_A2:dh,ERF_A3:hh,ERF_A4:ph,ERF_A5:fh,ERF_P:lh,PARALLELIZE_THRESHOLD:rh,get RowPartitionType(){return Rn},SELU_SCALE:Oc,SELU_SCALEALPHA:Pc,applyActivation:Zd,assertAndGetBroadcastShape:gt,assertAxesAreInnerMostDims:Ie,assertParamsConsistent:oh,assignToTypedArray:Dg,axesAreInnerMostDims:yd,calculateShapes:co,checkEinsumDimSizes:yh,checkPadOnDimRoundingMode:ze,combineLocations:Fm,combineRaggedTensorToTensorShapes:Tg,complexWithEvenIndex:Lg,complexWithOddIndex:Eg,computeConv2DInfo:ye,computeConv3DInfo:ws,computeDefaultPad:ud,computeDilation2DInfo:Si,computeOptimalWindowSize:Ac,computeOutAndReduceShapes:me,computeOutShape:Kn,computePool2DInfo:pn,computePool3DInfo:ss,convertConv2DDataFormat:os,decodeEinsumEquation:bh,eitherStridesOrDilationsAreOne:Te,expandShapeToKeepDim:re,exponent:Mg,exponents:Wg,fromStringArrayToUint8:Jg,fromUint8ToStringArray:cs,getAxesPermutation:Yt,getBroadcastDims:Uo,getComplexWithIndex:mh,getEinsumComputePath:Ih,getEinsumPermutation:xh,getFusedBiasGradient:Kd,getFusedDyActivation:Od,getImageCenter:ih,getInnerMostAxes:ee,getPermuted:Vi,getRaggedRank:Rg,getReductionAxes:ce,getReshaped:Mi,getReshapedPermuted:Fi,getRowPartitionTypesHelper:Ng,getSliceBeginCoords:ah,getSliceSize:ch,getSparseFillEmptyRowsIndicesDenseShapeMismatch:zg,getSparseFillEmptyRowsNegativeIndexErrorMessage:Xg,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Ag,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:Kg,getSparseReshapeInputOutputMismatchErrorMessage:Bg,getSparseReshapeInputOutputMultipleErrorMessage:Zg,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Pg,getSparseReshapeNegativeOutputDimErrorMessage:Og,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Ug,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:vh,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Hg,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:_g,getUndoAxesPermutation:Cs,isIdentityPermutation:wh,log:fw,mergeRealAndImagArrays:as,prepareAndValidate:Jd,prepareSplitSize:Ch,segment_util:ET,shouldFuse:Bd,slice_util:NT,splitRealAndImagArrays:Gg,stridesOrDilationsArePositive:no,tupleValuesAreOne:eo,upcastType:_e,validateDefaultValueShape:$g,validateInput:ck,validateUpdateShape:ng,warn:je},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */IT();/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jg={kernelName:ya,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,Wi(st(e,"float32"),-1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WT={kernelName:vr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Bt(st(e,"float32")),o=Ee(pt(Gt(1),s));return ne(dt(n,o))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MT={kernelName:Sr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Ee(pt(Bt(st(e,"float32")),1));return dt(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VT={kernelName:Fo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{let a=n;const c=ce(e.shape,o);return c.length>0&&(a=ut(a,c)),W(a,e.shape)},b:()=>{let a=n;const c=ce(s.shape,o);return c.length>0&&(a=ut(a,c)),W(a,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FT={kernelName:nu,saveAllInputs:!0,gradFunc:(n,t)=>{const e={};return t.forEach((s,o)=>{e[o]=()=>n.clone()}),e}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zT={kernelName:Ia,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>St(e)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XT={kernelName:wa,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>St(e)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const AT={kernelName:kr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Ee(pt(Gt(1),Bt(st(e,"float32")))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PT={kernelName:Tr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Ee(Q(Gt(1),Bt(st(e,"float32"))));return dt(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OT={kernelName:$r,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=Q(Bt(e),Bt(s));let c=E(n,dt(s,a));const l=ce(e.shape,o);return l.length>0&&(c=ut(c,l)),W(c,e.shape)},b:()=>{const a=Q(Bt(e),Bt(s));let c=ne(E(n,dt(e,a)));const l=ce(s.shape,o);return l.length>0&&(c=ut(c,l)),W(c,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KT={kernelName:Nr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Q(Bt(st(e,"float32")),1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZT={kernelName:Rr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,pt(Gt(1),Bt(st(e,"float32"))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BT(n,t,e,s,o,r){const i=N(n,"dy","avgPool3dGrad"),a=N(t,"input","avgPool3dGrad");let c=i,l=a,u=!1;a.rank===4&&(u=!0,c=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=W(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),v(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),v(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),ze("avgPool3dGrad",o,r);const d={dy:c,input:l},h={filterSize:e,strides:s,pad:o,dimRoundingMode:r},p=G.runKernel(iu,d,h);return u?W(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const HT=D({avgPool3dGrad_:BT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _T={kernelName:va,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:o,strides:r,pad:i,dimRoundingMode:a}=e;return{x:()=>HT(n,s,o,r,i,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UT(n,t,e,s,o){const r=N(n,"dy","avgPoolGrad"),i=N(t,"input","avgPoolGrad");v(i.rank===r.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${r.rank})`);let a=i,c=r,l=!1;i.rank===3&&(l=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),v(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);const u={dy:c,input:a},d={filterSize:e,strides:s,pad:o},h=G.runKernel(ru,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const YT=D({avgPoolGrad_:UT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QT={kernelName:Ca,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:o,strides:r,pad:i}=e;return{x:()=>YT(n,s,o,r,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JT={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(n,t,e)=>{const[s,o]=t,{transposeA:r,transposeB:i}=e;return!r&&!i?{a:()=>$t(n,o,!1,!0),b:()=>$t(s,n,!0,!1)}:!r&&i?{a:()=>$t(n,o,!1,!1),b:()=>$t(n,s,!0,!1)}:r&&!i?{a:()=>$t(o,n,!1,!0),b:()=>$t(s,n,!1,!1)}:{a:()=>$t(o,n,!0,!0),b:()=>$t(n,s,!0,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jT={kernelName:ka,gradFunc:(n,t,e)=>{const{blockShape:s,crops:o}=e;return{x:()=>Nd(n,s,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qT={kernelName:dw,gradFunc:(n,t,e)=>{const s=e,o=s.inputShape,r=s.shape,i=Array.from(r);for(let c=o.length-1;c>=0;c--)if(o[c]===r[c])i[c]=1;else if(o[c]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${r}].`);const a=[];for(let c=0;c1&&a.push(c);return{x:()=>ut(n,a,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tN={kernelName:Gr,gradFunc:n=>({x:()=>n.clone()})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eN={kernelName:Lr,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nN={kernelName:Er,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{clipValueMin:o,clipValueMax:r}=e;return{x:()=>Le(rs(oo(s,o),Qo(s,r)),n,St(n))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sN={kernelName:Ta,inputsToSave:["x"],gradFunc:jg.gradFunc};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oN={kernelName:Na,saveAllInputs:!0,gradFunc:(n,t,e)=>{const s=t.map(c=>c.shape),{axis:o}=e,r=It(o,t[0].shape)[0],i=s.map(c=>c[r]);return on(n,i,r).map(c=>()=>c)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rN={kernelName:Ra,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,{dilations:r,strides:i,pad:a,dataFormat:c}=e;return v(eo(r),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`),{x:()=>md(s.shape,n,o,i,a,c),filter:()=>Pd(s,n,o.shape,i,a,c)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iN={kernelName:$a,inputsToSave:["dy","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,{strides:r,pad:i,dataFormat:a,dimRoundingMode:c}=e;return{dy:()=>so(n,o,r,i,a,1,c),filter:()=>Pd(n,s,o.shape,r,i,a,c)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aN(n,t,e,s,o){let r=n;n.rank===4&&(r=W(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let i=t;i.rank===4&&(i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),v(r.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`),v(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),v(e.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${e}.`),v(r.shape[4]===e[3],()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${e[3]}.`),v(i.shape[4]===e[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${e[4]}).`);const a={x:r,dy:i},c={strides:s,pad:o,filterShape:e};return G.runKernel(du,a,c)}const cN=D({conv3DBackpropFilter_:aN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lN={kernelName:Ga,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:o,pad:r}=e;v(eo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[i,a]=t;return{x:()=>Dm(i.shape,n,a,o,r),filter:()=>cN(i,n,a.shape,o,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uN={kernelName:Dr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(ne(jm(st(e,"float32"))),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dN={kernelName:Wr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(qm(st(e,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hN={kernelName:La,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o,exclusive:r,reverse:i}=e;return{x:()=>{const a=Yt([o],s.rank);let c=Mm(n,o,r,!i);return a!=null&&(c=kt(c,a)),c}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pN={kernelName:Ea,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:o,pad:r,dimRoundingMode:i}=e,a=s??[1,1];v(eo(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[c,l]=t;return v(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`),v(c.shape[3]===l.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),v(Te(o,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${a}'.`),ze("depthwiseConv2d",r,i),{x:()=>Nk(c.shape,n,l,o,r,a,i),filter:()=>kk(c,n,l.shape,o,r,a,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fN={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,r={x:s,filter:o,dy:n},i={x:s,filter:o,dy:n};return{x:()=>G.runKernel(yu,r,e),filter:()=>G.runKernel(Iu,i,e)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mN={kernelName:Vr,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t,s={dy:n,y:e};return{x:()=>G.runKernel(Cu,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gN={kernelName:Fr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=E(An(ne(Bt(e))),2/Math.sqrt(Math.PI));return{x:()=>E(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bN={kernelName:zr,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,e)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xN={kernelName:Ma,inputsToSave:["input"],gradFunc:(n,t)=>{const[e]=t;return{input:()=>W(n,e.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yN={kernelName:Xr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,An(e))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const IN={kernelName:Ar,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wN={kernelName:Pr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=dt(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{let a=E(n,st(e,"float32"));const c=ce(s.shape,o);c.length>0&&(a=W(ut(a,c),s.shape));const l=Bt(s);return ne(dt(a,st(l,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CN={kernelName:Va,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,t,e)=>{const{varianceEpsilon:s}=e,[o,r,i,a]=t,c=a??Gt(1),l=ce(r.shape,o.shape),u=[];if(r.rank===1){for(let y=0;yr.rank===1?W(E(E(n,Nn(W(p,[1,1,1,r.shape[0]]),u)),c),o.shape):W(E(E(n,p),c),o.shape),mean:()=>{let y=E(E(p,Gt(-1)),h);return r.rank===1&&(y=ut(y,l)),W(y,r.shape)},variance:()=>{let y=E(E(f,d),h);return r.rank===1&&(y=ut(y,l)),W(y,r.shape)},scale:()=>{const y=E(d,p);let w=E(n,y);return r.rank===1&&(w=ut(w,l)),W(w,r.shape)},offset:()=>{let y=n;return r.rank===1&&(y=ut(y,l)),W(y,r.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vN={kernelName:Fa,inputsToSave:["x","indices"],gradFunc:(n,t,e)=>{const[s,o]=t,{axis:r,batchDims:i}=e,a=It(r,s.shape)[0],c=(l,u,d)=>()=>{const h=l.shape,p=u.size,f=h.slice(0,a),m=f.length,g=h.slice(r,h.length).slice(1),b=g.length,x=qg(0,m),I=qg(m+1,m+1+b),y=t0([f,[p],g]),w=W(d,y),C=W(u,[p]),k=t0([[m],x,I]),S=kt(w,k);let T=og(S,C,l.shape[a]);const R=Cs(k);return T=kt(T,R),T};if(i===1){const l=s.shape[0],u=s.split(l,0);return{x:()=>On(u.map((p,f)=>c(p,o.slice(f,1),n.slice(f,1))())).reshape(s.shape),indices:()=>o}}else return{x:c(s,o,n),indices:()=>o}}};function qg(n,t){const e=[];for(let s=n;s{const[e,s]=t;return{a:()=>St(e),b:()=>St(s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kN={kernelName:Kr,gradFunc:n=>({x:()=>st(n,"float32")})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TN={kernelName:Zr,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NN={kernelName:Br,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RN={kernelName:Hr,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $N={kernelName:Xa,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{alpha:o}=e,r=sn(s,0);return{x:()=>Le(r,n,E(n,o))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GN={kernelName:Ur,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Q(e,1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LN={kernelName:_r,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,st(e,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EN={kernelName:pw,inputsToSave:[],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e;return{logits:()=>{const i=An(s);return pt(n,E(ut(n,o,!0),i))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DN(n,t,e,s=5,o=1,r=1,i=.5){const a={x:n,y:t,dy:e},c={depthRadius:s,bias:o,alpha:r,beta:i};return G.runKernel(Ru,a,c)}const WN=D({localResponseNormalizationBackprop_:DN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MN={kernelName:Ba,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{depthRadius:r,bias:i,alpha:a,beta:c}=e;return{x:()=>WN(s,o,n,r,i,a,c)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e0(n,t,e,s){return t.rankE(n,st(Xn(e,t),n.dtype))}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n0={kernelName:Ha,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{reductionIndices:o}=s,r=t[0],i=t[1],a=It(o,r.shape),c=e0(n,i,r,a);return{x:()=>c.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VN={kernelName:Yr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>E(n,st(oo(e,s),"float32")),b:()=>E(n,st(Wc(e,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FN(n,t,e,s,o,r,i){const a=N(n,"dy","maxPool3dGrad"),c=N(t,"input","maxPool3dGrad"),l=N(e,"output","maxPool3dGrad");let u=a,d=c,h=l,p=!1;c.rank===4&&(p=!0,u=W(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),d=W(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),h=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),v(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),v(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),v(h.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${h.rank}.`),ze("maxPool3dGrad",r,i);const f={dy:u,input:d,output:h},m={filterSize:s,strides:o,pad:r,dimRoundingMode:i},g=G.runKernel(Gu,f,m);return p?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const zN=D({maxPool3dGrad_:FN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XN={kernelName:Ua,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=e;return{x:()=>zN(n,s,o,r,i,a,c)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AN(n,t,e,s,o,r,i){const a=N(n,"dy","maxPoolGrad"),c=N(t,"input","maxPoolGrad"),l=N(e,"output","maxPoolGrad");v(c.rank===a.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${a.rank})`),v(a.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`),v(c.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${c.rank}.`),ze("maxPoolGrad",r,i);const u={dy:a,input:c,output:l},d={filterSize:s,strides:o,pad:r,dimRoundingMode:i};return G.runKernel($u,u,d)}const PN=D({maxPoolGrad_:AN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ON={kernelName:_a,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{filterSize:r,strides:i,pad:a}=e;return{x:()=>PN(n,s,o,r,i,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KN={kernelName:Ya,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e,r=It(o,s.shape),a=me(s.shape,r)[1],c=Z(a);return{x:()=>{const u=s.shape.slice();r.forEach(p=>{u[p]=1});const d=W(n,u);return dt(E(d,Ss(s.shape,"float32")),c)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZN={kernelName:Qa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{axis:o}=s,[r,i]=t,a=It(o,r.shape),c=e0(n,i,r,a);return{x:()=>c.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BN={kernelName:Qr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>E(n,st(Qo(e,s),"float32")),b:()=>E(n,st(sn(e,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HN={kernelName:Ja,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:o}=e,r=o.map(i=>i[0]);return{x:()=>Xt(n,r,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _N={kernelName:Jr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=ce(e.shape,o);return a.length>0?W(ut(n,a),e.shape):n},b:()=>{const a=E(n,ne(Dc(dt(e,s)))),c=ce(s.shape,o);return c.length>0?W(ut(a,c),s.shape):a}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UN={kernelName:jr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=E(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{const a=E(n,st(e,"float32")),c=ce(s.shape,o);return c.length>0?W(ut(a,c),s.shape):a}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YN={kernelName:ja,gradFunc:n=>({x:()=>ne(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QN={kernelName:ec,inputsToSave:["indices"],gradFunc:(n,t)=>{const e=t[0];return{indices:()=>ge(e.shape,"float32")}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JN={kernelName:tc,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jN={kernelName:nc,saveAllInputs:!0,gradFunc:(n,t,e)=>{const{axis:s}=e;return lo(n,s).map(r=>()=>r)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const s0={kernelName:sc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:o}=e,r=o.map(i=>i[0]);return{x:()=>Xt(n,r,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qN={kernelName:qr,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,t)=>{const[e,s,o]=t,r=e,i=s,a=gt(r.shape,i.shape);return{a:()=>{const u=st(i,"float32");let d=E(n,E(u,Yo(r,pt(u,Gt(1)))));const h=ce(r.shape,a);return h.length>0&&(d=ut(d,h)),W(d,r.shape)},b:()=>{const u=sn(r,0),d=Le(u,Pn(r),St(r));let h=E(n,E(o,d));const p=ce(i.shape,a);return p.length>0&&(h=ut(h,p)),W(h,i.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tR={kernelName:oc,inputsToSave:["x","alpha"],gradFunc:(n,t)=>{const[e,s]=t,o=sn(e,0);return{x:()=>Le(o,n,E(n,s)),alpha:()=>{let r=Le(o,St(n),E(n,e));const i=ce(s.shape,n.shape);return i.length>0&&(r=ut(r,i)),W(r,s.shape)}}}};/** + * @license + * Copyright 2022 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eR(n,t,e){const s=n.shape.slice();s[e]=1;const o=W(t,s),r=bd(n,e,!0,!1),i=bd(n,e,!0,!0),a=E(r,i);return E(o,a)}function nR(n,t,e){const s=n.shape.length,o=s-e.length,r=Yt(e,s);let i=n;r!=null&&(i=kt(n,r));const a=i.shape.slice(),l=a.splice(s-e.length,e.length).reduce((h,p)=>h*p,1);a.push(l);const u=i.reshape(a);let d=eR(u,t,o);if(d=d.reshape(i.shape),r!=null){const h=Cs(r);d=kt(d,h)}return d}const sR={kernelName:rc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e;let r=[];return o==null?r=s.shape.map((i,a)=>a):typeof o=="number"?r=[o]:r=o,{x:()=>nR(s,n,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oR={kernelName:Mr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=dt(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{let a=E(n,st(e,"float32"));const c=ce(s.shape,o);c.length>0&&(a=W(ut(a,c),s.shape));const l=Bt(s);return ne(dt(a,st(l,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rR={kernelName:ti,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,ne(Bt(e)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iR={kernelName:ni,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=E(Qo(e,6),Wi(e));return{x:()=>E(n,st(s,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aR={kernelName:ei,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,st(Wi(e),"float32"))}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cR={kernelName:ic,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>W(n,e.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lR={kernelName:cc,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,o={dy:n,images:s};return{images:()=>G.runKernel(Fu,o,e)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uR={kernelName:ac,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,o={dy:n,images:s};return{images:()=>G.runKernel(Vu,o,e)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dR={kernelName:lc,gradFunc:(n,t,e)=>{const{dims:s}=e,o=It(s,n.shape);return{x:()=>ao(n,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hR={kernelName:si,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pR={kernelName:oi,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>ne(dt(n,E(Yo(e,1.5),2)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fR={kernelName:uc,inputsToSave:["condition"],gradFunc:(n,t)=>{const[e]=t;return{condition:()=>st(St(e),"float32"),t:()=>E(n,st(e,n.dtype)),e:()=>E(n,st(vd(e),n.dtype))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mR={kernelName:ri,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=sn(e,Gt(0)),o=Gt(Pc),r=Gt(Oc),i=E(n,r),a=E(E(n,o),An(st(e,"float32")));return Le(s,i,a)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gR={kernelName:li,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,E(e,pt(Gt(1),e)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bR={kernelName:ci,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xR={kernelName:ii,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(gd(st(e,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yR={kernelName:ai,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(Wm(st(e,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const IR={kernelName:dc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{begin:o,size:r}=e,i=s.shape,[a,c]=zc(s,o,r),l=[];for(let u=0;uTd(n,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wR={kernelName:mc,outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{dim:o}=e,r=!0,i=E(n,s);return{logits:()=>pt(i,E(ut(i,[o],r),s))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CR={kernelName:ui,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,_o(e))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const o0={kernelName:pc,gradFunc:(n,t,e)=>{const{blockShape:s,paddings:o}=e;return{x:()=>fd(n,s,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const r0={kernelName:fc,gradFunc:(n,t,e)=>{const{axis:s}=e;return{x:()=>Xe(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vR={kernelName:di,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,E(Ee(st(e,"float32")),2))}}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SR={kernelName:zu,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,E(st(e,"float32"),2))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kR={kernelName:hi,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=Gt(2);return{a:()=>E(n,E(o,pt(e,s))),b:()=>E(n,E(o,pt(s,e)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TR={kernelName:bi,gradFunc:n=>({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NR={kernelName:pi,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{let a=n;const c=ce(e.shape,o);return c.length>0&&(a=ut(a,c)),W(a,e.shape)},b:()=>{let a=n;const c=ce(s.shape,o);return c.length>0&&(a=ut(a,c)),W(ne(a),s.shape)}}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RR={kernelName:hc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,o=s.shape.slice(),{axis:r}=e;It(r,s.shape).forEach(l=>{o[l]=1});const a=W(n,o),c=E(a,Ss(s.shape,"float32"));return{x:()=>c}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $R={kernelName:fi,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Bt(gd(e)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GR={kernelName:mi,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(pt(Gt(1),Bt(e)),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LR={kernelName:gi,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{reps:o}=e;return{x:()=>{let i=St(s);if(s.rank===1)for(let a=0;a{const s=e,{perm:o}=s,r=Cs(o);return{x:()=>kt(n,r)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DR={kernelName:gc,gradFunc:(n,t,e)=>{const s=e,{axis:o}=s;return{value:()=>On(n,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WR={kernelName:bc,inputsToSave:["segmentIds"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>MR(n,e)}}};function MR(n,t){const e=vs(t,St(t)),s=Id(n,e);let o=oo(t,Gt(0,"int32"));const r=s.rank-o.rank;for(let a=0;a({x:()=>St(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FR=[jg,WT,MT,VT,FT,zT,XT,AT,PT,OT,KT,ZT,_T,QT,JT,jT,qT,tN,eN,nN,sN,oN,iN,rN,lN,uN,dN,hN,pN,fN,oR,mN,gN,bN,xN,yN,wN,IN,CN,vN,SN,kN,TN,NN,RN,$N,GN,LN,EN,MN,n0,n0,VN,XN,ON,KN,ZN,BN,HN,_N,UN,YN,QN,JN,jN,s0,s0,qN,tR,sR,rR,iR,aR,cR,lR,uR,dR,hR,pR,fR,mR,gR,bR,xR,yR,IR,wR,CR,o0,o0,r0,r0,vR,kR,SR,TR,NR,RR,$R,GR,LR,ER,DR,WR,VR];for(const n of FR)mw(n);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.abs=function(){return this.throwIfDisposed(),Ge(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.acos=function(){return this.throwIfDisposed(),bC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.acosh=function(){return this.throwIfDisposed(),yC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.add=function(n){return this.throwIfDisposed(),Q(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.all=function(n,t){return this.throwIfDisposed(),Gm(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.any=function(n,t){return this.throwIfDisposed(),ld(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.argMax=function(n){return this.throwIfDisposed(),vi(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.argMin=function(n){return this.throwIfDisposed(),SC(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.asScalar=function(){return this.throwIfDisposed(),v(this.size===1,()=>"The array must have only 1 element."),W(this,[])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.asType=function(n){return this.throwIfDisposed(),st(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.as2D=function(n,t){return this.throwIfDisposed(),W(this,[n,t])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.as3D=function(n,t,e){return this.throwIfDisposed(),W(this,[n,t,e])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.as4D=function(n,t,e,s){return this.throwIfDisposed(),W(this,[n,t,e,s])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.as5D=function(n,t,e,s,o){return this.throwIfDisposed(),W(this,[n,t,e,s,o])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.asin=function(){return this.throwIfDisposed(),TC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.asinh=function(){return this.throwIfDisposed(),RC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.atan=function(){return this.throwIfDisposed(),GC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.atan2=function(n){return this.throwIfDisposed(),EC(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.atanh=function(){return this.throwIfDisposed(),WC(this)},O().prototype.avgPool=function(n,t,e,s){return this.throwIfDisposed(),hd(this,n,t,e,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.batchToSpaceND=function(n,t){return this.throwIfDisposed(),fd(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.batchNorm=function(n,t,e,s,o){return this.throwIfDisposed(),Rc(this,n,t,e,s,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.broadcastTo=function(n){return this.throwIfDisposed(),Ni(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.cast=function(n){return this.throwIfDisposed(),st(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.ceil=function(){return this.throwIfDisposed(),a2(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.clipByValue=function(n,t){return this.throwIfDisposed(),nn(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.concat=function(n,t){return this.throwIfDisposed(),n instanceof ae&&(n=[n]),Xe([this,...n],t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.conv1d=function(n,t,e,s,o,r){return this.throwIfDisposed(),Lm(this,n,t,e,s,o,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.conv2dTranspose=function(n,t,e,s,o){return this.throwIfDisposed(),Em(this,n,t,e,s,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.conv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),so(this,n,t,e,s,o,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.cos=function(){return this.throwIfDisposed(),gd(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.cosh=function(){return this.throwIfDisposed(),Wm(this)};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.cumprod=function(n,t,e){return this.throwIfDisposed(),bd(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.cumsum=function(n,t,e){return this.throwIfDisposed(),Mm(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.depthToSpace=function(n,t){return this.throwIfDisposed(),E2(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.depthwiseConv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),xd(this,n,t,e,s,o,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.dilation2d=function(n,t,e,s,o){return this.throwIfDisposed(),M2(this,n,t,e,s,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.divNoNan=function(n){return this.throwIfDisposed(),A2(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.div=function(n){return this.throwIfDisposed(),dt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.dot=function(n){return this.throwIfDisposed(),O2(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.elu=function(){return this.throwIfDisposed(),Gc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.equal=function(n){return this.throwIfDisposed(),Xn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.erf=function(){return this.throwIfDisposed(),H2(this)};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.euclideanNorm=function(n,t){return this.throwIfDisposed(),ev(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.exp=function(){return this.throwIfDisposed(),An(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.expandDims=function(n){return this.throwIfDisposed(),Ae(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.expm1=function(){return this.throwIfDisposed(),rv(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.fft=function(){return this.throwIfDisposed(),eg(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.floor=function(){return this.throwIfDisposed(),Dc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.floorDiv=function(n){return this.throwIfDisposed(),$m(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.gather=function(n,t,e){return this.throwIfDisposed(),Id(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.greaterEqual=function(n){return this.throwIfDisposed(),oo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.greater=function(n){return this.throwIfDisposed(),sn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.ifft=function(){return this.throwIfDisposed(),Xd(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.irfft=function(){return this.throwIfDisposed(),US(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.isFinite=function(){return this.throwIfDisposed(),fv(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.isInf=function(){return this.throwIfDisposed(),gv(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.isNaN=function(){return this.throwIfDisposed(),xv(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.leakyRelu=function(n){return this.throwIfDisposed(),Cd(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.lessEqual=function(n){return this.throwIfDisposed(),Qo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.less=function(n){return this.throwIfDisposed(),Wc(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.localResponseNormalization=function(n,t,e,s){return this.throwIfDisposed(),vv(this,n,t,e,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logSigmoid=function(){return this.throwIfDisposed(),Gv(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logSoftmax=function(n){return this.throwIfDisposed(),Pm(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logSumExp=function(n,t){return this.throwIfDisposed(),Om(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.log=function(){return this.throwIfDisposed(),Pn(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.log1p=function(){return this.throwIfDisposed(),Am(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logicalAnd=function(n){return this.throwIfDisposed(),rs(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logicalNot=function(){return this.throwIfDisposed(),vd(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logicalOr=function(n){return this.throwIfDisposed(),Km(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.logicalXor=function(n){return this.throwIfDisposed(),zv(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.matMul=function(n,t,e){return this.throwIfDisposed(),$t(this,n,t,e)},O().prototype.maxPool=function(n,t,e,s){return this.throwIfDisposed(),Sd(this,n,t,e,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.max=function(n,t){return this.throwIfDisposed(),Tn(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.maximum=function(n){return this.throwIfDisposed(),vs(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.mean=function(n,t){return this.throwIfDisposed(),ie(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.min=function(n,t){return this.throwIfDisposed(),Lc(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.minimum=function(n){return this.throwIfDisposed(),Gi(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.mirrorPad=function(n,t){return this.throwIfDisposed(),Hv(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.mod=function(n){return this.throwIfDisposed(),Uv(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.mul=function(n){return this.throwIfDisposed(),E(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.neg=function(){return this.throwIfDisposed(),ne(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.norm=function(n,t,e){return this.throwIfDisposed(),Ec(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.notEqual=function(n){return this.throwIfDisposed(),Mc(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.oneHot=function(n,t=1,e=0){return this.throwIfDisposed(),Zm(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.onesLike=function(){return this.throwIfDisposed(),fn(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.pad=function(n,t){return this.throwIfDisposed(),Td(this,n,t)},O().prototype.pool=function(n,t,e,s,o,r){return this.throwIfDisposed(),oS(this,n,t,e,s,o,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.pow=function(n){return this.throwIfDisposed(),Yo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.prelu=function(n){return this.throwIfDisposed(),Rd(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.prod=function(n,t){return this.throwIfDisposed(),aS(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.reciprocal=function(){return this.throwIfDisposed(),RS(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.relu=function(){return this.throwIfDisposed(),io(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.relu6=function(){return this.throwIfDisposed(),_m(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.reshapeAs=function(n){return this.throwIfDisposed(),W(this,n.shape)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.reshape=function(n){return this.throwIfDisposed(),W(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.resizeBilinear=function(n,t,e){return this.throwIfDisposed(),cg(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.resizeNearestNeighbor=function(n,t,e){return this.throwIfDisposed(),lg(this,n,t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.reverse=function(n){return this.throwIfDisposed(),ao(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.rfft=function(){return this.throwIfDisposed(),JS(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.round=function(){return this.throwIfDisposed(),Um(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.rsqrt=function(){return this.throwIfDisposed(),Ym(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.selu=function(){return this.throwIfDisposed(),Qm(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.separableConv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),Jm(this,n,t,e,s,o,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sigmoid=function(){return this.throwIfDisposed(),_o(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sign=function(){return this.throwIfDisposed(),FS(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sin=function(){return this.throwIfDisposed(),jm(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sinh=function(){return this.throwIfDisposed(),qm(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.slice=function(n,t){return this.throwIfDisposed(),Xt(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.softmax=function(n){return this.throwIfDisposed(),zd(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.softplus=function(){return this.throwIfDisposed(),$i(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.spaceToBatchND=function(n,t){return this.throwIfDisposed(),Nd(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.split=function(n,t){return this.throwIfDisposed(),on(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sqrt=function(){return this.throwIfDisposed(),Ee(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.square=function(){return this.throwIfDisposed(),Bt(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.squaredDifference=function(n){return this.throwIfDisposed(),qS(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.squeeze=function(n){return this.throwIfDisposed(),Di(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.stack=function(n,t){this.throwIfDisposed();const e=n instanceof ae?[this,n]:[this,...n];return On(e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.step=function(n){return this.throwIfDisposed(),Wi(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.stridedSlice=function(n,t,e,s,o,r,i,a){return this.throwIfDisposed(),ok(this,n,t,e,s,o,r,i,a)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sub=function(n){return this.throwIfDisposed(),pt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.sum=function(n,t){return this.throwIfDisposed(),ut(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.tan=function(){return this.throwIfDisposed(),ik(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.tanh=function(){return this.throwIfDisposed(),pd(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.tile=function(n){return this.throwIfDisposed(),Nn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.toBool=function(){return this.throwIfDisposed(),st(this,"bool")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.toFloat=function(){return this.throwIfDisposed(),st(this,"float32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.toInt=function(){return this.throwIfDisposed(),st(this,"int32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.topk=function(n,t){return this.throwIfDisposed(),uk(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.transpose=function(n){return this.throwIfDisposed(),kt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.unique=function(n){return this.throwIfDisposed(),pk(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.unsortedSegmentSum=function(n,t){return this.throwIfDisposed(),og(this,n,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.unstack=function(n){return this.throwIfDisposed(),lo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.where=function(n,t){return this.throwIfDisposed(),Le(n,this,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */O().prototype.zerosLike=function(){return this.throwIfDisposed(),St(this)};/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Zn extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Zn.prototype)}}class gn extends Error{constructor(t){super(t),Object.setPrototypeOf(this,gn.prototype)}}class $ extends Error{constructor(t){super(t),Object.setPrototypeOf(this,$.prototype)}}class bt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,bt.prototype)}}class kh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,kh.prototype)}}/** + * @license + * Copyright 2022 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class i0{constructor(t){this.maxEntries=t||100,this.cache=new Map}get(t){let e;return this.cache.has(t)&&(e=this.cache.get(t),this.cache.delete(t),this.cache.set(t,e)),e}put(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxEntries){const s=this.cache.keys().next().value;this.cache.delete(s)}this.cache.set(t,e)}getMaxEntries(){return this.maxEntries}setMaxEntries(t){if(t<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${t}.`);if(this.maxEntries>t)for(let e=0;ee.toUpperCase())}let bn={};function Th(n){if(n==null)return null;const t={};return t.className=n.getClassName(),t.config=n.getConfig(),t}function Nh(n){if(!(n==null||typeof n!="object"))if(Array.isArray(n))n.forEach(t=>Nh(t));else{const t=Object.keys(n);for(const e of t){const s=n[e];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?n[e]=s.value:Nh(s))}}}function zi(n,t={},e={},s="object",o=!1){if(typeof n=="string"){const r=n;let i;if(r in e)i=e[r];else if(r in bn)i=bn[r];else if(i=t[r],i==null)throw new $(`Unknown ${s}: ${n}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{const r=n;if(r.className==null||r.config==null)throw new $(`${s}: Improper config format: ${JSON.stringify(r)}. +'className' and 'config' must set.`);const i=r.className;let a,c;if(i in e?[a,c]=e[i]:i in bn?[a,c]=bn.className:i in t&&([a,c]=t[i]),a==null)throw new $(`Unknown ${s}: ${i}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){const l={};for(const p of Object.keys(bn))l[p]=bn[p];for(const p of Object.keys(e))l[p]=e[p];const u=r.config;u.customObjects=l;const d=Object.assign({},bn);for(const p of Object.keys(e))bn[p]=e[p];Nh(r.config);const h=c(a,r.config,e,o);return bn=Object.assign({},d),h}else{const l=Object.assign({},bn);for(const d of Object.keys(e))bn[d]=e[d];const u=new a(r.config);return bn=Object.assign({},l),u}}}function zR(n,t){return nt?1:0}function Kc(n,t){return-1*zR(n,t)}function Ts(n){if(n==null)return n;const t=[];for(const e of n)t.indexOf(e)===-1&&t.push(e);return t}function XR(n){if(n==null)throw new $(`Invalid value in obj: ${JSON.stringify(n)}`);for(const t in n)if(n.hasOwnProperty(t))return!1;return!0}function fo(n,t,e){if(e!=null&&n.indexOf(e)<0)throw new $(`${e} is not a valid ${t}. Valid values are ${n} or null/undefined.`)}function Rh(n,t,e=0,s=1/0){return Bn(e>=0),Bn(s>=e),Array.isArray(n)&&n.length>=e&&n.length<=s&&n.every(o=>typeof o===t)}function be(n,t){Array.isArray(n)?(v(n.length>0,()=>`${t} is unexpectedly an empty array.`),n.forEach((e,s)=>be(e,`element ${s+1} of ${t}`))):v(Number.isInteger(n)&&n>0,()=>`Expected ${t} to be a positive integer, but got ${c0(n)}.`)}function c0(n){return n===null?"null":Array.isArray(n)?"["+n.map(t=>c0(t)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function AR(n,t,e){let s=e!=null?e():Ve(),o;return(...i)=>{const a=e!=null?e():Ve();return a-s0){const e=`${n}_${t}`;return er.set(e,1),e}else return n}const YR=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function m0(n){return!!n.match(YR)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function QR(n){return n===parseInt(n.toString(),10)}function Ns(n,t,e){t==null&&(t=0),e==null&&(e=n.length);let s=1;for(let o=t;ot&&(t=s)}return t}function $n(n,t){if(t{if(n.shape.length!==2)throw new $(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);const e=Ai(n,1);return Eh(e,[1,t,1])})}function jR(n){const t=[Ns(n.shape)];return W(n,t)}function qR(n){if(n.rank<=1)throw new $(`batchFlatten requires a minimum rank of 2. Got rank: ${n.rank}.`);const t=[n.shape[0],Ns(n.shape,1)];return W(n,t)}function go(n,t,e){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:return tg(n,[t,0],[e,n.shape[1]]);case 3:return Fd(n,[t,0,0],[e,n.shape[1],n.shape[2]]);case 4:return Fc(n,[t,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3]]);case 5:return Xt(n,[t,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return Xt(n,[t,0,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new $(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Gh(n,t,e){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:return tg(n,[0,t],[n.shape[0],e]);case 3:return Fd(n,[0,0,t],[n.shape[0],n.shape[1],e]);case 4:return Fc(n,[0,0,0,t],[n.shape[0],n.shape[1],n.shape[2],e]);default:throw new $(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Hc(n,t,e,s){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:switch(s){case 1:return go(n,t,e);case 2:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return go(n,t,e);case 2:return Fd(n,[0,t,0],[n.shape[0],e,n.shape[2]]);case 3:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return go(n,t,e);case 2:return Fc(n,[0,t,0,0],[n.shape[0],e,n.shape[2],n.shape[3]]);case 3:return Fc(n,[0,0,t,0],[n.shape[0],n.shape[1],e,n.shape[3]]);case 4:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}default:throw new $(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Lh(n,t=-1){let e;return t<0&&(e=n[0].rank,e!==0?t=e:t=0),t===n[0].rank&&(t=-1),Xe(n,t)}function g0(n,t){switch(n.rank){case 1:return u2([n,t]);case 2:return h2([n,t],0);case 3:return f2([n,t],0);case 4:return g2([n,t],0);default:throw new $(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function Eh(n,t){if(Array.isArray(t)||(t=[t]),n.rank!==t.length)throw new $(`The length of input n (${t.length}) does not match the number of dimensions in input x (${n.rank})`);return Nn(n,t)}function _c(n,t=0,e=1,s,o){return SS(n,t,e,s,o)}function _n(n,t,e,s){if(n.rank<2||t.rank<2)throw new bt(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${t.shape}`);if(t.rank>=3){const o=n.shape.slice(-1)[0],r=t.shape.slice(-2)[0];if(o!==r)throw new bt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and y shape = ${t.shape}`)}if(n.rank===2&&t.rank===2)return ig({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Dh(n.rank,s,Gn()):null,activation:e});{const o=n.shape.slice(),r=o.pop();n=W(n,[-1,r]);const i=t.shape.slice(),a=i.pop(),c=i.pop(),l=[...i,a],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=W(kt(t,u),[c,-1]);const d=[...o,...l];return W(ig({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Dh(n.rank,s,Gn()):null,activation:e}),d)}}function b0(n,t,e){return M(()=>(Array.isArray(t)?t=Ue(t,"int32"):t=st(t,"int32"),Id(n,t,e)))}function Pi(n){return E(n,n)}function Dh(n,t,e){const s=t.shape;if(t.rank!==1&&t.rank!==n)throw new $(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${n}`);if(n===5){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1,1]):W(t,[1,s[3],s[0],s[1],s[2]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,1,1,s[0]]):W(t,[1].concat(s))}else if(n===4){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1]):W(t,[1,s[2],s[0],s[1]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,1,s[0]]):W(t,[1].concat(s))}else if(n===3){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1]):W(t,[1,s[1],s[0]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,s[0]]):W(t,[1].concat(s))}else if(n<3)return t;throw new $(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ln(n,t,e){return M(()=>(e==null&&(e=Gn()),se(e),Q(n,Dh(n.rank,t,e))))}function t$(n,t=1){if(t!==1)throw new bt(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Gc(n)}function e$(n){return M(()=>dt(n,Q(Ge(n),1)))}function x0(n,t,e,s){return M(()=>Ik(n,t,e,s))}function n$(n){return M(()=>{const t=Q(.5,E(.2,n));return nn(t,0,1)})}function Oi(n,t,e=!1){return e?n():t()}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const s$=["fanIn","fanOut","fanAvg"],o$=["normal","uniform","truncatedNormal"];/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function r$(n){fo(s$,"FanMode",n)}function i$(n){fo(o$,"Distribution",n)}class xn extends qo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class y0 extends xn{apply(t,e){return ge(t,e)}}y0.className="Zeros",_(y0);class Wh extends xn{apply(t,e){return Ss(t,e)}}Wh.className="Ones",_(Wh);class I0 extends xn{constructor(t){if(super(),typeof t!="object")throw new $(`Expected argument of type ConstantConfig but got ${t}`);if(t.value===void 0)throw new $(`config must have value set but got ${t}`);this.value=t.value}apply(t,e){return M(()=>E(Gt(this.value),Ss(t,e)))}getConfig(){return{value:this.value}}}I0.className="Constant",_(I0);class w0 extends xn{constructor(t){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=t.minval||this.DEFAULT_MINVAL,this.maxval=t.maxval||this.DEFAULT_MAXVAL,this.seed=t.seed}apply(t,e){return Li(t,this.minval,this.maxval,e,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}w0.className="RandomUniform",_(w0);class C0 extends xn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`randomNormal does not support dType ${e}.`);return _c(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}C0.className="RandomNormal",_(C0);class v0 extends xn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`truncatedNormal does not support dType ${e}.`);return sg(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}v0.className="TruncatedNormal",_(v0);class S0 extends xn{constructor(t){super(),this.gain=t.gain!=null?t.gain:1}apply(t,e){return M(()=>{if(t.length!==2||t[0]!==t[1])throw new $("Identity matrix initializer can only be used for 2D square matrices.");return E(this.gain,Xm(t[0]))})}getConfig(){return{gain:this.gain}}}S0.className="Identity",_(S0);function a$(n,t="channelsLast"){let e,s;if(se(t),n.length===2)e=n[0],s=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(t==="channelsFirst"){const o=Ns(n,2);e=n[1]*o,s=n[0]*o}else if(t==="channelsLast"){const o=Ns(n,0,n.length-2);e=n[n.length-2]*o,s=n[n.length-1]*o}}else{const o=Ns(n);e=Math.sqrt(o),s=Math.sqrt(o)}return[e,s]}class Ye extends xn{constructor(t){if(super(),t.scale<0)throw new $(`scale must be a positive float. Got: ${t.scale}`);this.scale=t.scale==null?1:t.scale,this.mode=t.mode==null?"fanIn":t.mode,r$(this.mode),this.distribution=t.distribution==null?"normal":t.distribution,i$(this.distribution),this.seed=t.seed}apply(t,e){const s=a$(t),o=s[0],r=s[1];let i=this.scale;if(this.mode==="fanIn"?i/=Math.max(1,o):this.mode==="fanOut"?i/=Math.max(1,r):i/=Math.max(1,(o+r)/2),this.distribution==="normal"){const a=Math.sqrt(i);if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`${this.getClassName()} does not support dType ${e}.`);return sg(t,0,a,e,this.seed)}else{const a=Math.sqrt(3*i);return Li(t,-a,a,e,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Ye.className="VarianceScaling",_(Ye);class Mh extends Ye{constructor(t){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Mh.className="GlorotUniform",_(Mh);class Vh extends Ye{constructor(t){super({scale:1,mode:"fanAvg",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Vh.className="GlorotNormal",_(Vh);class Fh extends Ye{constructor(t){super({scale:2,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Fh.className="HeNormal",_(Fh);class zh extends Ye{constructor(t){super({scale:2,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}zh.className="HeUniform",_(zh);class Xh extends Ye{constructor(t){super({scale:1,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Xh.className="LeCunNormal",_(Xh);class Ah extends Ye{constructor(t){super({scale:1,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Ah.className="LeCunUniform",_(Ah);class k0 extends xn{constructor(t){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=t.gain==null?this.DEFAULT_GAIN:t.gain,this.seed=t.seed}apply(t,e){return M(()=>{if(t.length<2)throw new bt("Shape must be at least 2D.");if(e!=="int32"&&e!=="float32"&&e!==void 0)throw new TypeError(`Unsupported data type ${e}.`);e=e;const s=Z(t.slice(0,-1)),o=t[t.length-1],r=s*o;r>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);const i=[Math.max(o,s),Math.min(o,s)],a=_c(i,0,1,e,this.seed),c=gT.qr(a,!1);let l=c[0];const d=c[1].flatten().stridedSlice([0],[Math.min(o,s)*Math.min(o,s)],[Math.min(o,s)+1]);return l=E(l,d.sign()),ss*o);return t}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const R0="Variable";class c${constructor(t,e="float32",s=R0,o=!0,r=null){this.dtype=e??"float32",this.shape=t.shape,this.id=u0(),s=s??R0,this.originalName=p0(s),this.name=f0(this.originalName),this.trainable_=o,this.constraint=r,this.val=gk(t,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(t){return this.assertNotDisposed(),l$(this.val,t),this.val.id!==t.id&&(this.val.assign(t),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(t){this.trainable_=t,this.val.trainable=t}}function l$(n,t){if(n.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(n.shape)+" vs. "+JSON.stringify(t.shape))}function Oh(n){return n.map(t=>t.read())}function Kh(n){n.forEach(t=>{t[0].write(t[1])})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ue{constructor(t){this.dtype=t.dtype,this.shape=t.shape,t.shape!=null?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}class Un{constructor(t,e,s,o,r,i,a){this.dtype=t,this.shape=e,this.sourceLayer=s,this.inputs=o,this.callArgs=r,this.outputTensorIndex=a,this.id=u0(),i!=null&&(this.originalName=p0(i),this.name=f0(this.originalName)),this.rank=e.length}}let u$=0;class Qc{constructor(t,e){this.callArgs=e,this.id=u$++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(const s of t.inboundLayers)s!=null&&s.outboundNodes.push(this);t.outboundLayer.inboundNodes.push(this)}getConfig(){const t=[];for(const e of this.inboundLayers)e!=null?t.push(e.name):t.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let d$=0;class Ct extends qo{constructor(t={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=d$++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let e=t.name;if(!e){const s=this.getClassName();e=ls(s)+"_"+Bc(s)}if(this.name=e,this.trainable_=t.trainable==null?!0:t.trainable,t.inputShape!=null||t.batchInputShape!=null){let s;if(t.batchInputShape!=null)s=t.batchInputShape;else if(t.inputShape!=null){let r=null;t.batchSize!=null&&(r=t.batchSize),s=[r].concat(t.inputShape)}this.batchInputShape=s;let o=t.dtype;o==null&&(o=t.inputDType),o==null&&(o="float32"),this.dtype=o}t.weights!=null?this.initialWeights=t.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(t,e){return t.name+"_ib-"+e.toString()}getNodeAtIndex(t,e){if(this.inboundNodes.length===0)throw new gn(`The layer has never been called and thus has no defined ${e}.`);if(this.inboundNodes.length<=t)throw new $(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[t]}getInputAt(t){return Pe(this.getNodeAtIndex(t,"input").inputTensors)}getOutputAt(t){return Pe(this.getNodeAtIndex(t,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} is not connected, no input to return.`);return Pe(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Pe(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(t=>t())}get updates(){return this._updates}get built(){return this._built}set built(t){this._built=t}get trainable(){return this.trainable_}set trainable(t){this._trainableWeights.forEach(e=>e.trainable=t),this.trainable_=t}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(t=>t.trainable):[]}set trainableWeights(t){this._trainableWeights=t}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(t=>!t.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(t){this._nonTrainableWeights=t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(t){const e=Lt(t);if(this.inputSpec==null||this.inputSpec.length===0)return;const s=Lt(this.inputSpec);if(e.length!==s.length)throw new $(`Layer ${this.name} expects ${s.length} inputs, but it received ${e.length} input tensors. Input received: ${t}`);for(let o=0;oi.maxNDim)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${a}`);if(i.minNDim!=null&&a=0?c[u]:c[c.length+u];if(d!=null&&[d,null].indexOf(h)===-1)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${d} but got shape ${c}.`)}}if(i.shape!=null)for(let c=0;c{if(!this.built){this.assertInputCompatibility(t);const i=[];for(const a of Lt(t))i.push(a.shape);this.build(Pe(i)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(t),r){let i=this.call(t,e);this.supportsMasking&&this.setMaskMetadata(t,i);const a=Lt(i),c=[];for(let l of a)s.indexOf(l)!==-1&&(l=l.clone()),c.push(l);if(i=Pe(c),this.activityRegularizer!=null)throw new bt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}else{const i=h$(t),a=this.computeOutputShape(i);let c;const l=p$(t);if(this.warnOnIncompatibleInputShape(Array.isArray(t)?i[0]:i),a!=null&&a.length>0&&Array.isArray(a[0])?c=a.map((u,d)=>new Un(l,u,this,Lt(t),e,this.name,d)):c=new Un(l,a,this,Lt(t),e,this.name),this.addInboundNode(t,c,null,null,i,a,e),this._refCount++,this.activityRegularizer!=null)throw new bt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return c}})}warnOnIncompatibleInputShape(t){if(this.batchInputShape!=null)if(t.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let e=!1;this.batchInputShape.forEach((s,o)=>{s!=null&&t[o]!=null&&t[o]!==s&&(e=!0)}),e&&console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Zn(`The layer ${this.name} has never been called and thus has no defined output shape.`);const t=[];for(const e of this.inboundNodes){const s=JSON.stringify(e.outputShapes);t.indexOf(s)===-1&&t.push(s)}if(t.length===1){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&e.length===1?e[0]:e}else throw new Zn(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new gn(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Yc(this.weights)}build(t){this.built=!0}getWeights(t=!1){return Oh(t?this.trainableWeights:this.weights)}setWeights(t){M(()=>{const e=this.weights;if(e.length!==t.length)throw new $(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);if(e.length===0)return;const s=[],o=Oh(e);for(let r=0;rr.apply(u.read())),i==null&&(i=!0),i?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(t){this.fastWeightInitDuringBuild=t}addLoss(t){t==null||Array.isArray(t)&&t.length===0||(t=Lt(t),this._losses!==void 0&&this._losses!==null&&this.losses.push(...t))}computeOutputShape(t){return t}computeMask(t,e){if(!this.supportsMasking){if(e!=null)if(Array.isArray(e))e.forEach(s=>{if(s!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return e}setMaskMetadata(t,e,s){if(!this.supportsMasking)return;const o=this.computeMask(t,s),r=Lt(e),i=Lt(o);if(r.length!==i.length)throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);for(let a=0;at.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let t=0;return--this._refCount===0&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}}}function h$(n){n=Lt(n);const t=[];for(const e of n)t.push(e.shape);return Pe(t)}function p$(n){return"float32"}function $0(n,t,e){if((t==null||e!=null&&e>0)&&(t=n.sourceLayer,e=n.nodeIndex),t.inboundNodes.length===0)return[n];{const s=t.inboundNodes[e];if(s.inboundLayers.length===0)return s.inputTensors;{const o=[];for(let r=0;rf.name),c=[],l=t.names();for(const f of a)l.indexOf(f)!==-1?c.push(t.getValue(f)):c.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const u=a.join(",")+"|"+t.names().sort().join(",");let d=Jc.get(u),h;if(d==null){const f=y$(i,t);d=f.sorted,h=f.recipientCounts,Jc.put(u,d),jc.put(u,h)}h={},o||Object.assign(h,jc.get(u));const p=new $s(t);for(let f=0;fs.maxNumTensors&&(s.maxNumTensors=T),T0,()=>"Expected at least one fetch, got none");let e=[],s={};if(n.length===1){const o=G0(n[0],t);e=o.sorted,s=o.recipientMap}else{const o=new Set;for(const r of n){const{sorted:i,recipientMap:a}=G0(r,t);for(const c of i)o.has(c.name)||(e.push(c),o.add(c.name));for(const c in a)s[c]==null&&(s[c]=new Set),a[c].forEach(l=>s[c].add(l))}}return{sorted:e,recipientCounts:I$(s)}}function I$(n){const t={};for(const e in n)t[e]=n[e].size;return t}function G0(n,t){const e=new Set,s=[],o={};for(const a of t.names())e.add(a);const r=[],i=[];for(r.push(n);r.length>0;){const a=r[r.length-1];if(e.has(a.name)){r.pop();continue}const c=i[i.length-1]===r.length-1;if(a.inputs.length===0||c)r.pop(),s.push(a),e.add(a.name),c&&i.pop();else{i.push(r.length-1);for(const l of a.inputs)o[l.name]==null&&(o[l.name]=new Set),o[l.name].add(a.name),!e.has(l.name)&&r.push(l)}}return{sorted:s,recipientMap:o}}function w$(n){let t;if(n.sourceLayer.inboundNodes.length===1)t=n.sourceLayer.output;else{let e=null;for(let s=0;s100,x$);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Zh(n,t){return M(()=>Ee(ut(E(n,n),t,!0)))}class Bi extends qo{getConfig(){return{}}}class L0 extends Bi{constructor(t){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>{const e=Zh(t,this.axis),s=nn(e,0,this.maxValue);return E(t,dt(s,Q(le(),e)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}L0.className="MaxNorm",_(L0);class E0 extends Bi{constructor(t){super(),this.defaultAxis=0,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>dt(t,Q(le(),Zh(t,this.axis))))}getConfig(){return{axis:this.axis}}}E0.className="UnitNorm",_(E0);class D0 extends Bi{apply(t){return io(t)}}D0.className="NonNeg",_(D0);class W0 extends Bi{constructor(t){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=t.minValue!=null?t.minValue:this.defaultMinValue,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.rate=t.rate!=null?t.rate:this.defaultRate,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>{const e=Zh(t,this.axis),s=Q(E(this.rate,nn(e,this.minValue,this.maxValue)),E(1-this.rate,e));return E(t,dt(s,Q(le(),e)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}W0.className="MinMaxNorm",_(W0);const M0={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function de(n){return Th(n)}function V0(n,t={}){return zi(n,mn.getMap().classNameMap,t,"constraint")}function he(n){if(n==null)return null;if(typeof n=="string"){const e={className:n in M0?M0[n]:n,config:{}};return V0(e)}else return n instanceof Bi?n:V0(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */async function bo(n){if(n==null)return;const t=[],e=[],s=[];for(const o in n){const r=n[o];if(typeof r!="number"){const i=r;t.push(i.data()),e.push(o),s.push(i)}}if(t.length>0){const o=await Promise.all(t);for(let r=0;rQ(this.totals[o],E(r,s)));this.totals[o]=a,i!=null&&i.dispose()}}}async onEpochEnd(t,e){if(e!=null)for(const s of this.params.metrics)this.totals[s]!=null&&(typeof this.totals[s]=="number"?e[s]=this.totals[s]/this.seen:M(()=>{const o=E(dt(1,this.seen),this.totals[s]);e[s]=o,this.totals[s].dispose(),en(e[s])}))}}class k$ extends Hi{async onTrainBegin(t){this.epoch=[],this.history={}}async onEpochEnd(t,e){e==null&&(e={}),this.epoch.push(t);for(const s in e)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(e[s])}async syncData(){const t=[],e=[],s=[];for(const r in this.history){const i=this.history[r];for(let a=0;anew T$(s,t))}class yn{constructor(){}static registerCallbackConstructor(t,e){v(t>=0&&Number.isInteger(t),()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`),yn.checkForDuplicate(e),yn.constructors[t]==null&&(yn.constructors[t]=[]),yn.constructors[t].push(e)}static checkForDuplicate(t){for(const e in yn.constructors)yn.constructors[+e].forEach(o=>{if(o===t)throw new $("Duplicate callback constructor.")})}static clear(){yn.constructors={}}static createCallbacks(t){const e=[];for(const s in yn.constructors){const o=+s;t>=o&&e.push(...yn.constructors[o])}return e.map(s=>new s)}}yn.constructors={};function A0(n,t,e,s,o,r,i,a,c){const l=new k$,u=[new S$,...yn.createCallbacks(t)];n!=null&&u.push(...n),u.push(l);const d=new v$(u);return d.setParams({epochs:e,initialEpoch:s,samples:o,steps:r,batchSize:i,verbose:t,doValidation:a,metrics:c}),{callbackList:d,history:l}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function us(n,t={},e=!1){return zi(n,mn.getMap().classNameMap,t,"layer",e)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function qc(n,t){return M(()=>{n.dtype!=="float32"&&(n=st(n,"float32"));const e=ut(Pi(n),t,!0),s=$c(e.shape,le()),o=Ee(vs(e,s));return dt(n,o)})}function tl(n,t){return M(()=>ie(Pi(pt(t,n)),-1))}function Bh(n,t){return M(()=>ie(Ge(pt(t,n)),-1))}function Hh(n,t){return M(()=>{const e=pt(n,t),s=nn(Ge(n),le(),Number.MAX_VALUE),o=Ge(dt(e,s));return E(100,ie(o,-1))})}function N$(n,t){return M(()=>{const e=nn(t,le(),Number.MAX_VALUE),s=Pn(Q(1,e)),o=nn(n,le(),Number.MAX_VALUE),r=Pn(Q(1,o));return ie(Pi(pt(s,r)),-1)})}function R$(n,t){return M(()=>{const e=vs(0,pt(1,E(n,t)));return ie(Pi(e),-1)})}function $$(n,t){return M(()=>{const e=vs(0,pt(1,E(n,t)));return ie(e,-1)})}function G$(n,t){return M(()=>{const e=ut(E(n,t),-1),s=Tn(E(pt(1,n),t),-1);return vs(0,Q(1,pt(s,e)))})}function L$(n,t){return M(()=>{const e=Math.log(2),s=pt(t,n),o=pt(Q(s,$i(E(-2,s))),e);return ie(o,-1)})}function _i(n,t,e=!1){return M(()=>{if(e)t=zd(t);else{const s=ut(t,t.shape.length-1,!0);t=dt(t,s)}return t=nn(t,le(),1-le()),ne(ut(E(st(n,"float32"),Pn(t)),t.shape.length-1))})}function el(n,t,e=!1){return M(()=>{const s=st(Dc(jR(n)),"int32");t=nn(t,le(),1-le());const o=t.shape,r=W(Zm(s,o[o.length-1]),o);return _i(r,t,e)})}function E$(n,t){if(!Rt(n.shape,t.shape))throw new $(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(t.shape)}`);return M(()=>{const e=io(t),s=ne(Ge(t));return Q(pt(e,E(t,n)),Am(An(s)))})}function nl(n,t){return M(()=>{let e;return e=nn(t,le(),1-le()),e=Pn(dt(e,pt(1,e))),ie(E$(n,e),-1)})}function D$(n,t){return M(()=>{const e=nn(n,le(),1),s=nn(t,le(),1);return ut(E(n,Pn(dt(e,s))),-1)})}function W$(n,t){return M(()=>{const e=Pn(Q(le(),t));return ie(pt(t,E(n,e)),-1)})}function P0(n,t){return M(()=>{const e=qc(n,-1),s=qc(t,-1),o=E(e,s);return ne(ut(o,-1))})}const sl={meanSquaredError:tl,meanAbsoluteError:Bh,meanAbsolutePercentageError:Hh,meanSquaredLogarithmicError:N$,squaredHinge:R$,hinge:$$,categoricalHinge:G$,logcosh:L$,categoricalCrossentropy:_i,sparseCategoricalCrossentropy:el,binaryCrossentropy:nl,kullbackLeiblerDivergence:D$,poisson:W$,cosineProximity:P0};function _h(n){if(typeof n=="string"){if(n in sl)return sl[n];let t=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new $(t)}else return n}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function O0(n,t){return M(()=>{const e=E(.5,fn(t)),s=Hn(sn(t,e),n.dtype);return ie(Xn(n,s),-1)})}function K0(n,t){return M(()=>Hn(Xn(vi(n,-1),vi(t,-1)),"float32"))}function M$(n,t){return M(()=>st(ut(rs(Xn(n,1),Xn(t,1))),"float32"))}function V$(n,t){return M(()=>st(ut(rs(Xn(n,0),Xn(t,1))),"float32"))}function F$(n,t){return M(()=>{const e=M$(n,t),s=V$(n,t),o=Q(e,s);return st(Le(sn(o,0),dt(e,o),0),"float32")})}function z$(n,t){return nl(n,t)}function X$(n,t){return n.rank===t.rank&&(n=Di(n,[n.rank-1])),t=vi(t,-1),t.dtype!==n.dtype&&(t=st(t,n.dtype)),st(Xn(n,t),"float32")}const A$=tl,P$=tl,O$=Bh,K$=Bh,Z$=Hh,B$=Hh,Z0=_i,H$=P0,B0=el,ol={binaryAccuracy:O0,categoricalAccuracy:K0,precision:F$,categoricalCrossentropy:Z0,sparseCategoricalCrossentropy:B0,mse:A$,MSE:P$,mae:O$,MAE:K$,mape:Z$,MAPE:B$,cosine:H$};function _$(n){if(typeof n=="string"&&n in ol)return ol[n];if(typeof n!="string"&&n!=null)return n;throw new $(`Unknown metric ${n}`)}function rl(n){if(Bn(n!==null,`Unknown LossOrMetricFn ${n}`),typeof n=="string")return n;{let t;for(const e of Object.keys(sl))if(sl[e]===n){t=e;break}if(t!==void 0)return t;for(const e of Object.keys(ol))if(ol[e]===n){t=e;break}return t!==void 0?t:n.name}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function U$(n){const t={Adagrad:()=>tr.adagrad(.01),Adadelta:()=>tr.adadelta(1,.95,le()),Adam:()=>tr.adam(.001,.9,.999,le()),Adamax:()=>tr.adamax(.002,.9,.999,le(),0),RMSProp:()=>tr.rmsprop(.001,.9,0,le()),SGD:()=>tr.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,n in t)return t[n]();throw new $(`Unknown Optimizer ${n}`)}/** + * @license + * Copyright 2019 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const H0=1*1024*1024;function _0(n,t,e=!1){if(n==null||typeof n!="object"||Object.getPrototypeOf(n)!==Object.prototype||!Uh(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(e){const s=JSON.stringify(n);s.length>H0&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${H0}.`)}}function Uh(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){const t=Object.keys(n);for(const e of t)if(typeof e!="string"||!Uh(n[e]))return!1;return!0}else if(Array.isArray(n)){for(const t of n)if(!Uh(t))return!1;return!0}else return!1;else{const t=typeof n;return t==="string"||t==="number"||t==="boolean"}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Y$(n,t,e,s=console.log){const o=J$(n),r=["Layer (type)","Input Shape","Output shape","Param #"];o?(t=t||90,e=e||[.32,.61,.89,1]):(t=t||115,e=e||[.24,.48,.7,.8,1]),e[e.length-1]<=1&&(e=e.map(u=>Math.floor(t*u)));let i;if(!o){r.push("Receives inputs"),i=[];for(const u in n.nodesByDepth)i.push(...n.nodesByDepth[u])}s("_".repeat(t)),il(r,e,s),s("=".repeat(t));const a=n.layers;for(let u=0;u1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}s.push(...o)}if(t)for(const o of n.layers){let r=!1;for(const i of o.inboundNodes)if(s.indexOf(i)!==-1)if(r){t=!1;break}else r=!0;if(!t)break}return t}function il(n,t,e=console.log){let s="";for(let o=0;o0&&(s=s.slice(0,s.length-1)+" "),s+=n[o],s=s.slice(0,t[o]),s+=" ".repeat(t[o]-s.length);e(s)}function j$(n,t,e){let s,o;try{o=n.inboundNodes.map(c=>JSON.stringify(c.inputShapes)).join(",")}catch{o="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}const r=n.name,i=n.getClassName(),a=[`${r} (${i})`,o,s,n.countParams().toString()];il(a,t,e)}function q$(n,t,e,s){let o,r;try{r=n.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch{r="multiple"}try{o=JSON.stringify(n.outputShape)}catch{o="multiple"}const i=[];for(const d of n.inboundNodes)if(!(e!=null&&e.length>0&&e.indexOf(d)===-1))for(let h=0;h{const t=Object.keys(n);if(t.length===0)return!1;const e=t[0].split("/");return!isNaN(parseInt(e[e.length-1],10))};class En extends Ct{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,this.name==null){const x=this.getClassName().toLowerCase();this.name=Bc(x)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],Ts(this.inputs).length!==this.inputs.length)throw new $(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(x=>x.name)}`);Ts(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(x=>x.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const x of this.outputs){const I=x.sourceLayer,y=x.nodeIndex,w=x.tensorIndex;this.outputLayers.push(I),this.outputLayersNodeIndices.push(y),this.outputLayersTensorIndices.push(w)}for(const x of this.inputs){const I=x.sourceLayer,y=x.nodeIndex,w=x.tensorIndex;Bn(y===0,"input layer has >1 nodes"),Bn(w===0,"input layer has >1 tensors"),this.inputLayers.push(I),this.inputLayersNodeIndices.push(y),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let x=0;xx.shape),this.internalOutputShapes=this.outputs.map(x=>x.shape);const e={},s={},o={},r={},i={},a=[],c=(x,I,y,w,C,k)=>{(w==null||C==null||k==null)&&(w=x.sourceLayer,C=x.nodeIndex,k=x.tensorIndex);const S=w.inboundNodes[C];if(y.indexOf(S)!==-1)throw new gn(`The tensor ${x.name} at layer "${w.name}" is part of a cycle.`);if(I.indexOf(S)!==-1)return;this.containerNodes.add(En.nodeKey(w,C)),w.id in i||(i[w.id]=Object.keys(i).length),y.indexOf(S)===-1&&y.push(S);const T=S.inboundLayers.length;for(let R=0;R=0;)y.splice(y.indexOf(S),1);a.push(S)},l=[],u=[];for(const x of this.outputs)c(x,l,u);const d=a.slice().reverse();for(const x of d){s[x.id]=x,x.id in e||(e[x.id]=0);let I=e[x.id];const y=o[x.outboundLayer.id]==null?0:o[x.outboundLayer.id];I=Math.max(I,y),o[x.outboundLayer.id]=I,r[x.outboundLayer.id]=x.outboundLayer,e[x.id]=I;for(let w=0;wparseInt(x,10)).sort(Kc);this.layers=[];for(const x of f){const I=p[x];I.sort((y,w)=>{const C=i[y.id],k=i[w.id];return Ck?1:0});for(const y of I)y instanceof En&&this.internalContainerRefs.push(y),this.layers.push(y)}this.layersByDepth=p,f=Object.keys(h).map(x=>parseInt(x,10)).sort(Kc);const m=this.inputs.slice(),g=[];for(const x of f)for(const I of h[x]){const y=I.outboundLayer;if(y!=null){for(const w of I.inputTensors)if(m.indexOf(w)===-1)throw new gn(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${y.name}". The following previous layers were accessed without issue: ${g}`);for(const w of I.outputTensors)m.push(w);g.push(y.name)}}this.nodesByDepth=h;const b=this.layers.map(x=>x.name);for(const x of b){const I=b.filter(y=>y===x).length;if(I!==1)throw new gn(`The name "${x}" is used ${I} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(b))}this.outboundNodes=[],this.inboundNodes=[],new Qc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(x=>null),outputMasks:this.outputs.map(x=>null),inputShapes:this.inputs.map(x=>x.shape),outputShapes:this.outputs.map(x=>x.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const t={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const e of this.layers)t.numDisposedVariables+=e.dispose().numDisposedVariables;for(const e of this.internalContainerRefs)t.numDisposedVariables+=e.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(e=>{e._trainableWeights.forEach(s=>s.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new $("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let t=[];for(const e of this.layers)t=t.concat(e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.layers)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const s of this.layers)e.push(...s.trainableWeights);return e.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,e=!0){const s={};let o=0;const r=tG(t);r&&this.parseWeights(t);for(const a of this.layers)for(const[c,l]of a.weights.entries()){const u=r?`${l.name.split("/").slice(0,-1).join("/")+"/"}${c}`:l.originalName;if(s[u]!=null)throw new $(`Duplicate weight name: ${u}`);s[u]=l,o++}const i=[];for(const a in t){let c=a;if(s[a]==null){const l=a.split("/");c=l.slice(0,-2).concat([l[l.length-1]]).join("/")}if(s[c]!=null)i.push([s[c],t[a]]);else if(e)throw new $(`Provided weight data has no target variable: ${a}`);delete s[c]}if(e){const a=[];for(const c in s)a.push(c);if(a.length>0)throw new $(`${a.length} of ${o} weights are not set: ${a}`)}Kh(i)}parseWeights(t){for(const e in Object.keys(t)){const s=e.split("/"),o=["vars","layer_checkpoint_dependencies"],r=s.map(i=>i.startsWith("_")?i.slice(1):i).filter(i=>!o.includes(i)).join("/");r!==e&&(t[r]=t[e],delete t[e])}}updatedConfig(){const t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion=`tfjs-layers ${Y0}`,e.backend="TensorFlow.js",e}toJSON(t,e=!0){const s=Qh(this.updatedConfig());return e?JSON.stringify(s):s}call(t,e){return M(()=>{t=Lt(t);const s=new $s;for(let o=0;o{t=Lt(t);let s;return e==null?s=ho(null,t.length):s=Lt(e),this.runInternalGraph(t,s)[1]})}computeOutputShape(t){const e=Uc(t);if(e.length!==this.inputLayers.length)throw new $(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let a=0;aparseInt(a,10)).sort(Kc);if(o.length>1)for(const a of o){const c=this.nodesByDepth[a];for(const l of c){const u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;const d=[];for(let m=0;mparseInt(c,10)).sort(Kc);for(const c of o){const l=this.nodesByDepth[c];for(const u of l){const d=u.outboundLayer,h=u.inputTensors,p=u.outputTensors,f=new Array;for(const m of h)m.id in s&&f.push(s[m.id]);if(f.length===h.length){let m={},g,b,x,I;if(u.callArgs!=null&&(m=u.callArgs),f.length===1){const[y,w]=f[0];m.mask==null&&(m.mask=w),x=Lt(d.call(y,m)),I=Lt(d.computeMask(y,w)),g=[y],b=[w]}else g=f.map(y=>y[0]),b=f.map(y=>y[1]),m.mask==null&&(m.mask=b),x=Lt(d.call(g,m)),I=Lt(d.computeMask(g,b));if(d.activityRegularizer)throw new bt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let y=0;y{const t=[];for(const e of this.layers)for(let s=0;s0){const m=[];for(let g=0;g0&&g.apply(Pe(x),I)}function l(g){const b=g.name,x=us(g,e.customObjects!=null?e.customObjects:{});x.setFastWeightInitDuringBuild(o),r[b]=x,g.inboundNodes.forEach(y=>{if(!(y instanceof Array))throw new $(`Corrupted configuration, expected array for nodeData: ${y}`);a(x,y)})}const u=e.name,d=e.layers;for(const g of d)l(g);for(;!XR(i);)for(const g of d){const b=r[g.name];if(b.name in i){const x=i[b.name];delete i[b.name];for(const I of x)c(b,I)}}const h=[],p=[],f=e.inputLayers;for(const g of f){const b=g[0],x=g[1],I=g[2];Bn(b in r);const w=r[b].inboundNodes[x].outputTensors;h.push(w[I])}const m=e.outputLayers;for(const g of m){const b=g[0],x=g[1],I=g[2];Bn(b in r);const w=r[b].inboundNodes[x].outputTensors;p.push(w[I])}return new t({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new $("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const t of this.layers)if(t.stateful)return!0;return!1}resetStates(){M(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function eG(n,t,e){const s=t.length;if(n==null||Array.isArray(n)&&n.length===0)return t.map(o=>null);if(s===1)return Array.isArray(n)&&n.length===1?n:typeof n=="object"&&t[0]in n?[n[t[0]]]:[n];if(Array.isArray(n)){if(n.length!==s)throw new Error(`Provided ${e} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return n}else if(typeof n=="object"&&Object.keys(n).length>0&&typeof n[Object.keys(n)[0]]=="object"){const o=[];return t.forEach(r=>{r in n?o.push(n[r]):o.push(null)}),o}else throw new Error(`The model has multiple (${s}) outputs, so ${e} must be either an array with ${s} elements or an object with ${t} keys. Provided ${e} not understood: ${JSON.stringify(n)}`)}function Q0(n,t){return eG(n,t,"classWeight")}async function J0(n,t,e,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(e!=null){const o=M(()=>{if(n.shape.length===1)return to(n);if(n.shape.length===2){if(n.shape[1]>1)return vi(n,1);if(n.shape[1]===1)return W(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),r=Array.from(await o.data());vt(o);const i=[];return r.forEach(a=>{if(e[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);i.push(e[a])}),Ue(i,"float32")}else return null}function nG(n,t){return E(n,t)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const sG=32;function j0(n,t){let e,s;const o=t;e=o.xs,s=o.ys,v(e!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);const r=q0("input",n.inputNames,e),i=q0("output",n.outputNames,s),a=r[0].shape[0];v(r.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length} inputs, but the dataset provides ${r.length} inputs. (Expected input keys: ${JSON.stringify(n.inputNames)})`),v(i.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let c=0;c`Batch size mismatch: input ${n.inputNames[c]} has ${r[c].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);for(let c=0;c`Batch size mismatch: output ${n.outputNames[c]} has ${i[c].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);return{xs:r,ys:i}}function q0(n,t,e){if(e instanceof ae)return[e];if(Array.isArray(e))return v(e.length===t.length,()=>`Received an array of ${e.length} Tensors, but expected ${t.length} to match the ${n} keys ${t}.`),e;{const s=[];for(const o of t){if(e[o]==null)throw new $(`The feature data generated by the dataset lacks the required ${n} key '${o}'.`);s.push(e[o])}return s}}function oG(n){if(n.length===3)throw new bt("Validation with sample weights is not implemented yet.");return{xs:n[0],ys:n[1]}}async function rG(n,t,e){const s=e.batchesPerEpoch!=null;if(v(n.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v(e!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v(e.epochs!=null&&e.epochs>0&&Number.isInteger(e.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${e.epochs}`),v(!s||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${e.batchesPerEpoch}`),v(e.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0;try{const o=e.validationData!=null;let r,i;if(o)if(tb(e.validationData))v(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${e.validationBatches}`);else{const g=oG(e.validationData);r=g.xs,i=g.ys}const a=n.makeTrainFunction(),c=n.getDedupedMetricsNames();let l;o?l=c.slice().concat(c.map(g=>"val_"+g)):l=c.slice();const u=X0(e.callbacks,e.yieldEvery),d=e.verbose==null?1:e.verbose,{callbackList:h,history:p}=A0(u,d,e.epochs,null,null,iG(t,e),null,o,l);h.setModel(n),n.history=p,await h.onTrainBegin(),n.stopTraining_=!1;let f=e.initialEpoch==null?0:e.initialEpoch,m=await t.iterator();for(;f=e.batchesPerEpoch:I.done){if(o){let y;tb(e.validationData)?y=Lt(await n.evaluateDataset(e.validationData,{batches:e.validationBatches})):y=Lt(n.evaluate(r,i,{batchSize:e.validationBatchSize==null?sG:e.validationBatchSize,verbose:0}));for(let w=0;w0)throw new bt("Verbose mode is not implemented yet.");v(!s||e.batches>0&&Number.isInteger(e.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(e.batches)}`);const i=aG(t)?t:await t.iterator();let a=0,c=0;for(;!s||c{if(l.value){const{xs:u,ys:d}=j0(n,l.value),h=u.concat(d),p=M(()=>o(h));if(vt(h),c===0)for(let m=0;mQ(r[m],E(f,g))),c>0&&vt(b)}vt(p),a+=f,++c}return r}),l.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${e.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let l=0;l0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function Ui(n,t,e){return n==null?[null]:Array.isArray(n)?n.map(s=>go(s,t,e-t)):go(n,t,e-t)}function jh(n,t){return M(()=>n==null?null:Array.isArray(n)?n.map(e=>jh(e,t)):b0(n,t.dtype==="int32"?t:st(t,"int32")))}function qh(n,t){const e=[];let s=0,o=null;for(;s=n&&(o=n),e.push([s,o]),s=o;return e}function eb(n){const t=[];n instanceof ae&&(n=[n]);for(let e=0;ee.push(o.id));else if(t!=null)for(const o in t){const r=t[o];e.push(r.id)}const s=[];if(n instanceof ae)e.indexOf(n.id)===-1&&s.push(n);else if(Array.isArray(n))n.forEach(o=>{e.indexOf(o.id)===-1&&s.push(o)});else if(n!=null)for(const o in n){const r=n[o];e.indexOf(r.id)===-1&&s.push(r)}s.forEach(o=>{o.isDisposed||o.dispose()})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function lG(n){return n instanceof ae}function tp(n){return Array.isArray(n)}function nb(n){return!lG(n)&&!tp(n)}function sb(n,t,e,s=!0,o=""){if(t==null||t.length===0){if(n!=null){let i=!1;if(tp(n)&&n.length>0)i=!0;else if(nb(n)){for(const a in n)if(n.hasOwnProperty(a)){i=!0;break}}else i=!0;if(i)throw new $(`Error when checking model ${o} expected no data, but got ${n}`)}return[]}if(n==null)return t.map(i=>null);let r;if(nb(n)){n=n,r=[];for(const i of t){if(n[i]==null)throw new $(`No data provided for "${i}". Need data for each key in: ${t}`);r.push(n[i])}}else if(tp(n)){if(n=n,n.length!==t.length)throw new $(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${n}`);r=n}else{if(n=n,t.length>1)throw new $(`The model ${o} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);r=[n]}if(r=eb(r),e!=null)for(let i=0;i=0&&l!==u)throw new $(`${o} expected a batch of elements where each example has shape [${e[i].slice(1,e[i].length)}] (i.e.,tensor shape [*,${e[i].slice(1,e[i].length)}]) but the ${o} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1,a.shape.length)}] (tensor shape [${a.shape}])`)}}return r}function uG(n,t,e){const s=Ts(n.map(r=>r.shape[0]));s.sort();const o=Ts(t.map(r=>r.shape[0]));if(o.sort(),s.length>1)throw new $(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map(r=>r.shape))}`);if(o.length>1)throw new $(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(r=>r.shape))}`);if(s.length>0&&o.length>0&&!Rt(s,o))throw new $(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${o[0]} target sample(s).`)}function dG(n,t,e){const s=[tl,nl,_i];for(let o=0;o1)throw new $(`The model expects ${t.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);r=[n]}if(e!=null)for(let i=0;i[]);let e;if(typeof n=="string"||typeof n=="function")e=[n];else if(Array.isArray(n)||typeof n=="object")e=n;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);if(Array.isArray(e))return t.map(s=>e);{const s=[];for(const o of t){let r=e.hasOwnProperty(o)?e[o]:[];Array.isArray(r)||(r=[r]),s.push(r)}return s}}const pG="layers-model";class sr extends En{constructor(t){super(t),this.isTraining=!1}summary(t,e,s=console.log){if(!this.built)throw new $("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");Y$(this,t,e,s)}compile(t){if(t.loss==null&&(t.loss=[]),this.loss=t.loss,typeof t.optimizer=="string")this.optimizer_=U$(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof ks))throw new $("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}let e=[];if(!Array.isArray(t.loss)&&typeof t.loss!="string"&&typeof t.loss!="function"){t.loss=t.loss;for(const i in t.loss)if(this.outputNames.indexOf(i)===-1)throw new $(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);for(const i of this.outputNames)t.loss[i]==null&&console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`),e.push(_h(t.loss[i]))}else if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new $(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${t.loss}.`);e=t.loss.map(a=>_h(a))}else{const i=_h(t.loss);this.outputs.forEach(a=>{e.push(i)})}this.lossFunctions=e,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let i=0;i{for(let i=0;i1&&(this.metricsTensors.push([a,i]),this.metricsNames.push(this.outputNames[i]+"_loss"))}});const o=hG(t.metrics,this.outputNames),r=(i,a,c)=>{this.outputNames.length>1&&(a=this.outputNames[i]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([c,i])};mo("metric",()=>{for(let i=0;i{const u="";let d,h,p;for(const f of l){if(typeof f=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(f)!==-1){const g=this.internalOutputShapes[i];g[g.length-1]===1||this.lossFunctions[i]===nl?["accuracy","acc"].indexOf(f)!==-1?h=O0:["crossentropy","ce"].indexOf(f)!==-1&&(h=z$):this.lossFunctions[i]===el?["accuracy","acc"].indexOf(f)!==-1?h=X$:["crossentropy","ce"].indexOf(f)!==-1&&(h=B0):["accuracy","acc"].indexOf(f)!==-1?h=K0:["crossentropy","ce"].indexOf(f)!==-1&&(h=Z0);let b;["accuracy","acc"].indexOf(f)!==-1?b="acc":["crossentropy","ce"].indexOf(f)!==-1&&(b="ce"),p=h,d=u+b}else p=_$(f),d=u+rl(f);let m;mo(d,()=>{m=p}),r(i,d,m)}})(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(t,e,s={}){const o=s.batchSize==null?32:s.batchSize;Jh(o);const i=this.standardizeUserDataXY(t,e,!0,o);try{const a=i[0].concat(i[1]);this.makeTestFunction();const c=this.testFunction,l=this.testLoop(c,a,o,s.verbose,s.steps);return Pe(l)}finally{Dn(i[0],t),Dn(i[1],e)}}async evaluateDataset(t,e){return this.makeTestFunction(),cG(this,t,e)}checkNumSamples(t,e,s,o="steps"){let r;if(s!=null){if(r=null,e!=null)throw new $(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${e}`)}else if(t!=null)Array.isArray(t)?r=t[0].shape[0]:r=t.shape[0];else throw new $(`Either the input data should have a defined shape, or ${o} shoud be specified.`);return r}execute(t,e){if(Array.isArray(e)&&e.length===0)throw new $("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(e),o=s?e:[e],r=this.retrieveSymbolicTensors(o),i=new $s;if(t instanceof ae&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new $(`The number of inputs provided (${t.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let c=0;ca.name);for(let a=0;a0){const o=[];throw e.forEach((r,i)=>{r==null&&o.push(t[i])}),new $(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`)}return e}predictLoop(t,e=32,s=!1){return M(()=>{const o=this.checkNumSamples(t);if(s)throw new bt("Verbose predictLoop() is not implemented yet.");const r=qh(o,e),i=this.outputs.map(a=>[]);for(let a=0;a{const l=r[a][0],u=r[a][1],d=Ui(t,l,u),h=[];if(Array.isArray(d))for(let f=0;fi[u].push(l));return Pe(i.map(a=>Xe(a,0)))})}predict(t,e={}){const s=eb(t);ob(s,this.inputNames,this.feedInputShapes,!1);try{const o=e.batchSize==null?32:e.batchSize;return Jh(o),this.predictLoop(s,o)}finally{Dn(s,t)}}predictOnBatch(t){ob(t,this.inputNames,this.feedInputShapes,!0);const e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)}standardizeUserDataXY(t,e,s=!0,o){if(this.optimizer_==null)throw new gn("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let i=0;i0&&t[0].shape[0]%o!==0)throw new $(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${t[0].shape[0]} sample(s).`);return[t,e]}async standardizeUserData(t,e,s,o,r=!0,i){const[a,c]=this.standardizeUserDataXY(t,e,r,i);if(s!=null)throw new Error("sample weight is not supported yet.");let l=null;if(o!=null){const u=Q0(o,this.outputNames);l=[];for(let d=0;d{const i=this.checkNumSamples(e,s,r,"steps"),a=[];if(o>0)throw new bt("Verbose mode is not implemented yet.");if(r!=null)throw new bt("steps mode in testLoop() is not implemented yet");{const c=qh(i,s),l=Ue($n(0,i));for(let u=0;u1){const i=a0(t.slice(0,s),o);r+=`_${i}`}e.push(r)}return e}makeTrainFunction(){return t=>{const e=[],s=t.slice(0,this.inputs.length),o=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=t.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),i=[],a=()=>{const d=[];for(let m=0;m1&&m{f=Q(f,m)}),f},c=this.collectedTrainableWeights.map(d=>d.read());return[this.optimizer_.minimize(a,!0,c)].concat(i)}}makeTestFunction(){this.testFunction=t=>M(()=>{const e=[];let s;const o=t.slice(0,this.inputs.length),r=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=[];for(let l=0;l0){if(g=!0,s.validationData.length===2)c=s.validationData[0],l=s.validationData[1];else throw s.validationData.length===3?new bt("validationData including sample weights is not supported yet."):new $(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const R=await this.standardizeUserData(c,l,null,null,!0,p);u=R[0],d=R[1],b=u.concat(d)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){g=!0;const T=Math.floor(o[0].shape[0]*(1-s.validationSplit)),R=o[0].shape[0];u=Ui(o,T,R),i=o,o=Ui(o,0,T),d=Ui(r,T,R),a=r,r=Ui(r,0,T),b=u.concat(d)}else s.validationSteps!=null&&(g=!0);const x=o.concat(r).concat(h);this.checkTrainableWeightsConsistency();const I=this.makeTrainFunction(),y=this.getDedupedMetricsNames();let w,C;g?(this.makeTestFunction(),w=this.testFunction,C=y.slice().concat(y.map(T=>"val_"+T))):(w=null,b=[],C=y.slice());const k=X0(s.callbacks,s.yieldEvery);return await this.fitLoop(I,x,y,p,s.epochs,s.verbose,k,w,b,s.shuffle,C,s.initialEpoch,null,null)}finally{this.isTraining=!1,Dn(o,t),Dn(r,e),Dn(i,t),Dn(a,e),Dn(u,c),Dn(d,l),h!=null&&vt(h)}}async fitLoop(t,e,s,o,r,i,a,c,l,u,d,h,p,f){o==null&&(o=32),r==null&&(r=1),u==null&&(u=!0),h==null&&(h=0);let m=!1;if(c!=null&&l!=null&&(m=!0),f!=null&&(m=!0,p==null))throw new $("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=this.checkNumSamples(e,o,p,"steps_per_epoch");let b;g!=null&&(b=$n(0,g)),i==null&&(i=1);const{callbackList:x,history:I}=A0(a,i,r,h,g,p,o,m,d);x.setModel(this),this.history=I,await x.onTrainBegin(),this.stopTraining_=!1;for(let y=h;y{const R=k[S][0],L=k[S][1],V=go(C,R,L-R);T.batch=S,T.size=L-R;const F=jh(e,V),X=t(F);for(let A=0;Als(e))}else{const e=Object.keys(this.loss);t={};const s=this.loss;for(const o of e)if(typeof s[o]=="string")t[o]=ls(s[o]);else throw new Error("Serialization of non-string loss is not supported.")}return t}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ls(rl(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(t=>ls(rl(t)));{const t={};for(const e in this.metrics)t[e]=ls(rl(this.metrics[e]));return t}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(t){if(t.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(t.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(t.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const e=Yh(t.optimizer_config),s=us(e);let o;if(typeof t.loss=="string")o=po(t.loss);else if(Array.isArray(t.loss))o=t.loss.map(i=>po(i));else if(t.loss!=null){o={};for(const i in t.loss)o[i]=po(t.loss[i])}let r;if(Array.isArray(t.metrics))r=t.metrics.map(i=>po(i));else if(t.metrics!=null){r={};for(const i in t.metrics)r[i]=po(t.metrics[i])}this.compile({loss:o,metrics:r,optimizer:s})}async save(t,e){if(typeof t=="string"){const l=_w(t);if(l.length===0)throw new $(`Cannot find any save handlers for URL '${t}'`);if(l.length>1)throw new $(`Found more than one (${l.length}) save handlers for URL '${t}'`);t=l[0]}if(t.save==null)throw new $("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await ym(this.getNamedWeights(e)),a={modelTopology:this.toJSON(null,!1),format:pG,generatedBy:`TensorFlow.js tfjs-layers v${Y0}`,convertedBy:null};if((e==null?!1:e.includeOptimizer)&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const l="optimizer",{data:u,specs:d}=await ym(await this.optimizer.getWeights(),l);s.specs.push(...d),s.data=Hw([s.data,u])}return this.userDefinedMetadata!=null&&(_0(this.userDefinedMetadata,this.name,!0),a.userDefinedMetadata=this.userDefinedMetadata),a.weightData=s.data,a.weightSpecs=s.specs,t.save(a)}setUserDefinedMetadata(t){_0(t,this.name),this.userDefinedMetadata=t}getUserDefinedMetadata(){return this.userDefinedMetadata}}sr.className="Model",_(sr);class rb extends sr{}rb.className="Functional",_(rb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Yi extends sr{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=t.name!=null?t.name:Bc("sequential_"),t.layers!=null)for(const e of t.layers)this.add(e)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some(s=>s<0))throw new $(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){const e=t instanceof Yi||t instanceof sr;let s;if(e){if(s=t,s.outputs.length!==1)throw new $("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new $("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(t.inboundNodes.length===0){if(t.batchInputShape==null)throw new $("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const o=g$({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(o)}if(e)this.outputs=s.outputs,this.inputs=s.inputs;else{if(t.inboundNodes.length!==1)throw new $(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(t.inboundNodes[0].outputTensors.length!==1)throw new $("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=$0(this.outputs[0])}this.inboundNodes=[],new Qc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ho(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(o=>o.shape),outputShapes:this.outputs[0].shape})}else{const o=t.apply(this.outputs[0]);if(Array.isArray(o))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[o],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,e){return this.model==null&&this.build(),this.model.call(t,e)}build(t){if(Nt(t),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new sr({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(t,e,s=console.log){this.built||this.build(),super.summary(t,e,s)}setWeights(t){this.model==null&&this.build(),this.model.setWeights(t)}evaluate(t,e,s={}){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.evaluate(t,e,s)}async evaluateDataset(t,e){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,e)}predict(t,e={}){return this.model==null&&this.build(),this.model.predict(t,e)}predictOnBatch(t){return this.model==null&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(t){this.model.optimizer=t}async fit(t,e,s={}){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.fit(t,e,s)}async fitDataset(t,e){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.fitDataset(t,e)}async trainOnBatch(t,e){return this.model.trainOnBatch(t,e)}static fromConfig(t,e,s={},o=!1){let r,i={};if(e instanceof Array){if(e[0].className==null||e[0].className==="Merge")throw new $("Legacy serialization format not supported yet.");r=e}else v(e.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=e.layers,delete e.layers,i=e;const a=new t(i);if(!(a instanceof Yi))throw new bt(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of r){const u=us(c,void 0,o);o&&u.setFastWeightInitDuringBuild(!0),a.add(u)}return a}set stopTraining(t){if(this.model==null)throw new $("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(this.model==null)throw new $("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const t=[];for(const e of this.layers){const s={};s.className=e.getClassName(),s.config=e.getConfig(),t.push(s)}return{name:this.name,layers:t}}}Yi.className="Sequential",_(Yi);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */let Oe=class extends qo{getConfig(){return{}}};class ib extends Oe{apply(t,e=1){return t$(t,e)}}ib.className="elu",_(ib);class ab extends Oe{apply(t){return Qm(t)}}ab.className="selu",_(ab);class cb extends Oe{apply(t){return io(t)}}cb.className="relu",_(cb);class lb extends Oe{apply(t){return M(()=>Gi(6,io(t)))}}lb.className="relu6",_(lb);class ub extends Oe{apply(t){return t}}ub.className="linear",_(ub);class db extends Oe{apply(t){return _o(t)}}db.className="sigmoid",_(db);class hb extends Oe{apply(t){return n$(t)}}hb.className="hardSigmoid",_(hb);class pb extends Oe{apply(t){return $i(t)}}pb.className="softplus",_(pb);class fb extends Oe{apply(t){return e$(t)}}fb.className="softsign",_(fb);class mb extends Oe{apply(t){return pd(t)}}mb.className="tanh",_(mb);let ep=class extends Oe{apply(t,e=-1){return zd(t,e)}};ep.className="softmax",_(ep);class gb extends Oe{apply(t,e=-1){return Pm(t,e)}}gb.className="logSoftmax",_(gb);class bb extends Oe{apply(t,e=1){return M(()=>E(_o(E(t,e)),t))}}bb.className="swish",_(bb);class xb extends Oe{apply(t){return M(()=>E(t,pd($i(t))))}}xb.className="mish",_(xb);function Gs(n){return n.getClassName()}function np(n,t={}){return zi(n,mn.getMap().classNameMap,t,"activation")}function Ls(n){if(n==null){const t={};return t.className="linear",t.config={},np(t)}if(typeof n=="string"){const t={};return t.className=n,t.config={},np(t)}else return n instanceof Oe?n:np(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function fG(n){if(n!=null&&typeof n!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}class yb extends qo{}class Ib extends yb{constructor(t){super(),fG(t),this.l1=t==null||t.l1==null?.01:t.l1,this.l2=t==null||t.l2==null?.01:t.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(t){return M(()=>{let e=ge([1]);return this.hasL1&&(e=Q(e,ut(E(this.l1,Ge(t))))),this.hasL2&&(e=Q(e,ut(E(this.l2,Pi(t))))),W(e,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(t,e){return new t({l1:e.l1,l2:e.l2})}}Ib.className="L1L2",_(Ib);const wb={l1l2:"L1L2"};function Vt(n){return Th(n)}function Cb(n,t={}){return zi(n,mn.getMap().classNameMap,t,"regularizer")}function _t(n){if(n==null)return null;if(typeof n=="string"){const e={className:n in wb?wb[n]:n,config:{}};return Cb(e)}else return n instanceof yb?n:Cb(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class vb extends Ct{constructor(t){super(t??{}),this.supportsMasking=!0,t!=null&&(this.maxValue=t.maxValue)}call(t,e){t=mt(t);let s=io(t);return this.maxValue!=null&&(s=nn(s,0,this.maxValue)),s}computeOutputShape(t){return t}getConfig(){const t={maxValue:this.maxValue},e=super.getConfig();return Object.assign(t,e),t}}vb.className="ReLU",_(vb);class Sb extends Ct{constructor(t){super(t??{}),this.DEFAULT_ALPHA=.3,t==null&&(t={}),this.alpha=t.alpha==null?this.DEFAULT_ALPHA:t.alpha}call(t,e){const s=mt(t);return Cd(s,this.alpha)}computeOutputShape(t){return t}getConfig(){const t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}}Sb.className="LeakyReLU",_(Sb);class kb extends Ct{constructor(t){if(super(t??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",t==null&&(t={}),this.supportsMasking=!0,this.alphaInitializer=Ht(t.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(t.alphaRegularizer),this.alphaConstraint=he(t.alphaConstraint),t.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(t.sharedAxes))this.sharedAxes=t.sharedAxes;else if(typeof t.sharedAxes=="number")this.sharedAxes=[t.sharedAxes];else throw new $(`Expected sharedAxes to be a number or an array of numbers, but got ${t.sharedAxes}`)}build(t){t=Nt(t);const e=t.slice(1);if(this.sharedAxes!=null)for(const o of this.sharedAxes)e[o-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let o=1;o{let s=mt(t);const o=e.mask;if(o!=null){const r=E(pt(Ss(s.shape),st(o,s.dtype)),Gt(-1e9));s=Q(s,r)}return this.axis instanceof Array?this.axis.length>1?An(pt(s,Om(s,this.axis,!0))):this.softmax(s,this.axis[0]):this.softmax(s,this.axis)})}computeOutputShape(t){return t}getConfig(){const t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}}Rb.className="Softmax",_(Rb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function or(n,t,e){if(typeof n=="number")return ho(n,t);if(n.length!==t)throw new $(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${n.length} elements.`);for(let s=0;s(se(t),t==="channelsFirst"?kt(n,[0,2,3,1]):n))}function $b(n,t){return M(()=>(se(t),t==="channelsFirst"?kt(n,[0,2,3,4,1]):n))}function mG(n,t,e,s=1,o="valid",r,i=1){return M(()=>{if(r==null&&(r=Gn()),se(r),n.shape.length!==3)throw new $(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);if(t.shape.length!==3)throw new $(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(e!=null&&e.shape.length!==1)throw new $(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(r==="channelsFirst"&&(n=kt(n,[0,2,1])),o==="causal")throw new bt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=Lm(n,t,s,o==="same"?"same":"valid","NWC",i);return e!=null&&(a=Ln(a,e)),a})}function Gb(n,t,e,s=[1,1],o="valid",r,i,a=null){return M(()=>{if(r==null&&(r=Gn()),se(r),n.rank!==3&&n.rank!==4)throw new $(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(t.rank!==3&&t.rank!==4)throw new $(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let c=sp(n,r);if(o==="causal")throw new bt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return c=vk({x:c,filter:t,strides:s,pad:o==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:e,activation:a}),r==="channelsFirst"&&(c=kt(c,[0,3,1,2])),c})}function gG(n,t,e,s=[1,1,1],o="valid",r,i){return M(()=>{if(r==null&&(r=Gn()),se(r),n.rank!==4&&n.rank!==5)throw new $(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);if(t.rank!==4&&t.rank!==5)throw new $(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);let a=$b(n,r);if(o==="causal")throw new bt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=C2(a,t,s,o==="same"?"same":"valid","NDHWC",i),e!=null&&(a=Ln(a,e)),r==="channelsFirst"&&(a=kt(a,[0,4,1,2,3])),a})}class al extends Ct{constructor(t,e){if(super(e),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",al.verifyArgs(e),this.rank=t,be(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new bt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=or(e.kernelSize,t,"kernelSize"),this.strides=or(e.strides==null?1:e.strides,t,"strides"),this.padding=e.padding==null?"valid":e.padding,rn(this.padding),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,se(this.dataFormat),this.activation=Ls(e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.biasInitializer=Ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=he(e.biasConstraint),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.dilationRate=or(e.dilationRate==null?1:e.dilationRate,t,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new $(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new $(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new $(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(t){if(Bn("kernelSize"in t,"required key 'kernelSize' not in config"),typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,3))throw new $(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){const t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Gs(this.activation),useBias:this.useBias,biasInitializer:Qt(this.biasInitializer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),biasConstraint:de(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}class rr extends al{constructor(t,e){super(t,e),this.kernel=null,rr.verifyArgs(e),this.filters=e.filters,be(this.filters,"filters"),this.kernelInitializer=Ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=he(e.kernelConstraint),this.kernelRegularizer=_t(e.kernelRegularizer)}build(t){t=Nt(t);const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $(`The channel dimension of the input should be defined. Found ${t[e]}`);const s=t[e],o=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[e]:s}}],this.built=!0}call(t,e){return M(()=>{t=mt(t);let s;const o=this.bias==null?null:this.bias.read(),r=l0(this.activation.getClassName());if(r!=null&&this.rank===2)s=Gb(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)s=mG(t,this.kernel.read(),o,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=Gb(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=gG(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new bt("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(t){t=Nt(t);const e=[],s=this.dataFormat==="channelsLast"?t.slice(1,t.length-1):t.slice(2);for(let r=0;r 0 but got ${JSON.stringify(t.filters)}`)}}class Qi extends rr{constructor(t){super(2,t),Qi.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,2))throw new $(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}}Qi.className="Conv2D",_(Qi);class Ji extends rr{constructor(t){super(3,t),Ji.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!(Array.isArray(t.kernelSize)&&(t.kernelSize.length===1||t.kernelSize.length===3)))throw new $(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}}Ji.className="Conv3D",_(Ji);class Lb extends Qi{constructor(t){if(super(t),this.inputSpec=[new ue({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new $(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Nt(t),t.length!==4)throw new $("Input should have rank 4; Received input shape: "+JSON.stringify(t));const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $("The channel dimension of the inputs should be defined. Found `None`.");const s=t[e],o=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new ue({ndim:4,axes:{[e]:s}})],this.built=!0}call(t,e){return M(()=>{let s=mt(t);if(s.shape.length!==4)throw new $(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const o=s.shape,r=o[0];let i,a;this.dataFormat==="channelsFirst"?(i=2,a=3):(i=1,a=2);const c=o[i],l=o[a],u=this.kernelSize[0],d=this.kernelSize[1],h=this.strides[0],p=this.strides[1],f=Yn(c,h,u,this.padding),m=Yn(l,p,d,this.padding),g=[r,f,m,this.filters];this.dataFormat!=="channelsLast"&&(s=kt(s,[0,2,3,1]));let b=Em(s,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(b=kt(b,[0,3,1,2])),this.bias!=null&&(b=Ln(b,this.bias.read(),this.dataFormat)),this.activation!=null&&(b=this.activation.apply(b)),b})}computeOutputShape(t){t=Nt(t);const e=t.slice();let s,o,r;this.dataFormat==="channelsFirst"?(s=1,o=2,r=3):(s=3,o=1,r=2);const i=this.kernelSize[0],a=this.kernelSize[1],c=this.strides[0],l=this.strides[1];return e[s]=this.filters,e[o]=Yn(e[o],c,i,this.padding),e[r]=Yn(e[r],l,a,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}Lb.className="Conv2DTranspose",_(Lb);class Eb extends Ji{constructor(t){if(super(t),this.inputSpec=[new ue({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new $(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Nt(t),t.length!==5)throw new $("Input should have rank 5; Received input shape: "+JSON.stringify(t));const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $("The channel dimension of the inputs should be defined. Found `None`.");const s=t[e],o=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new ue({ndim:5,axes:{[e]:s}})],this.built=!0}call(t,e){return M(()=>{let s=mt(t);if(s.shape.length!==5)throw new $(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const o=s.shape,r=o[0];let i,a,c;this.dataFormat==="channelsFirst"?(c=2,i=3,a=4):(c=1,i=2,a=3);const l=o[c],u=o[i],d=o[a],h=this.kernelSize[0],p=this.kernelSize[1],f=this.kernelSize[2],m=this.strides[0],g=this.strides[1],b=this.strides[2],x=Yn(l,m,h,this.padding),I=Yn(u,g,p,this.padding),y=Yn(d,b,f,this.padding),w=[r,x,I,y,this.filters];this.dataFormat!=="channelsLast"&&(s=kt(s,[0,2,3,4,1]));let C=k2(s,this.kernel.read(),w,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(C=kt(C,[0,4,1,2,3])),this.bias!==null&&(C=Ln(C,this.bias.read(),this.dataFormat)),this.activation!==null&&(C=this.activation.apply(C)),C})}computeOutputShape(t){t=Nt(t);const e=t.slice();let s,o,r,i;this.dataFormat==="channelsFirst"?(s=1,o=2,r=3,i=4):(s=4,o=1,r=2,i=3);const a=this.kernelSize[0],c=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],d=this.strides[1],h=this.strides[2];return e[s]=this.filters,e[o]=Yn(e[o],u,a,this.padding),e[r]=Yn(e[r],d,c,this.padding),e[i]=Yn(e[i],h,l,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}Eb.className="Conv3DTranspose",_(Eb);class Db extends rr{constructor(t,e){if(super(t,e),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,e.filters==null)throw new $("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(e.kernelInitializer!=null||e.kernelRegularizer!=null||e.kernelConstraint!=null)throw new $("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(e.padding!=null&&e.padding!=="same"&&e.padding!=="valid")throw new $(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(e.padding)}`);this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ht(e.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(e.depthwiseRegularizer),this.depthwiseConstraint=he(e.depthwiseConstraint),this.pointwiseInitializer=Ht(e.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(e.pointwiseRegularizer),this.pointwiseConstraint=he(e.pointwiseConstraint)}build(t){if(t=Nt(t),t.length{t=mt(t);let s;if(this.rank===1)throw new bt("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(t=kt(t,[0,2,3,1])),s=Jm(t,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Ln(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=kt(s,[0,3,1,2])),s})}getConfig(){const t=super.getConfig();return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=Qt(this.depthwiseInitializer),t.pointwiseInitializer=Qt(this.pointwiseInitializer),t.depthwiseRegularizer=Vt(this.depthwiseRegularizer),t.pointwiseRegularizer=Vt(this.pointwiseRegularizer),t.depthwiseConstraint=de(this.depthwiseConstraint),t.pointwiseConstraint=de(this.pointwiseConstraint),t}}Db.className="SeparableConv";class Wb extends Db{constructor(t){super(2,t)}}Wb.className="SeparableConv2D",_(Wb);class cl extends rr{constructor(t){super(1,t),cl.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){const t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,1))throw new $(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}}cl.className="Conv1D",_(cl);class Mb extends Ct{constructor(t){super(t),typeof t.cropping=="number"?this.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:typeof t.cropping[0]=="number"?this.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:this.cropping=t.cropping,this.dataFormat=t.dataFormat===void 0?"channelsLast":t.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(t){return this.dataFormat==="channelsFirst"?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]}call(t,e){return M(()=>{if(t=mt(t),this.dataFormat==="channelsLast"){const s=Hc(t,this.cropping[0][0],t.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Hc(s,this.cropping[1][0],t.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=Hc(t,this.cropping[0][0],t.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Hc(s,this.cropping[1][0],t.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const t={cropping:this.cropping,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}Mb.className="Cropping2D",_(Mb);class Vb extends Ct{constructor(t){super(t),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=t.size==null?this.DEFAULT_SIZE:t.size,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),this.interpolation=t.interpolation==null?"nearest":t.interpolation,_R(this.interpolation)}computeOutputShape(t){if(this.dataFormat==="channelsFirst"){const e=t[2]==null?null:this.size[0]*t[2],s=t[3]==null?null:this.size[1]*t[3];return[t[0],t[1],e,s]}else{const e=t[1]==null?null:this.size[0]*t[1],s=t[2]==null?null:this.size[1]*t[2];return[t[0],e,s,t[3]]}}call(t,e){return M(()=>{let s=mt(t);const o=s.shape;if(this.dataFormat==="channelsFirst"){s=kt(s,[0,2,3,1]);const r=this.size[0]*o[2],i=this.size[1]*o[3],a=this.interpolation==="nearest"?is.resizeNearestNeighbor(s,[r,i]):is.resizeBilinear(s,[r,i]);return kt(a,[0,3,1,2])}else{const r=this.size[0]*o[1],i=this.size[1]*o[2];return this.interpolation==="nearest"?is.resizeNearestNeighbor(s,[r,i]):is.resizeBilinear(s,[r,i])}})}getConfig(){const t={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},e=super.getConfig();return Object.assign(t,e),t}}Vb.className="UpSampling2D",_(Vb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function bG(n,t,e=[1,1],s="valid",o,r){return M(()=>{o==null&&(o=Gn()),se(o);let i=sp(n,o);if(n.rank!==4)throw new $(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);if(t.rank!==4)throw new $(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=xd(i,t,e,s==="same"?"same":"valid","NHWC",r),o==="channelsFirst"&&(i=kt(i,[0,3,1,2])),i})}class Fb extends al{constructor(t){super(2,t),this.depthwiseKernel=null,this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Ht(t.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=he(t.depthwiseConstraint),this.depthwiseRegularizer=_t(t.depthwiseRegularizer)}build(t){if(t=Nt(t),t.length<4)throw new $(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(t)}.`);const e=this.dataFormat==="channelsFirst"?1:3;if(t[e]==null||t[e]<0)throw new $(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${t[e]}).`);const s=t[e],o=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",o,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{t=mt(t);let s=bG(t,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Ln(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(t){t=Nt(t);const e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,r=Wn(e,this.kernelSize[0],this.padding,this.strides[0]),i=Wn(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[t[0],o,r,i]:[t[0],r,i,o]}getConfig(){const t=super.getConfig();return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=Qt(this.depthwiseInitializer),t.depthwiseRegularizer=Vt(this.depthwiseRegularizer),t.depthwiseConstraint=de(this.depthwiseRegularizer),t}}Fb.className="DepthwiseConv2D",_(Fb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function zb(n,t,e,s){if(Array.isArray(n)){if(t!=null||e!=null)throw new $("When inputs is an array, neither initialState or constants should be provided");s!=null&&(e=n.slice(n.length-s,n.length),n=n.slice(0,n.length-s)),n.length>1&&(t=n.slice(1,n.length)),n=n[0]}function o(r){return r==null||Array.isArray(r)?r:[r]}return t=o(t),e=o(e),{inputs:n,initialState:t,constants:e}}function Xb(n,t,e,s=!1,o,r,i=!1,a=!1){return M(()=>{const c=t.shape.length;if(c<3)throw new $(`Input should be at least 3D, but is ${c}D.`);const l=[1,0].concat($n(2,c));if(t=kt(t,l),r!=null)throw new bt("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),o!=null&&(o=st(st(o,"bool"),"float32"),o.rank===c-1&&(o=Ae(o,-1)),o=kt(o,l)),s&&(t=ao(t,0),o!=null&&(o=ao(o,0)));const u=[];let d,h=e;const p=t.shape[0],f=lo(t);let m;o!=null&&(m=lo(o));for(let b=0;bn(x,h));if(o==null)d=I[0],h=I[1];else{const y=M(()=>{const w=m[b],C=pt(fn(w),w),k=Q(E(I[0],w),E(h[0],C)),S=h.map((T,R)=>Q(E(I[1][R],w),E(T,C)));return{output:k,newStates:S}});d=y.output,h=y.newStates}a&&u.push(d)}let g;return a&&(g=On(u,1)),[d,g,h]})}class Es extends Ct{constructor(t){super(t);let e;if(t.cell==null)throw new $("cell property is missing for the constructor of RNN.");if(Array.isArray(t.cell)?e=new ip({cells:t.cell}):e=t.cell,e.stateSize==null)throw new $("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=e,this.returnSequences=t.returnSequences==null?!1:t.returnSequences,this.returnState=t.returnState==null?!1:t.returnState,this.goBackwards=t.goBackwards==null?!1:t.goBackwards,this._stateful=t.stateful==null?!1:t.stateful,this.unroll=t.unroll==null?!1:t.unroll,this.supportsMasking=!0,this.inputSpec=[new ue({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return $n(0,t).map(e=>null)}else return this.states_}setStates(t){this.states_=t}computeOutputShape(t){Ph(t)&&(t=t[0]),t=t;let e=this.cell.stateSize;Array.isArray(e)||(e=[e]);const s=e[0];let o;if(this.returnSequences?o=[t[0],t[1],s]:o=[t[0],s],this.returnState){const r=[];for(const i of e)r.push([t[0],i]);return[o].concat(r)}else return o}computeMask(t,e){return M(()=>{Array.isArray(e)&&(e=e[0]);const s=this.returnSequences?e:null;if(this.returnState){const o=this.states.map(r=>null);return[s].concat(o)}else return s})}get states(){if(this.states_==null){const t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[];for(let s=0;si.shape[i.shape.length-1]),r))throw new $(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=r.map(i=>new ue({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(t,e=!1){M(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new $("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>ge([s,o])):this.states_=[ge([s,this.cell.stateSize])];else if(t==null)vt(this.states_),this.keptStates!=null&&(vt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>ge([s,o])):this.states_[0]=ge([s,this.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new $(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e===!0?this.keptStates.push(this.states_.slice()):vt(this.states_);for(let o=0;oen(o.clone()))})}apply(t,e){let s=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});const r=zb(t,s,o,this.numConstants);t=r.inputs,s=r.initialState,o=r.constants;let i=[],a=[];if(s!=null){e.initialState=s,i=i.concat(s),this.stateSpec=[];for(const l of s)this.stateSpec.push(new ue({shape:l.shape}));a=a.concat(this.stateSpec)}if(o!=null&&(e.constants=o,i=i.concat(o),this.numConstants=o.length),i[0]instanceof Un){const l=[t].concat(i),u=this.inputSpec.concat(a),d=this.inputSpec;this.inputSpec=u;const h=super.apply(l,e);return this.inputSpec=d,h}else return super.apply(t,e)}call(t,e){return M(()=>{const s=e==null?null:e.mask,o=e==null?null:e.training;let r=e==null?null:e.initialState;t=mt(t),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(t));const i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==i)throw new $(`RNN Layer has ${i} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const a={training:o},l=Xb((f,m)=>{const g=this.cell.call([f].concat(m),a);return[g[0],g.slice(1)]},t,r,this.goBackwards,s,null,this.unroll,this.returnSequences),u=l[0],d=l[1],h=l[2];this.stateful&&this.resetStates(h,o);const p=this.returnSequences?d:u;return this.returnState?[p].concat(h):p})}getInitialState(t){return M(()=>{let e=ge(t.shape);return e=ut(e,[1,2]),e=Ai(e),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?Eh(e,[1,s]):e):this.cell.stateSize>1?[Eh(e,[1,this.cell.stateSize])]:[e]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){const t=super.getConfig(),e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(e.numConstants=this.numConstants);const s=this.cell.getConfig();return this.getClassName()===Es.className&&(e.cell={className:this.cell.getClassName(),config:s}),Object.assign(Object.assign(Object.assign({},s),t),e)}static fromConfig(t,e,s={}){const o=e.cell,r=us(o,s);return new t(Object.assign(e,{cell:r}))}}Es.className="RNN",_(Es);class ll extends Ct{}class op extends ll{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation==null?this.DEFAULT_ACTIVATION:t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Nt(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{if(t=t,t.length!==2)throw new $(`SimpleRNNCell expects 2 input Tensors, got ${t.length}.`);let s=t[1];t=t[0];const o=e.training==null?!1:e.training;0fn(t),rate:this.dropout,training:o,dropoutFunc:this.dropoutFunc})),0fn(s),rate:this.recurrentDropout,training:o,dropoutFunc:this.dropoutFunc}));let r;const i=this.dropoutMask,a=this.recurrentDropoutMask;i!=null?r=_n(E(t,i),this.kernel.read()):r=_n(t,this.kernel.read()),this.bias!=null&&(r=Ln(r,this.bias.read())),a!=null&&(s=E(s,a));let c=Q(r,_n(s,this.recurrentKernel.read()));return this.activation!=null&&(c=this.activation.apply(c)),[c,c]})}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),recurrentInitializer:Qt(this.recurrentInitializer),biasInitializer:Qt(this.biasInitializer),kernelRegularizer:Vt(this.kernelRegularizer),recurrentRegularizer:Vt(this.recurrentRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),recurrentConstraint:de(this.recurrentConstraint),biasConstraint:de(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},t),e)}}op.className="SimpleRNNCell",_(op);class Ab extends Es{constructor(t){t.cell=new op(t),super(t)}call(t,e){return M(()=>{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return new t(e)}}Ab.className="SimpleRNN",_(Ab);class rp extends ll{constructor(t){if(super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.resetAfter)throw new $("GRUCell does not support reset_after parameter set to true.");this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Ls(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Nt(t);const e=t[t.length-1];this.kernel=this.addWeight("kernel",[e,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{if(t=t,t.length!==2)throw new $(`GRUCell expects 2 input Tensors (inputs, h, c), got ${t.length}.`);const s=e.training==null?!1:e.training;let o=t[1];t=t[0],0fn(t),rate:this.dropout,training:s,count:3,dropoutFunc:this.dropoutFunc})),0fn(o),rate:this.recurrentDropout,training:s,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,i=this.recurrentDropoutMask;let a,c,l;0{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}}Pb.className="GRU",_(Pb);class ul extends ll{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Ls(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=t.unitForgetBias,this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){var e;t=Nt(t);const s=t[t.length-1];this.kernel=this.addWeight("kernel",[s,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let o;if(this.useBias){if(this.unitForgetBias){const r=this.biasInitializer,i=this.units;o=new(e=class extends xn{apply(c,l){const u=r.apply([i]),d=new Wh().apply([i]),h=r.apply([i*2]);return g0(g0(u,d),h)}},e.className="CustomInit",e)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,o,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(t,e){return M(()=>{const s=e.training==null?!1:e.training;if(t=t,t.length!==3)throw new $(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);let o=t[1];const r=t[2];t=t[0],0fn(t),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc})),0fn(o),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,a=this.recurrentDropoutMask;let c,l,u,d;0{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}}Ob.className="LSTM",_(Ob);class ip extends ll{constructor(t){super(t),this.cells=t.cells}get stateSize(){const t=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?t.push(...e.stateSize):t.push(e.stateSize);return t}call(t,e){return M(()=>{t=t;let s=t.slice(1);const o=[];for(const a of this.cells.slice().reverse())Array.isArray(a.stateSize)?o.push(s.splice(0,a.stateSize.length)):o.push(s.splice(0,1));o.reverse();const r=[];let i;for(let a=0;a{mo(`RNNCell_${o}`,()=>{s.build(t),Array.isArray(s.stateSize)?e=s.stateSize[0]:e=s.stateSize,t=[t[0],e]})}),this.built=!0}getConfig(){const t=super.getConfig(),e=r=>({className:r.getClassName(),config:r.getConfig()}),o={cells:this.cells.map(e)};return Object.assign(Object.assign({},t),o)}static fromConfig(t,e,s={}){const o=[];for(const r of e.cells)o.push(us(r,s));return new t({cells:o})}get trainableWeights(){if(!this.trainable)return[];const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.cells)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const s of this.cells)e.push(...s.trainableWeights);return e.concat(t)}return t}getWeights(){const t=[];for(const e of this.cells)t.push(...e.weights);return Oh(t)}setWeights(t){const e=[];for(const s of this.cells){const o=s.weights.length,r=t.splice(o);for(let i=0;ir!=null?r(t(),e):x0(t(),e),a=()=>Oi(i,t,s);return!o||o<=1?en(a().clone()):Array(o).fill(void 0).map(a).map(l=>en(l.clone()))}/** + * @license + * Copyright 2020 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */var xG=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(n);o{if(this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),e&&e.constants)throw new $("ConvRNN2D cell does not support constants");const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}computeOutputShape(t){let e=this.computeSingleOutputShape(t);return this.returnSequences||(e=[e[0],...e.slice(2)]),this.returnState&&(e=[e,...Array(2).fill([t[0],...e.slice(-3)])]),e}getInitialState(t){return M(()=>{const{stateSize:e}=this.cell,s=t.shape,o=this.computeSingleOutputShape(s),r=[o[0],...o.slice(2)],i=ge(r);return Array.isArray(e)?Array(e.length).fill(i):[i]})}resetStates(t,e=!1){M(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,o=this.computeSingleOutputShape(s),r=[o[0],...o.slice(2)];if(s[0]==null)throw new $("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ge(r)):this.states_=[ge(r)];else if(t==null)vt(this.states_),this.keptStates!=null&&(vt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ge(r)):this.states_[0]=ge(r);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new $(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e?this.keptStates.push(this.states_.slice()):vt(this.states_);for(let a=0;aen(a.clone()))})}computeSingleOutputShape(t){const{dataFormat:e,filters:s,kernelSize:o,padding:r,strides:i,dilationRate:a}=this.cell,c=e==="channelsFirst",l=t[c?3:2],u=t[c?4:3],d=Wn(l,o[0],r,i[0],a[0]),h=Wn(u,o[1],r,i[1],a[1]);return[...t.slice(0,2),...c?[s,d,h]:[d,h,s]]}}Kb.className="ConvRNN2D";class ap extends ul{constructor(t){const{filters:e,kernelSize:s,strides:o,padding:r,dataFormat:i,dilationRate:a}=t;super(Object.assign(Object.assign({},t),{units:e})),this.filters=e,be(this.filters,"filters"),this.kernelSize=or(s,2,"kernelSize"),this.kernelSize.forEach(c=>be(c,"kernelSize")),this.strides=or(o||1,2,"strides"),this.strides.forEach(c=>be(c,"strides")),this.padding=r||"valid",rn(this.padding),this.dataFormat=i||"channelsLast",se(this.dataFormat),this.dilationRate=or(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>be(c,"dilationRate"))}build(t){var e;t=Nt(t);const s=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[s]==null)throw new $(`The channel dimension of the input should be defined. Found ${t[s]}`);const o=t[s],r=4,i=this.kernelSize.concat([o,this.filters*r]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let c;if(this.unitForgetBias){const l=this.biasInitializer,u=this.filters;c=new(e=class extends xn{apply(h,p){const f=l.apply([u]),m=Ss([u]),g=l.apply([u*2]);return Lh([f,m,g])}},e.className="CustomInit",e)}else c=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,c,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(t,e){return M(()=>{if(t.length!==3)throw new $(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);const s=e.training||!1,o=t[0],r=t[1],i=t[2],a=4;0fn(o),rate:this.dropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const c=this.dropoutMask,l=(U,Y,j)=>!Y||!Y[j]?U:E(Y[j],U);let u=l(o,c,0),d=l(o,c,1),h=l(o,c,2),p=l(o,c,3);0fn(r),rate:this.recurrentDropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const f=this.recurrentDropoutMask;let m=l(r,f,0),g=l(r,f,1),b=l(r,f,2),x=l(r,f,3);const I=3,[y,w,C,k]=on(this.kernel.read(),a,I),[S,T,R,L]=this.useBias?on(this.bias.read(),a):[null,null,null,null];u=this.inputConv(u,y,S,this.padding),d=this.inputConv(d,w,T,this.padding),h=this.inputConv(h,C,R,this.padding),p=this.inputConv(p,k,L,this.padding);const[V,F,X,A]=on(this.recurrentKernel.read(),a,I);m=this.recurrentConv(m,V),g=this.recurrentConv(g,F),b=this.recurrentConv(b,X),x=this.recurrentConv(x,A);const P=this.recurrentActivation.apply(Q(u,m)),B=this.recurrentActivation.apply(Q(d,g)),K=Q(E(B,i),E(P,this.activation.apply(Q(h,b)))),H=E(this.recurrentActivation.apply(Q(p,x)),this.activation.apply(K));return[H,H,K]})}getConfig(){const t=super.getConfig(),e=xG(t,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},e),s)}inputConv(t,e,s,o){const r=so(t,e,this.strides,o||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?Ln(r,s,this.dataFormat):r}recurrentConv(t,e){return so(t,e,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}ap.className="ConvLSTM2DCell",_(ap);class Zb extends Kb{constructor(t){const e=new ap(t);super(Object.assign(Object.assign({},t),{cell:e}))}static fromConfig(t,e){return new t(e)}}Zb.className="ConvLSTM2D",_(Zb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class cp extends Ct{constructor(t){super(t),this.rate=Math.max(Math.min(t.rate,1),0),this.noiseShape=t.noiseShape,this.seed=t.seed,this.supportsMasking=!0}getNoiseShape(t){if(this.noiseShape==null)return this.noiseShape;const e=t.shape,s=[];for(let o=0;o{this.invokeCallHook(t,e);const s=mt(t);if(0x0(s,this.rate,r,this.seed),()=>s,o)}return t})}getConfig(){const t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},e=super.getConfig();return Object.assign(t,e),t}dispose(){return super.dispose()}}cp.className="Dropout",_(cp);class Bb extends cp{constructor(t){super(t),this.inputSpec=[{ndim:3}]}getNoiseShape(t){const e=t.shape;return[e[0],1,e[2]]}}Bb.className="SpatialDropout1D",_(Bb);class Hb extends Ct{constructor(t){if(super(t),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.batchInputShape==null&&t.inputShape==null&&t.inputDim!=null){let e=null;t.batchSize!=null&&(e=t.batchSize),this.batchInputShape=[e,t.inputDim]}this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation),t.useBias!=null&&(this.useBias=t.useBias),this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=he(t.kernelConstraint),this.biasConstraint=he(t.biasConstraint),this.kernelRegularizer=_t(t.kernelRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(t){t=Nt(t);const e=t[t.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[e,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:e}}],this.built=!0}computeOutputShape(t){t=Nt(t);const e=t.slice();return e[e.length-1]=this.units,e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t),o=l0(this.activation.getClassName());let r;return o!=null?r=_n(s,this.kernel.read(),o,this.bias?this.bias.read():null):(r=_n(s,this.kernel.read()),this.bias!=null&&(r=Ln(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){const t={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),biasInitializer:Qt(this.biasInitializer),kernelRegularizer:Vt(this.kernelRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),biasConstraint:de(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}Hb.className="Dense",_(Hb);class _b extends Ct{constructor(t){t=t||{},super(t),this.inputSpec=[{minNDim:3}],this.dataFormat=t.dataFormat}computeOutputShape(t){t=Nt(t);for(const e of t.slice(1))if(e==null)throw new $(`The shape of the input to "Flatten" is not fully defined (got ${t.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[t[0],Ns(t,1)]}call(t,e){return M(()=>{this.invokeCallHook(t,e);let s=mt(t);if(this.dataFormat==="channelsFirst"&&s.rank>1){const o=[0];for(let r=2;r{this.invokeCallHook(t,e);const s=mt(t);return this.activation.apply(s)})}getConfig(){const t={activation:Gs(this.activation)},e=super.getConfig();return Object.assign(t,e),t}}Ub.className="Activation",_(Ub);class Yb extends Ct{constructor(t){super(t),this.n=t.n,this.inputSpec=[{ndim:2}]}computeOutputShape(t){return[t[0],this.n,t[1]]}call(t,e){return M(()=>(t=mt(t),JR(t,this.n)))}getConfig(){const t={n:this.n},e=super.getConfig();return Object.assign(t,e),t}}Yb.className="RepeatVector",_(Yb);class Qb extends Ct{constructor(t){super(t),this.targetShape=t.targetShape;for(let e=0;e{this.invokeCallHook(t,e);const s=mt(t),o=s.shape,r=o.slice(0,1).concat(this.fixUnknownDimension(o.slice(1),this.targetShape));return W(s,r)})}getConfig(){const t={targetShape:this.targetShape},e=super.getConfig();return Object.assign(t,e),t}}Qb.className="Reshape",_(Qb);class Jb extends Ct{constructor(t){if(super(t),t.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(t.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${t.dims} instead.`);const e=$n(1,t.dims.length+1);if(!Rt(t.dims.slice().sort(),e))throw new Error("Invalid permutation `dims`: "+JSON.stringify(t.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=t.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new ue({ndim:this.dims.length+1})]}computeOutputShape(t){t=Nt(t);const e=t.slice();return this.dims.forEach((s,o)=>{e[o+1]=t[s]}),e}call(t,e){return kt(mt(t),this.dimsIncludingBatch)}getConfig(){const t={dims:this.dims},e=super.getConfig();return Object.assign(t,e),t}}Jb.className="Permute",_(Jb);class jb extends Ct{constructor(t){super(t??{}),this.supportsMasking=!0,t!=null?this.maskValue=t.maskValue==null?0:t.maskValue:this.maskValue=0}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={maskValue:this.maskValue};return Object.assign(e,t),e}computeMask(t,e){const s=mt(t);return ld(Mc(s,this.maskValue),-1)}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t),i=ld(Mc(s,this.maskValue),-1,!0);return E(s,st(i,s.dtype))})}}jb.className="Masking",_(jb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class qb extends Ct{constructor(t){if(super(t),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",t.batchInputShape==null&&t.inputShape==null){let e=null;t.batchSize!=null&&(e=t.batchSize),t.inputLength==null?this.batchInputShape=[e,null]:this.batchInputShape=[e].concat(Lt(t.inputLength))}this.inputDim=t.inputDim,be(this.inputDim,"inputDim"),this.outputDim=t.outputDim,be(this.outputDim,"outputDim"),this.embeddingsInitializer=Ht(t.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(t.embeddingsRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.embeddingsConstraint=he(t.embeddingsConstraint),this.maskZero=t.maskZero,this.supportsMasking=t.maskZero,this.inputLength=t.inputLength}build(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(t){}computeMask(t,e){return M(()=>this.maskZero?(t=mt(t),Mc(t,St(t))):null)}computeOutputShape(t){if(t=Nt(t),this.inputLength==null)return[...t,this.outputDim];const e=Lt(this.inputLength);if(e.length!==t.length-1)throw new $(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);{let s=0;for(let o=0;o{this.invokeCallHook(t,e);let s=mt(t);s.dtype!=="int32"&&(s=Hn(s,"int32"));const o=b0(this.embeddings.read(),W(s,[s.size]));return W(o,Nt(this.computeOutputShape(s.shape)))})}getConfig(){const t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Qt(this.embeddingsInitializer),embeddingsRegularizer:Vt(this.embeddingsRegularizer),activityRegularizer:Vt(this.activityRegularizer),embeddingsConstraint:de(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},e=super.getConfig();return Object.assign(t,e),t}}qb.className="Embedding",_(qb);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class xo extends Ct{constructor(t){super(t||{}),this.supportsMasking=!0}mergeFunction(t){throw new bt}computeElementwiseOpOutputShape(t,e){if(t==null||e==null)return null;if(t.length1)throw new $(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);let s=t[0]==null?null:t[0].slice(1);for(let r=1;rr.length);t.indexOf(null)===-1&&Ts(o).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(t,e){return M(()=>{if(t=t,this.reshapeRequired){const s=[],o=t.map(r=>r.rank);if(o.indexOf(null)===-1){const r=Rs(o);for(let i of t){const a=i.rank;for(let c=0;c1){const u=$n(1,l).concat([0]);s.push(kt(c,u)),r=!0}else s.push(c)}let i=this.mergeFunction(s);const a=i.rank;if(r){if(a==null){const c=i.shape,l=c.length,u=c[l-1],d=[u].concat(c.slice(0,c.length-1));i=W(kt(W(i,[-1,u]),[1,0]),d)}else if(a>1){const c=[a-1].concat($n(0,a-1));i=kt(i,c)}}return i}}else return this.mergeFunction(t)})}computeOutputShape(t){t=t;let e;t[0]==null?e=null:e=t[0].slice(1);for(let o=1;o{if(e==null)return null;if(!Array.isArray(e))throw new $("`mask` should be an Array");if(!Array.isArray(t))throw new $("`inputs` should be an Array");if(e.length!==t.length)throw new $(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${t.length} vs ${e.length})`);if(e.every(o=>o==null))return null;e=e.map(o=>o==null?o:Ae(o,0));let s=e[0];for(let o=1;o{let e=t[0].clone();for(let s=1;s{let e=t[0].clone();for(let s=1;s{let e=t[0].clone();for(let s=1;s{let e=t[0];for(let s=1;s{let e=t[0];for(let s=1;s1)throw new $("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}mergeFunction(t){return M(()=>Lh(t,this.axis))}computeOutputShape(t){if(!(Array.isArray(t)&&Array.isArray(t[0])))throw new $("A `Concatenate` layer should be called on a list of inputs.");const e=t,s=e[0].slice(),o=this.axis<0?s.length+this.axis:this.axis;for(const r of e.slice(1)){if(s[o]==null||r[o]==null){s[o]=null;break}s[o]+=r[o]}return s}computeMask(t,e){if(e==null)return null;if(!Array.isArray(e))throw new $("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new $("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new $(`Mismatch in the length of mask (${e.length}) and the legnth of inputs (${t.length})`);return M(()=>{let s=!0;if(e.forEach(i=>{if(i!=null){s=!1;return}}),s)return null;const o=[];for(let i=0;i3||t.shape.length>3)throw new bt("batchDot is not implemented for tensors of 4D or higher rank yet");if(v(n.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`),v(n.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof e=="number"&&(e=[e,e]),n.dtype==="complex64"||t.dtype==="complex64")throw new bt("batchDot is not implemented for complex64-type Tensors yet.");const s=n.shape.length,o=t.shape.length;e==null&&(e=[s-1,o-2]);const r=e;return M(()=>{let i;if(s>o){i=s-o;const c=[];for(let l=0;ls){i=o-s;const c=[];for(let l=0;l0){let c;s>o?c=s+o-3:c=s-1;const l=[];for(let u=c;u"A `Dot` layer should be called on a list of exactly 2 inputs.");const e=t[0],s=t[1];if(e.length>3||s.length>3)throw new bt("Dot layer does not support tensors of 4D or higher rank yet.");const o=this.interpretAxes(e,s);if(e[o[0]]!==s[o[1]])throw new $(`Dimension incompatibility: ${e[o[0]]} !== ${s[o[1]]}`)}mergeFunction(t){if(t.length!==2)throw new $(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${t.length} input(s).`);let e=t[0],s=t[1],o;return Array.isArray(this.axes)?o=this.axes.map((r,i)=>ji(r,t[i].shape.length)):o=[ji(this.axes,e.shape.length),ji(this.axes,s.shape.length)],this.normalize&&(e=qc(e,o[0]),s=qc(s,o[1])),yG(e,s,o)}interpretAxes(t,e){let s;return Array.isArray(this.axes)?s=this.axes:s=[ji(this.axes,t.length),ji(this.axes,e.length)],s}computeOutputShape(t){v(Array.isArray(t)&&t.length===2&&Array.isArray(t[0])&&Array.isArray(t[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const e=t[0].slice(),s=t[1].slice();if(e.length>3||s.length>3)throw new bt("Dot layer does not support tensors of 4D or higher rank yet.");const o=this.interpretAxes(e,s);e.splice(o[0],1),s.splice(o[1],1),s.splice(0,1);const r=e.concat(s);return r.length===1&&r.push(1),r}computeMask(t,e){return null}getConfig(){const t={axes:this.axes,normalize:this.normalize},e=super.getConfig();return Object.assign(t,e),t}}ix.className="Dot",_(ix);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ax extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.stddev=t.stddev}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={stddev:this.stddev};return Object.assign(e,t),e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);return Oi(()=>Q(_c(s.shape,0,this.stddev),s),()=>s,e.training||!1)})}}ax.className="GaussianNoise",_(ax);class cx extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);return this.rate>0&&this.rate<1?Oi(()=>{const r=Math.sqrt(this.rate/(1-this.rate));return E(s,_c(s.shape,1,r))},()=>s,e.training||!1):s})}}cx.className="GaussianDropout",_(cx);class lx extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate,this.noiseShape=t.noiseShape}_getNoiseShape(t){return this.noiseShape||mt(t).shape}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return M(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(t);return Oi(()=>{const r=mt(t),c=-1.6732632423543772*1.0507009873554805;let l=oo(Li(s),this.rate);l=Hn(l,"float32");const u=((1-this.rate)*(1+this.rate*c**2))**-.5,d=-u*c*this.rate,h=Q(E(r,l),E(Q(l,-1),c));return Q(E(h,u),d)},()=>mt(t),e.training||!1)}return t})}}lx.className="AlphaDropout",_(lx);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function qi(n,t,e,s,o,r=.001){let i;if(n.rank===2)i=jC(n,t,e,s,o,r);else if(n.rank===3)i=t2(n,t,e,s,o,r);else if(n.rank===4)i=n2(n,t,e,s,o,r);else throw new bt(`batchNormalization is not implemented for array of rank ${n.rank} yet`);return i}function IG(n,t,e,s,o=.001){return M(()=>{const r=kd(n,s),i=r.mean,a=r.variance;return[qi(n,i,a,e,t,o),i,a]})}function wG(n,t,e,s,o=.001){return M(()=>{const r=kd(n,s),i=r.mean,a=r.variance,c=[];for(const f of $n(0,n.rank))s.indexOf(f)!==-1?c.push(1):c.push(n.shape[f]);const l=W(i,c),u=W(a,c),d=t==null?null:W(t,c),h=e==null?null:W(e,c);return[qi(n,l,u,h,d,o),i,a]})}function CG(n,t,e,s,o=.001){return Rt(s.slice().sort(),$n(0,n.rank-1))?IG(n,t,e,s,o):wG(n,t,e,s,o)}class ux extends Ct{constructor(t){t==null&&(t={}),super(t),this.supportsMasking=!0,this.axis=t.axis==null?-1:t.axis,this.momentum=t.momentum==null?.99:t.momentum,this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=Ht(t.betaInitializer||"zeros"),this.gammaInitializer=Ht(t.gammaInitializer||"ones"),this.movingMeanInitializer=Ht(t.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ht(t.movingVarianceInitializer||"ones"),this.betaConstraint=he(t.betaConstraint),this.gammaConstraint=he(t.gammaConstraint),this.betaRegularizer=_t(t.betaRegularizer),this.gammaRegularizer=_t(t.gammaRegularizer)}build(t){t=Nt(t);const e=this.axis>=0?this.axis:this.axis+t.length,s=t[e];if(s==null)throw new $(`Axis ${e} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(t)}.`);this.inputSpec=[new ue({ndim:t.length,axes:{[e]:s}})];const o=[s];this.scale&&(this.gamma=this.addWeight("gamma",o,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",o,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",o,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",o,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(t,e){return M(()=>{const s=e.training==null?!1:e.training,o=mt(t),r=o.shape,i=r.length,a=$n(0,i),c=this.axis>=0?this.axis:this.axis+i;a.splice(c,1);const l=ho(1,i);l[c]=r[c];const u=a.slice();u.sort();const d=!Rt(u,$n(0,i).slice(0,i-1)),h=()=>{if(d){const x=W(this.movingMean.read(),l),I=W(this.movingVariance.read(),l),y=this.center?W(this.beta.read(),l):null,w=this.scale?W(this.gamma.read(),l):null;return qi(o,x,I,y,w,this.epsilon)}else return qi(o,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return h();const[p,f,m]=CG(o,this.gamma.read(),this.beta.read(),a,this.epsilon),g=(x,I,y)=>{M(()=>{const w=1-y,C=x.read(),k=E(pt(C,I),w);x.write(pt(C,k))})};return(()=>{g(this.movingMean,f,this.momentum),g(this.movingVariance,m,this.momentum)})(),p})}getConfig(){const t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Qt(this.betaInitializer),gammaInitializer:Qt(this.gammaInitializer),movingMeanInitializer:Qt(this.movingMeanInitializer),movingVarianceInitializer:Qt(this.movingVarianceInitializer),betaRegularizer:Vt(this.betaRegularizer),gammaRegularizer:Vt(this.gammaRegularizer),betaConstraint:de(this.betaConstraint),gammaConstraint:de(this.gammaConstraint)},e=super.getConfig();return Object.assign(t,e),t}}ux.className="BatchNormalization",_(ux);class dx extends Ct{constructor(t){if(t==null&&(t={}),super(t),this.axis=t.axis==null?-1:t.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=Ht(t.betaInitializer||"zeros"),this.gammaInitializer=Ht(t.gammaInitializer||"ones"),this.betaRegularizer=_t(t.betaRegularizer),this.gammaRegularizer=_t(t.gammaRegularizer),this.supportsMasking=!0}build(t){t=Nt(t);const e=t.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=e)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Ts(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(r=>t[r]),o=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,o):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,o):this.beta=null,this.built=!0}call(t,e){const s=mt(t),o=s.shape,r=o.length;return M(()=>{let{mean:a,variance:c}=kd(s,this.axis,!0);const l=ho(1,r);for(const m of this.axis)l[m]=o[m];const u=m=>m!=null&&m.shape.length!==r?W(m,l):m;let d=this.scale?u(this.gamma.read()):null,h=this.center?u(this.beta.read()):null;const p=[],f=[];for(let m=0;m{if(n.rank!==4)throw new $(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new $("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(e==null&&(e=Gn()),e!=="channelsLast"&&e!=="channelsFirst")throw new $(`Unknown data format: ${e}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return e==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],Td(n,s)})}class hx extends Ct{constructor(t){if(t==null&&(t={}),super(t),this.dataFormat=t.dataFormat==null?Gn():t.dataFormat,t.padding==null)this.padding=[[1,1],[1,1]];else if(typeof t.padding=="number")this.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,t.padding.length!==2)throw new $(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${t.padding.length} array.`);let e,s;if(typeof t.padding[0]=="number")e=[t.padding[0],t.padding[0]],s=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,t.padding[0].length!==2)throw new $(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${t.padding[0].length} array.`);if(e=t.padding[0],t.padding[1].length!==2)throw new $(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${t.padding[1].length} array.`);s=t.padding[1]}this.padding=[e,s]}this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){t=Nt(t);let e,s;return this.dataFormat==="channelsFirst"?(t[2]!=null&&t[2]>=0?e=t[2]+this.padding[0][0]+this.padding[0][1]:e=null,t[3]!=null&&t[3]>=0?s=t[3]+this.padding[1][0]+this.padding[1][1]:s=null,[t[0],t[1],e,s]):(t[1]!=null&&t[1]>=0?e=t[1]+this.padding[0][0]+this.padding[0][1]:e=null,t[2]!=null&&t[2]>=0?s=t[2]+this.padding[1][0]+this.padding[1][1]:s=null,[t[0],e,s,t[3]])}call(t,e){return M(()=>vG(mt(t),this.padding,this.dataFormat))}getConfig(){const t={padding:this.padding,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}hx.className="ZeroPadding2D",_(hx);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function dl(n,t,e,s,o,r){return M(()=>{se(o),d0(r),rn(s),e==null&&(e=[1,1]),s==null&&(s="valid"),o==null&&(o=Gn()),r==null&&(r="max"),n=sp(n,o);let i;const a=s==="same"?"same":"valid";return r==="max"?i=Sd(n,t,e,a):i=hd(n,t,e,a),o==="channelsFirst"&&(i=kt(i,[0,3,1,2])),i})}function px(n,t,e,s,o,r){return M(()=>{se(o),d0(r),rn(s),e==null&&(e=[1,1,1]),s==null&&(s="valid"),o==null&&(o=Gn()),r==null&&(r="max"),n=$b(n,o);let i;const a=s==="same"?"same":"valid";return r==="max"?i=Pv(n,t,e,a):i=OC(n,t,e,a),o==="channelsFirst"&&(i=kt(i,[0,4,1,2,3])),i})}class fx extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=2),super(t),typeof t.poolSize=="number")this.poolSize=[t.poolSize];else if(Array.isArray(t.poolSize)&&t.poolSize.length===1&&typeof t.poolSize[0]=="number")this.poolSize=t.poolSize;else throw new $(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);if(be(this.poolSize,"poolSize"),t.strides==null)this.strides=this.poolSize;else if(typeof t.strides=="number")this.strides=[t.strides];else if(Array.isArray(t.strides)&&t.strides.length===1&&typeof t.strides[0]=="number")this.strides=t.strides;else throw new $(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,rn(this.padding),this.inputSpec=[new ue({ndim:3})]}computeOutputShape(t){t=Nt(t);const e=Wn(t[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]}call(t,e){return M(()=>{this.invokeCallHook(t,e),t=Ai(mt(t),2);const s=this.poolingFunction(mt(t),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Di(s,[2])})}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},e=super.getConfig();return Object.assign(t,e),t}}class mx extends fx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"max")}}mx.className="MaxPooling1D",_(mx);class gx extends fx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"avg")}}gx.className="AveragePooling1D",_(gx);class bx extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==2)throw new $(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides];be(this.poolSize,"poolSize"),be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),rn(this.padding),this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){t=Nt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2];return e=Wn(e,this.poolSize[0],this.padding,this.strides[0]),s=Wn(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,s]:[t[0],e,s,t[3]]}call(t,e){return M(()=>(this.invokeCallHook(t,e),this.poolingFunction(mt(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class xx extends bx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"max")}}xx.className="MaxPooling2D",_(xx);class yx extends bx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"avg")}}yx.className="AveragePooling2D",_(yx);class Ix extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==3)throw new $(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides,t.strides];be(this.poolSize,"poolSize"),be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),rn(this.padding),this.inputSpec=[new ue({ndim:5})]}computeOutputShape(t){t=Nt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[4]:t[3];return e=Wn(e,this.poolSize[0],this.padding,this.strides[0]),s=Wn(s,this.poolSize[1],this.padding,this.strides[1]),o=Wn(o,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,s,o]:[t[0],e,s,o,t[4]]}call(t,e){return M(()=>(this.invokeCallHook(t,e),this.poolingFunction(mt(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class wx extends Ix{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),px(t,e,s,o,r,"max")}}wx.className="MaxPooling3D",_(wx);class Cx extends Ix{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),px(t,e,s,o,r,"avg")}}Cx.className="AveragePooling3D",_(Cx);class vx extends Ct{constructor(t){super(t),this.inputSpec=[new ue({ndim:3})]}computeOutputShape(t){return[t[0],t[2]]}call(t,e){throw new bt}}class Sx extends vx{constructor(t){super(t||{})}call(t,e){return M(()=>{const s=mt(t);return ie(s,1)})}}Sx.className="GlobalAveragePooling1D",_(Sx);class kx extends vx{constructor(t){super(t||{})}call(t,e){return M(()=>{const s=mt(t);return Tn(s,1)})}}kx.className="GlobalMaxPooling1D",_(kx);class Tx extends Ct{constructor(t){super(t),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){return t=t,this.dataFormat==="channelsLast"?[t[0],t[3]]:[t[0],t[1]]}call(t,e){throw new bt}getConfig(){const t={dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class Nx extends Tx{call(t,e){return M(()=>{const s=mt(t);return this.dataFormat==="channelsLast"?ie(s,[1,2]):ie(s,[2,3])})}}Nx.className="GlobalAveragePooling2D",_(Nx);class Rx extends Tx{call(t,e){return M(()=>{const s=mt(t);return this.dataFormat==="channelsLast"?Tn(s,[1,2]):Tn(s,[2,3])})}}Rx.className="GlobalMaxPooling2D",_(Rx);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class $x extends Ct{constructor(t){super(t),this.layer=t.layer}build(t){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(t){this.layer!=null&&(this.layer.trainable=t)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(t){this.layer.setWeights(t)}getConfig(){const t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},e=super.getConfig();return Object.assign(t,e),t}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(t)}static fromConfig(t,e,s={}){const o=e.layer,r=us(o,s);delete e.layer;const i={layer:r};return Object.assign(i,e),new t(i)}}class Gx extends $x{constructor(t){super(t),this.supportsMasking=!0}build(t){if(t=Nt(t),t.length<3)throw new $(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(t)}`);this.inputSpec=[{shape:t}];const e=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(e),this.layer.built=!0),super.build(t)}computeOutputShape(t){t=Nt(t);const e=[t[0]].concat(t.slice(2)),s=this.layer.computeOutputShape(e),o=t[1];return[s[0],o].concat(s.slice(1))}call(t,e){return M(()=>(t=mt(t),Xb((i,a)=>[mt(this.layer.call(i,e)),[]],t,[],!1,null,null,!1,!0)[1]))}}Gx.className="TimeDistributed",_(Gx);function SG(n){fo(HR,"BidirectionalMergeMode",n)}const kG="concat";class Lx extends $x{constructor(t){super(t);const e=t.layer.getConfig(),s={};s.className=t.layer.getClassName(),s.config=e,this.forwardLayer=us(s),e.goBackwards=e.goBackwards!==!0;const o={};if(o.className=t.layer.getClassName(),o.config=e,this.backwardLayer=us(o),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=t.mergeMode===void 0?kG:t.mergeMode,SG(this.mergeMode),t.weights)throw new bt("weights support is not implemented for Bidirectional layer yet.");this._stateful=t.layer.stateful,this.returnSequences=t.layer.returnSequences,this.returnState=t.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=t.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(t){this._trainable=t,this.forwardLayer!=null&&(this.forwardLayer.trainable=t),this.backwardLayer!=null&&(this.backwardLayer.trainable=t)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(t){const e=t.length,s=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,s)),this.backwardLayer.setWeights(t.slice(s))}computeOutputShape(t){let e=this.forwardLayer.computeOutputShape(t);Array.isArray(e)&&Array.isArray(e[0])||(e=[e]),e=e;let s,o,r;return this.returnState&&(r=e.slice(1)),s=e[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,o=[s]):this.mergeMode==null?o=[s,s.slice()]:o=[s],this.returnState?this.mergeMode==null?o.concat(r).concat(r.slice()):[s].concat(r).concat(r.slice()):Pe(o)}apply(t,e){let s=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});const r=zb(t,s,o,this.numConstants);if(t=r.inputs,s=r.initialState,o=r.constants,Array.isArray(t)&&(s=t.slice(1),t=t[0]),(s==null||s.length===0)&&o==null)return super.apply(t,e);const i=[],a=[];if(s!=null){const l=s.length;if(l%2>0)throw new $("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");e.initialState=s,i.push(...s);const u=s.map(d=>new ue({shape:d.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),a.push(...u)}if(o!=null)throw new bt("Support for constants in Bidirectional layers is not implemented yet.");const c=i[0]instanceof Un;for(const l of i)if(l instanceof Un!==c)throw new $("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){const l=[t].concat(i),u=this.inputSpec.concat(a),d=this.inputSpec;this.inputSpec=u;const h=super.apply(l,e);return this.inputSpec=d,h}else return super.apply(t,e)}call(t,e){return M(()=>{const s=e.initialState;let o,r;if(s==null)o=this.forwardLayer.call(t,e),r=this.backwardLayer.call(t,e);else{const c=s.slice(0,s.length/2),l=s.slice(s.length/2);o=this.forwardLayer.call(t,Object.assign(e,{initialState:c})),r=this.backwardLayer.call(t,Object.assign(e,{initialState:l}))}let i;this.returnState&&(Array.isArray(o)&&(i=o.slice(1).concat(r.slice(1))),o=o[0],r=r[0]),this.returnSequences&&(r=ao(r,1));let a;return this.mergeMode==="concat"?a=Lh([o,r]):this.mergeMode==="sum"?a=Q(o,r):this.mergeMode==="ave"?a=E(.5,Q(o,r)):this.mergeMode==="mul"?a=E(o,r):this.mergeMode==null&&(a=[o,r]),this.returnState?this.mergeMode==null?a.concat(i):[a].concat(i):a})}resetStates(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(t){mo(this.forwardLayer.name,()=>{this.forwardLayer.build(t)}),mo(this.backwardLayer.name,()=>{this.backwardLayer.build(t)}),this.built=!0}computeMask(t,e){Array.isArray(e)&&(e=e[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[e,e]:s=e:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const r=this.forwardLayer.states.map(i=>null);return Array.isArray(s)?s.concat(r).concat(r):[s].concat(r).concat(r)}else return s}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(t),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(t)}getConfig(){const t={mergeMode:this.mergeMode},e=super.getConfig();return Object.assign(t,e),t}static fromConfig(t,e){const s=us(e.layer);if(delete e.layer,e.numConstants!=null)throw new bt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const o=e;return o.layer=s,new t(o)}}Lx.className="Bidirectional",_(Lx);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Ex extends Ct{constructor(t){super(t),this.scale=t.scale,t.offset?this.offset=t.offset:this.offset=0}getConfig(){const t={scale:this.scale,offset:this.offset},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return M(()=>(t=mt(t),t.dtype!=="float32"&&(t=Hn(t,"float32")),Q(E(t,this.scale),this.offset)))}}Ex.className="Rescaling",_(Ex);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const{resizeBilinear:TG,cropAndResize:NG}=is;class Dx extends Ct{constructor(t){super(t),this.height=t.height,this.width=t.width}centerCrop(t,e,s,o,r,i,a,c){return M(()=>{let l,u=!1;const d=e/i,h=s/a,p=(o+e)/i,f=(r+s)/a,m=[d,h,p,f],g=[];t.rank===3?(u=!0,l=On([t])):l=t;for(let w=0;w{const r=TG(t,[e,s]);return Hn(r,o)})}call(t,e){return M(()=>{const s=mt(t),o=s.dtype,r=s.shape,i=r[r.length-3],a=r[r.length-2];let c=0;i!==this.height&&(c=Math.floor((i-this.height)/2));let l=0;return a!==this.width&&(l=Math.floor((a-this.width)/2),l===0&&(l=1)),c>=0&&l>=0?this.centerCrop(s,c,l,this.height,this.width,i,a,o):this.upsize(t,this.height,this.width,o)})}getConfig(){const t={height:this.height,width:this.width},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){t=Nt(t);const e=t.length-3,s=t.length-2;return t[e]=this.height,t[s]=this.width,t}}Dx.className="CenterCrop",_(Dx);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function RG(n,t,e,s){let o=mt(n);if(o.dtype!=="int32"&&(o=Hn(o,"int32")),t==="int")return o;const r=o.shape;if(o.rank===0&&(o=Ae(o,-1)),t==="oneHot"&&o.shape[o.shape.length-1]!==1&&(o=Ae(o,-1)),o.rank>2)throw new $(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${r} which would result in output rank ${o.rank}.`);const i=["multiHot","oneHot"].includes(t),a=o;let c;if(typeof s<"u"&&t==="count"?c=Vm(a,s,e,i):c=Vm(a,[],e,i),t!=="tfIdf")return c;if(s)return E(c,s);throw new $("When outputMode is 'tfIdf', weights must be provided.")}/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Wx extends Ct{constructor(t){super(t),this.numTokens=t.numTokens,t.outputMode?this.outputMode=t.outputMode:this.outputMode="multiHot"}getConfig(){const t={numTokens:this.numTokens,outputMode:this.outputMode},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){return t=Nt(t),t==null?[this.numTokens]:this.outputMode==="oneHot"&&t[t.length-1]!==1?(t.push(this.numTokens),t):(t[t.length-1]=this.numTokens,t)}call(t,e){return M(()=>{t=mt(t),t.dtype!=="int32"&&(t=Hn(t,"int32"));let s;if(typeof e.countWeights<"u"){if(this.outputMode!=="count")throw new $(`countWeights is not used when outputMode !== count. + Received countWeights=${e.countWeights}`);s=mt(e.countWeights)}const o=Tn(t),r=Lc(t),i=sn(this.numTokens,o).bufferSync().get(0),a=oo(r,0).bufferSync().get(0);if(!(i&&a))throw new $(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return RG(t,this.outputMode,this.numTokens,s)})}}Wx.className="CategoryEncoding",_(Wx);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const $G=["bilinear","nearest"],Mx=new Set($G);class Vx extends Ct{constructor(t){if(super(t),this.height=t.height,this.width=t.width,t.interpolation)if(Mx.has(t.interpolation))this.interpolation=t.interpolation;else throw new $(`Invalid interpolation parameter: ${t.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!t.cropToAspectRatio}computeOutputShape(t){t=Nt(t);const e=t[2];return[this.height,this.width,e]}getConfig(){const t={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return M(()=>{const s=[this.height,this.width];if(this.interpolation==="bilinear")return is.resizeBilinear(t,s,!this.cropToAspectRatio);if(this.interpolation==="nearest")return is.resizeNearestNeighbor(t,s,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Mx]} are supported`)})}}Vx.className="Resizing",_(Vx);/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Fx{constructor(t){this.seed=t}next(){if(this.seed!==void 0)return this.seed++}}Fx.className="RandomSeed";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class zx extends Ct{constructor(t){super(t),this.randomGenerator=new Fx(t.seed)}getConfig(){const t={seed:this.randomGenerator.seed},e=super.getConfig();return Object.assign(t,e),t}}zx.className="BaseRandomLayer";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const GG=["bilinear","nearest"],Xx=new Set(GG);class Ax extends zx{constructor(t){super(t);const{factor:e,interpolation:s="bilinear"}=t;if(this.factor=e,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new $(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new $(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper{const s=mt(t);this.imgHeight=s.shape[s.shape.length-3];const o=s.shape[s.shape.length-2];this.widthFactor=Li([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*o;r=Math.round(r);const i=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return is.resizeBilinear(t,i);case"nearest":return is.resizeNearestNeighbor(t,i);default:throw new Error(`Interpolation is ${this.interpolation} + but only ${[...Xx]} are supported`)}})}}Ax.className="RandomWidth",_(Ax);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */z().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var Px;(function(n){n[n.DT_INVALID=0]="DT_INVALID",n[n.DT_FLOAT=1]="DT_FLOAT",n[n.DT_DOUBLE=2]="DT_DOUBLE",n[n.DT_INT32=3]="DT_INT32",n[n.DT_UINT8=4]="DT_UINT8",n[n.DT_INT16=5]="DT_INT16",n[n.DT_INT8=6]="DT_INT8",n[n.DT_STRING=7]="DT_STRING",n[n.DT_COMPLEX64=8]="DT_COMPLEX64",n[n.DT_INT64=9]="DT_INT64",n[n.DT_BOOL=10]="DT_BOOL",n[n.DT_QINT8=11]="DT_QINT8",n[n.DT_QUINT8=12]="DT_QUINT8",n[n.DT_QINT32=13]="DT_QINT32",n[n.DT_BFLOAT16=14]="DT_BFLOAT16",n[n.DT_QINT16=15]="DT_QINT16",n[n.DT_QUINT16=16]="DT_QUINT16",n[n.DT_UINT16=17]="DT_UINT16",n[n.DT_COMPLEX128=18]="DT_COMPLEX128",n[n.DT_HALF=19]="DT_HALF",n[n.DT_RESOURCE=20]="DT_RESOURCE",n[n.DT_VARIANT=21]="DT_VARIANT",n[n.DT_UINT32=22]="DT_UINT32",n[n.DT_UINT64=23]="DT_UINT64",n[n.DT_FLOAT_REF=101]="DT_FLOAT_REF",n[n.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",n[n.DT_INT32_REF=103]="DT_INT32_REF",n[n.DT_UINT8_REF=104]="DT_UINT8_REF",n[n.DT_INT16_REF=105]="DT_INT16_REF",n[n.DT_INT8_REF=106]="DT_INT8_REF",n[n.DT_STRING_REF=107]="DT_STRING_REF",n[n.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",n[n.DT_INT64_REF=109]="DT_INT64_REF",n[n.DT_BOOL_REF=110]="DT_BOOL_REF",n[n.DT_QINT8_REF=111]="DT_QINT8_REF",n[n.DT_QUINT8_REF=112]="DT_QUINT8_REF",n[n.DT_QINT32_REF=113]="DT_QINT32_REF",n[n.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",n[n.DT_QINT16_REF=115]="DT_QINT16_REF",n[n.DT_QUINT16_REF=116]="DT_QUINT16_REF",n[n.DT_UINT16_REF=117]="DT_UINT16_REF",n[n.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",n[n.DT_HALF_REF=119]="DT_HALF_REF",n[n.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",n[n.DT_VARIANT_REF=121]="DT_VARIANT_REF",n[n.DT_UINT32_REF=122]="DT_UINT32_REF",n[n.DT_UINT64_REF=123]="DT_UINT64_REF"})(Px||(Px={}));var Ox;(function(n){(function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))})(Ox||(Ox={}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var Kx;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(Kx||(Kx={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function it(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&v(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LG=rg;class hl extends Zl{nextDataId(){return hl.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new lf(this,zt())}write(t,e,s){this.firstUse&&(this.firstUse=!1,z().get("IS_NODE")&&je(` +============================ +Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. +============================`));const o={id:this.nextDataId()};return this.data.set(o,{values:t,dtype:s,refCount:1}),o}makeTensorInfo(t,e,s){let o;if(e==="string"&&s!=null&&s.length>0&&Cr(s[0])){const r=s.map(i=>bs(i));o=this.write(r,t,e)}else o=this.write(s,t,e);return{dataId:o,shape:t,dtype:e}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){const e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){const e=this.data.get(t);e.refCount--}}move(t,e,s,o,r){this.data.set(t,{values:e,dtype:o,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){const{dtype:e,complexTensorInfos:s}=this.data.get(t);if(e==="complex64"){const o=this.readSync(s.real.dataId),r=this.readSync(s.imag.dataId);return as(o,r)}return ow(this.data.get(t).values,e)}bufferSync(t){const e=this.readSync(t.dataId);if(t.dtype==="string")try{const s=e.map(o=>xs(o));return wt(t.shape,t.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}makeOutput(t,e,s){return zt().makeTensorFromTensorInfo(this.makeTensorInfo(e,s,t),this)}disposeData(t,e=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!e&&this.data.get(t).refCount>0)return!1;const{complexTensorInfos:s}=this.data.get(t);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){const e=Ve();return t(),{kernelMs:Ve()-e}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(t){it([t],"where");const e=this.readSync(t.dataId);return LG(t.shape,e)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}hl.nextDataId=0;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zx(n){const t=new Float32Array(n.length);for(let e=0;e{const{x:t}=n.inputs,e=n.backend;it(t,"abs");let s=new Float32Array(Z(t.shape));const o=e.data.get(t.dataId).values;return s=Zx(o),e.makeOutput(s,t.shape,t.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oe(n){return(t,e,s,o,r)=>{const i=gt(t,e),a=i.length,c=ct(i),l=Z(i),u=Se(r,l),d=t.length,h=e.length,p=ct(t),f=ct(e),m=Uo(t,i),g=Uo(e,i);if(m.length+g.length===0)for(let b=0;bI[k]=0);const y=Fn(I,d,p),w=x.slice(-h);g.forEach(k=>w[k]=0);const C=Fn(w,h,f);u[b]=n(s[y],o[C])}return[u,i]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qe(n){const{inputs:t,backend:e}=n,{real:s,imag:o}=t,r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,a=e.makeTensorInfo(s.shape,"complex64"),c=e.data.get(a.dataId);return c.complexTensorInfos={real:e.makeTensorInfo(s.shape,"float32",r),imag:e.makeTensorInfo(o.shape,"float32",i)},a}const DG={kernelName:lu,backendName:"cpu",kernelFunc:Qe};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pl(n,t,e="float32"){if(e==="complex64"){const o=pl(n,t,"float32"),r=pl(n,t,"float32");return Qe({inputs:{real:o,imag:r},backend:n})}const s=ke(Z(t),e);return n.makeTensorInfo(t,e,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qn(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const WG={kernelName:Kr,backendName:"cpu",kernelFunc:Qn};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yo(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.data.get(s.dataId).complexTensorInfos.real,r=e.data.get(o.dataId).values;return e.makeTensorInfo(o.shape,o.dtype,r)}const MG={kernelName:Mu,backendName:"cpu",kernelFunc:yo};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bx(n,t,e,s){if(s==="int32"){const o=Int32Array.from(n);return[t,"int32",o]}if(s==="bool"){const o=Ys([0],e),[r,i]=oe((a,c)=>a!==c?1:0)(t,[],n,o,"bool");return[i,"bool",r]}throw new Error(`Error in Cast: failed to cast ${e} to ${s}`)}function Ws(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dtype:r}=s;if(r==="complex64"){if(o.dtype==="complex64")return Qn({inputs:{x:o},backend:e});const u=pl(e,o.shape,o.dtype),d=Ws({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),h=Qe({inputs:{real:d,imag:u},backend:e});return e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(d),h}if(o.dtype==="complex64"){const u=yo({inputs:{input:o},backend:e}),d=Ws({inputs:{x:u},backend:e,attrs:{dtype:r}});return e.disposeIntermediateTensorInfo(u),d}if(!hf(o.dtype,r)){const u=Qn({inputs:{x:o},backend:e});return{dataId:u.dataId,shape:u.shape,dtype:r}}const i=e.data.get(o.dataId).values,[a,c,l]=Bx(i,o.shape,o.dtype,r);return e.makeTensorInfo(a,c,l)}const VG={kernelName:Gr,backendName:"cpu",kernelFunc:Ws};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pe(n,t,e,s){return e==null?({inputs:o,backend:r})=>{const{a:i,b:a}=o,c=r;it([i,a],n);const l=c.data.get(i.dataId).values,u=c.data.get(a.dataId).values,d=i.dtype==="string"?cs(l):l,h=i.dtype==="string"?cs(u):u,p=s||i.dtype,[f,m]=t(i.shape,a.shape,d,h,p);return c.makeTensorInfo(m,p,f)}:({inputs:o,backend:r})=>{const{a:i,b:a}=o,c=r;if(i.dtype==="complex64"||a.dtype==="complex64"){const l=Ws({inputs:{x:i},backend:c,attrs:{dtype:"complex64"}}),u=c.data.get(l.dataId),d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag,p=c.data.get(d.dataId).values,f=c.data.get(h.dataId).values,m=Ws({inputs:{x:a},backend:c,attrs:{dtype:"complex64"}}),g=c.data.get(m.dataId),b=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,I=c.data.get(b.dataId).values,y=c.data.get(x.dataId).values,[w,C,k]=e(i.shape,a.shape,p,f,I,y),S=c.makeTensorInfo(k,"float32",w),T=c.makeTensorInfo(k,"float32",C),R=Qe({inputs:{real:S,imag:T},backend:c});return c.disposeIntermediateTensorInfo(l),c.disposeIntermediateTensorInfo(m),c.disposeIntermediateTensorInfo(S),c.disposeIntermediateTensorInfo(T),R}else{const l=c.data.get(i.dataId).values,u=c.data.get(a.dataId).values,d=s||i.dtype,[h,p]=t(i.shape,a.shape,l,u,d);return c.makeTensorInfo(p,d,h)}}}function lp(n){return(t,e,s,o,r,i)=>{const a=gt(t,e),c=Z(a),l=a.length,u=ct(a),d=Se("float32",c),h=Se("float32",c),p=Uo(t,a),f=Uo(e,a),m=as(s,o),g=as(r,i),b=t.length,x=ct(t),I=e.length,y=ct(e);if(p.length+f.length===0)for(let w=0;wk[V]=0);const S=Fn(k,b,x),T=C.slice(-I);f.forEach(V=>T[V]=0);const R=Fn(T,I,y),L=n(m[S*2],m[S*2+1],g[R*2],g[R*2+1]);d[w]=L.real,h[w]=L.imag}return[d,h,a]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hx=oe((n,t)=>n+t),FG=lp((n,t,e,s)=>({real:n+e,imag:t+s})),ir=pe(Fo,Hx,FG),zG={kernelName:Fo,backendName:"cpu",kernelFunc:ir};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function up(n,t,e,s,o){const r=Z(s),i=ke(o,e);for(let a=0;a=o||(r>0?i[c]+=t[a]:i[c]+=1)}return i}function _x(n,t,e,s=!1){const o=n.shape[0],r=n.shape[1],i=wt([o,e],t.dtype);for(let a=0;a=e||(s?i.set(1,a,l):t.size>0?i.set(i.get(a,l)+t.get(a,c),a,l):i.set(i.get(a,l)+1,a,l))}return i}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ux=oe((n,t)=>n&t),XG=pe(cu,Ux),AG={kernelName:cu,backendName:"cpu",kernelFunc:XG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jn(n){return(t,e,s)=>{const o=qt(e,t.length);for(let r=0;r{const{x:i}=s;it(i,n);const a=r,c=a.data.get(i.dataId).values;let l;if(i.dtype==="string"){if(!Array.isArray(c))throw new Error("String tensor's value was not an instance of Array");l=cs(c)}else l=c;const u=e||i.dtype,d=t(l,u,o);return a.makeTensorInfo(i.shape,u,d)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yx=Jn(n=>Math.ceil(n)),PG=Ms(Lr,Yx),OG={kernelName:Lr,backendName:"cpu",kernelFunc:PG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qx(n,t,e,s){const o=qt(e,Z(t));if(s&&e!=="string"){let r=0;n.forEach(i=>{const a=Z(i.shape);o.set(i.vals,r),r+=a})}else{let r=0;n.forEach(i=>{const a=e==="string"?cs(i.vals):i.vals;let c=0;for(let l=0;ln===t?1:0),jx=pe(Wa,Jx,null,"bool"),KG={kernelName:Wa,backendName:"cpu",kernelFunc:jx};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qx=Jn(n=>Math.exp(n)),ty=Ms(zr,qx,"float32"),ZG={kernelName:zr,backendName:"cpu",kernelFunc:ty};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ey=Jn(n=>Math.expm1(n)),BG=Ms(Xr,ey),HG={kernelName:Xr,backendName:"cpu",kernelFunc:BG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ny=Jn(n=>Math.floor(n)),_G=Ms(Ar,ny),UG={kernelName:Ar,backendName:"cpu",kernelFunc:_G};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sy=oe((n,t)=>Math.floor(n/t)),YG=pe(Pr,sy,null,"int32"),QG={kernelName:Pr,backendName:"cpu",kernelFunc:YG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oy(n,t,e,s,o,r,i,a,c){const l=wt([s,r],e);for(let u=0;u=c/r)throw new Error(`Invalid indices: ${d} does not index into ${a}`);for(let p=0;pn>t?1:0),JG=pe(za,iy,null,"bool"),jG={kernelName:za,backendName:"cpu",kernelFunc:JG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ay=oe((n,t)=>n>=t?1:0),qG=pe(Or,ay,null,"bool"),tL={kernelName:Or,backendName:"cpu",kernelFunc:qG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cy=oe((n,t)=>nn<=t?1:0),sL=pe(Pa,ly,null,"bool"),oL={kernelName:Pa,backendName:"cpu",kernelFunc:sL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uy(n,t,e){const s=(t-n)/(e-1),o=ke(e,"float32");o[0]=n;for(let r=1;rMath.log(n)),rL=Ms(_r,dy),iL={kernelName:_r,backendName:"cpu",kernelFunc:rL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hy(n,t,e,s){const o=Se(s,Z(e));for(let r=0;ra)&&(a=l)}o[r]=a}return o}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const py=oe((n,t)=>Math.max(n,t)),aL=pe(Yr,py),cL={kernelName:Yr,backendName:"cpu",kernelFunc:aL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fy=oe((n,t)=>Math.min(n,t)),lL=pe(Qr,fy),uL={kernelName:Qr,backendName:"cpu",kernelFunc:lL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dp=oe((n,t)=>n*t),dL=lp((n,t,e,s)=>({real:n*e-t*s,imag:n*s+t*e})),fl=pe(jr,dp,dL),hL={kernelName:jr,backendName:"cpu",kernelFunc:fl};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function my(n,t,e){const s=gs(-1,e);return dp([],t,s,n,e)}function pL(n){const{inputs:t,backend:e}=n,{x:s}=t;it(s,"neg");const o=e.data.get(s.dataId).values,[r,i]=my(o,s.shape,s.dtype);return e.makeTensorInfo(i,s.dtype,r)}const fL={kernelName:ja,backendName:"cpu",kernelFunc:pL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gy=oe((n,t)=>n!==t?1:0),mL=pe(qa,gy,null,"bool"),gL={kernelName:qa,backendName:"cpu",kernelFunc:mL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hp(n,t,e,s,o){const r=t.length,i=Z(t),a=ct(t),c=ct(o),l=Se(e,Z(o));for(let u=0;ue.disposeIntermediateTensorInfo(x)),e.makeTensorInfo(b,g,f)}const yL={kernelName:rc,backendName:"cpu",kernelFunc:xL};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IL(n,t,e){n.forEach((s,o)=>{if(s<0||s>=e){const r=Vo(o,t.length,ct(t)).join(",");throw new Error(`indices[${r}] = ${s} is not in [0, ${e})`)}})}function wL(n,t){for(let e=0;eo)throw new Error("Ragged splits must not point past values");for(let r=1;rs[r])throw new Error("Ragged splits must be sorted in ascending order")}}function CL(n,t,e,s){const o=[];let r=0;const i=t.length-1+e.length,a=new Array(i).fill(null).map(()=>[0]);wL(e,s);let c=1;for(let l=0;l=0){const m=a[f],g=m[m.length-1]-p[u];for(let b=u;bo[i]=r)}return t}function xy(n,t){const e=n.slice(0,t);for(;e.length1)throw new Error("starts must be a scalar or vector");if(o.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");const a=t.length===0,c=o.length===0,l=i.length===0,u=[];a||u.push(t[0]),c||u.push(o[0]),l||u.push(i[0]);for(let g=1;g0&&xb)y=0;else if(y=Math.ceil(Math.abs((x-b)/I)),y>Iy)throw new Error(`Requires ((limit - start) / delta) <= ${Iy}`);h[g+1]=h[g]+y}const p=h[d],f=qt(e,p);let m=0;for(let g=0;gs&&(s=r)}return s}static getMaxWidthValueRowID(t){const e=t.length;if(e===0)return 0;let s=0,o=t[0],r=0;for(let i=1;i"Final length of result must be equal to firstDimension."),r}calculateOutputIndexRowSplit(t,e,s,o){const r=t.length,i=[];for(let a=0;a0&&i.length!==t[r-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,e,s,o){const r=t.length,i=[];if(r===0)return[];let a=0,c=t[0];if(c>=e.length)throw new Error(`Got currentValueRowId=${c}, which is not less than ${e.length}`);let l=e[c];i.push(l);for(let u=1;u=0&&(++a,a=e.length)throw new Error(`Got nextValueRowId=${d} which is not less than ${e.length}`);l=e[d]}i.push(l)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,e,s,o){const r=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case In.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,e,s,o);case In.ROW_SPLITS:if(r.length-1>e.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${e.length}`);return this.calculateOutputIndexRowSplit(r,e,s,o);default:throw new Error(`Unsupported partition type: ${In[i]}`)}}getFirstDimensionSize(){const t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");const e=this.rowPartitionTypes[0];switch(e){case In.FIRST_DIM_SIZE:return t[0];case In.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case In.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${In[e]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),s=this.calculateOutputSize(e),o=new Array(this.raggedRank+1);o[o.length-1]=1;for(let c=o.length-2;c>=0;--c)o[c]=o[c+1]*s[c+1];const r=vy(s,!1),i=qt(this.valuesDType,Z(r));if(o[0]*s[0]>0){let c=this.calculateFirstParentOutputIndex(e,o[0],s[0]);for(let l=1;l<=this.raggedRank;++l)c=this.calculateOutputIndex(l-1,c,o[l],s[l]);this.setOutput(this.raggedRank,c,i,r)}return[r,i]}setOutput(t,e,s,o){if(s.length===0)return;const r=this.values,i=s;let a=o.slice();a=a.slice(t+1);const c=Z(a),l=e.length;let u=this.defaultValue;if(u.length!==c&&u.length!==1){const f=this.defaultValueShape;M(()=>{const m=W(u,f);u=Ni(m,a).dataSync()})}let d=0,h=0,p=0;for(let f=0;f<=l;++f){let m=f=l){const g=s.length;m=Math.floor(g/c)}if(m>p)if(this.defaultValue.length===1)i.subarray(p*c,m*c).fill(this.defaultValue[0]),p=m;else for(;m>p;){const g=i.slice(p*c);Cy(g,u,c),++p}m<0?(d=f+1,h=p):(d=f,h=p,p=h+1)}}}function Cy(n,t,e){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}e.push(s)}return e}function Sy(n,t,e,s,o,r,i,a,c,l){return new ml(n,t,e,s,o,r,i,a,c,l).compute()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ky(n,t,e,s){const o=n===t,r=n1;if(o||r||i)return ke(0,s);const a=Math.abs(Math.ceil((t-n)/e)),c=ke(a,s);t1/Math.sqrt(n)),TL=Ms(oi,Ty),NL={kernelName:oi,backendName:"cpu",kernelFunc:TL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Io(n,t,e,s,o,r,i,a,c,l){const u=[s/o,o],d=n.values,h=t.values;if(s===0)return wt(e,t.dtype);const p=c instanceof xe?c:wt(u,t.dtype);typeof c=="string"||typeof c=="number"?p.values.fill(c):typeof c=="boolean"&&p.values.fill(+c);for(let f=0;f=s/o)throw new Error(`Invalid indices: ${m} does not index into ${e}`);for(let b=0;b1/(1+Math.exp(-n))),Ny=Et(li,n=>1/(1+Math.exp(-n))),$L={kernelName:li,backendName:"cpu",kernelFunc:Ny};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ry(n,t,e,s,o){const r=eh(s,t,e),i=Z(e),a=ct(s);if(r){const d=nh(t,a);return o==="string"?n.slice(d,d+i):n.subarray(d,d+i)}const c=o==="string"?cs(n):n,l=wt(s,o,c),u=wt(e,o);for(let d=0;df+t[m]);u.set(l.get(...p),...h)}return o==="string"?Jg(u.values):u.values}function wo(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,size:i}=s;it(o,"slice");const[a,c]=zc(o,r,i);qd(o,a,c);const l=e.data.get(o.dataId).values,u=Ry(l,a,c,o.shape,o.dtype);return e.makeTensorInfo(c,o.dtype,u)}const GL={kernelName:dc,backendName:"cpu",kernelFunc:wo};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $y(n,t,e,s,o,r,i){const a=t[0],c=r[0],l=new Array(c),u=new Array(a),d=t[1];if(c===0){if(a!==0)throw new Error(zg(a));const g=qt(e,0),b=qt(o,0);return[g,[0,d],b,l,u]}let h=!0,p=0;const f=new Array(c).fill(0);for(let g=0;g=c)throw new Error(Ag(g,b,c));++f[b],h=h&&b>=p,p=b}let m=!0;for(let g=0;g0&&(f[g]+=f[g-1])}if(m&&h){const g=n,b=s;for(let x=0;x0){p[h-1]=1;for(let g=h-2;g>=0;--g)p[g]=p[g+1]*s[g+1]}const f=[];if(a>0){f[a-1]=1;for(let g=a-2;g>=0;--g)f[g]=f[g+1]*c[g+1]}const m=qt(e,i*a);for(let g=0;g0?o[a-1]+1:0;if(d<0)throw new Error(vh());const h=t.slice();h[0]=d;const p=h.reduce((I,y)=>I*y,1),f=qt(e,p);if(a===0)return d>0&&f.fill(i),[f,h];if(d<=0)throw new Error(vh());let m=0,g=1,b=0,x=o[m];for(;;){let I=0;if(g=I)throw new Error(Hg())}if(x<0||x>=d)throw new Error(_g(x,d));x>b&&f.fill(i,b*l,x*l);for(let y=m;y=c[0])throw new Error(Ug(y,s[y],c[0]));for(let C=0;Ca)break}return bMath.sqrt(n)),EL=Et(di,n=>Math.sqrt(n)),DL={kernelName:di,backendName:"cpu",kernelFunc:EL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ly=oe((n,t)=>{const e=n-t;return e*e}),WL=pe(hi,Ly),ML={kernelName:hi,backendName:"cpu",kernelFunc:WL};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ey=Jn((n,t)=>{const{pattern:e,replaceGlobal:s,rewrite:o}=t;return n.replace(new RegExp(e,s?"g":""),o)}),VL=Ms(Xu,Ey),FL={kernelName:Xu,backendName:"cpu",kernelFunc:VL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dy(n,t,e,s){const o=wt(n,t.dtype);for(let r=0;r0?0:a-c);let p=0;p+=l*this.leftPad.length;for(let x=0;xx.forEach(I=>m[g++]=I);for(let x=0;x0){b(t[h+d-1]);for(let x=0;x0){let c=e[0];if(c!==0)throw new Error(`First split value must be 0, got ${c}`);for(let l=1;l=c;if(u=u&&e[l]<=s,!u)throw new Error(`Invalid split value ${e[l]}, must be in [${c}, ${s}]`);c=e[l]}if(c!==s)throw new Error(`Last split value must be data size. Expected ${s}, got ${c}`)}const r=o-1,i=qt("int32",o);if(s===0||o===0){const c=new Array(s);for(let l=0;l<=r;++l)i[l]=0;return[c,i]}i[0]=0;for(let c=1;c<=r;++c){const l=e[c]-e[c-1];let u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),i[c]=i[c-1]+u}const a=new Array(i[r]);for(let c=0;c{const h=e[c+1]-e[c],p=this.getNumNGrams(h,d);this.createNGrams(t,l,a,u,p,d),u+=p}),this.preserveShort&&u===i[c]){const d=e[c+1]-e[c];if(d===0)continue;const h=d+2*this.padWidth;this.createNGrams(t,l,a,u,1,h)}}return[a,i]}}function Wy(n,t,e,s,o,r,i,a){return new zL(e,s,o,r,i,a).compute(n,t)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XL(n,t,e,s){if(!n.length)return;if(t.length===0){for(let r=0;rn-t),AL=lp((n,t,e,s)=>({real:n-e,imag:t-s})),fp=pe(pi,Fy,AL),PL={kernelName:pi,backendName:"cpu",kernelFunc:fp};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zy(n,t){const e=new Array(n.rank);for(let o=0;o{const e=t.value-n.value;return e===0?n.index-t.index:e};function Xy(n,t,e=0,s=n.length-1){for(;s>e;){if(s-e>600){const a=s-e+1,c=t-e+1,l=Math.log(a),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(a-u)/a)*Math.sign(c-a/2),h=Math.max(e,Math.floor(t-c*u/a+d)),p=Math.min(s,Math.floor(t+(a-c)*u/a+d));Xy(n,t,h,p)}const o=n[t];let r=e,i=s;for(Eo(n,e,t),ta(n[s],o)>0&&Eo(n,e,s);r0;)i=i-1}ta(n[e],o)===0?Eo(n,e,i):(i=i+1,Eo(n,i,s)),i<=t&&(e=i+1),t<=i&&(s=i-1)}}function Ay(n,t,e,s,o){const r=t[t.length-1],[i,a]=[n.length/r,r],c=Se(e,i*s),l=Se("int32",i*s);for(let d=0;df[I]={value:x,index:I}),s{for(let g=0;gnew hl,1);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Oy=Et(Vr,n=>n>=0?n:Math.exp(n)-1),KL={kernelName:Vr,backendName:"cpu",kernelFunc:Oy};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ky(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{alpha:r}=s;it([o],"leakyRelu");const i=Z(o.shape),a=e.data.get(o.dataId).values,c=Se("float32",i);for(let l=0;ln<0?t*n:n);function Zy(n){const{inputs:t,backend:e}=n,{x:s,alpha:o}=t;it([s,o],"prelu");const r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,[a,c]=BL(s.shape,o.shape,r,i,"float32");return e.makeTensorInfo(c,"float32",a)}const HL={kernelName:oc,backendName:"cpu",kernelFunc:Zy};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const By=Et(ei,n=>Math.max(0,n)),_L={kernelName:ei,backendName:"cpu",kernelFunc:By};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hy=Et(ni,n=>Math.min(Math.max(0,n),6)),UL={kernelName:ni,backendName:"cpu",kernelFunc:Hy};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gl(n,t,e,s,o){if(e==="linear")return Qn({inputs:{x:t},backend:n});if(e==="relu")return By({inputs:{x:t},backend:n});if(e==="elu")return Oy({inputs:{x:t},backend:n});if(e==="relu6")return Hy({inputs:{x:t},backend:n});if(e==="prelu")return Zy({inputs:{x:t,alpha:s},backend:n});if(e==="leakyrelu")return Ky({inputs:{x:t},backend:n,attrs:{alpha:o}});if(e==="sigmoid")return Ny({inputs:{x:t},backend:n});throw new Error(`Activation ${e} has not been implemented for the CPU backend.`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function At(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{shape:r}=s,i=Z(o.shape),a=df(r,i),c=Z(a);v(i===c,()=>`The new shape (${a}) has ${c} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),e.incRef(o.dataId);const l=e.data.get(o.dataId);if(l.complexTensorInfos!=null){const u=l.complexTensorInfos.real,d=l.complexTensorInfos.imag;u.shape=a,d.shape=a}return{dataId:o.dataId,shape:a,dtype:o.dtype}}const YL={kernelName:ic,backendName:"cpu",kernelFunc:At};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _y(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r}=t,{transposeA:i,transposeB:a}=s;it([o,r],"matMul");const c=o.shape.length,l=r.shape.length,u=i?o.shape[c-2]:o.shape[c-1],d=a?r.shape[l-1]:r.shape[l-2],h=i?o.shape[c-1]:o.shape[c-2],p=a?r.shape[l-2]:r.shape[l-1],f=o.shape.slice(0,-2),m=r.shape.slice(0,-2),g=Z(f),b=Z(m),I=gt(o.shape.slice(0,-2),r.shape.slice(0,-2)).concat([h,p]);v(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${o.shape} and ${r.shape} and transposeA=${i} and transposeB=${a} must match.`);const y=i?[g,u,h]:[g,h,u],w=a?[b,p,d]:[b,d,p],C=At({inputs:{x:o},backend:e,attrs:{shape:y}}),k=At({inputs:{x:r},backend:e,attrs:{shape:w}}),S=i?C.shape[1]:C.shape[2],T=i?C.shape[2]:C.shape[1],R=a?k.shape[1]:k.shape[2],L=Math.max(g,b),V=e.data.get(C.dataId).values,F=e.data.get(k.dataId).values,X=ct(C.shape),A=ct(k.shape),[P,B,K]=i?[X[0],1,X[1]]:[X[0],X[1],1],[H,U,Y]=a?[1,A[1],A[0]]:[A[1],1,A[0]],j=T*R,J=wt([L,T,R],C.dtype),nt=J.values,q=e.blockSize;for(let rt=0;rtMath.acos(n)),tE={kernelName:vr,backendName:"cpu",kernelFunc:qL};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eE=Et(Sr,n=>Math.acosh(n)),nE={kernelName:Sr,backendName:"cpu",kernelFunc:eE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sE(n){const{inputs:t,backend:e}=n,s=t;it(t,"addN");const o=s.map(a=>e.data.get(a.dataId).values),r=wt(s[0].shape,s[0].dtype),i=r.values;for(let a=0;ax&&(x=w,I=y)}p[g]=I}return l.forEach(g=>e.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(u,"int32",p)}const uE={kernelName:Ia,backendName:"cpu",kernelFunc:lE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;it(o,"argMin");let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Ke({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),i=[i[0]],Ie("argMin",i,c.shape.length);const[u,d]=me(c.shape,i),h=Z(u),p=ke(h,"int32"),f=Z(d),m=e.data.get(c.dataId).values;for(let g=0;ge.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(u,"int32",p)}const hE={kernelName:wa,backendName:"cpu",kernelFunc:dE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pE=Et(kr,n=>Math.asin(n)),fE={kernelName:kr,backendName:"cpu",kernelFunc:pE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mE=Et(Tr,n=>Math.asinh(n)),gE={kernelName:Tr,backendName:"cpu",kernelFunc:mE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bE=Et(Nr,n=>Math.atan(n)),xE={kernelName:Nr,backendName:"cpu",kernelFunc:bE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yE=oe((n,t)=>Math.atan2(n,t)),IE=pe($r,yE),wE={kernelName:$r,backendName:"cpu",kernelFunc:IE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CE=Et(Rr,n=>Math.atanh(n)),vE={kernelName:Rr,backendName:"cpu",kernelFunc:CE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mp(n,t,e,s,o,r){const i=o.strideHeight,a=o.strideWidth,c=o.dilationHeight,l=o.dilationWidth,u=o.effectiveFilterHeight,d=o.effectiveFilterWidth,h=o.padInfo.top,p=o.padInfo.left,f=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=wt(o.outShape,e),g=m.values,b=o.outShape[1]*o.outShape[2]*o.outShape[3],x=o.outShape[2]*o.outShape[3],I=o.outShape[3];for(let y=0;yB?B=q:r==="avg"&&(K+=q,H++)}if(isNaN(B))break}const U=V+F*I+k;g[U]=r==="avg"?K/H:B}}}return m}function Uy(n,t,e,s,o=!1,r=!1){const i=wt(s.outShape,"int32"),a=s.strideHeight,c=s.strideWidth,l=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,h=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,m=wt(t,e,n);for(let g=0;gR&&(R=P,o?L=r?((g*s.inHeight+V)*s.inWidth+X)*s.inChannels+b:(V*s.inWidth+X)*s.inChannels+b:L=F*h+A)}}i.set(L,g,x,C,b)}}return i}function Yy(n,t,e,s,o,r){const i=o.strideDepth,a=o.strideHeight,c=o.strideWidth,l=o.dilationDepth,u=o.dilationHeight,d=o.dilationWidth,h=o.effectiveFilterDepth,p=o.effectiveFilterHeight,f=o.effectiveFilterWidth,m=o.padInfo.front,g=o.padInfo.top,b=o.padInfo.left,x=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,I=wt(o.outShape,e),y=I.values,w=o.outShape[1]*o.outShape[2]*o.outShape[3]*o.outShape[4],C=o.outShape[2]*o.outShape[3]*o.outShape[4],k=o.outShape[3]*o.outShape[4],S=o.outShape[4];for(let T=0;Tft?ft=Ut:r==="avg"&&(ht+=Ut,xt++),isNaN(ft))break}if(isNaN(ft))break}if(isNaN(ft))break}const yt=lt+V;y[yt]=r==="avg"?ht/Math.max(xt,1):ft}}}}return I}function SE(n,t){const e=wt(t.outShape,"int32"),s=t.strideDepth,o=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,h=t.padInfo.front,p=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=F&&(F=Y,X=P*u*d+K*u+U)}}}e.set(X,m,b,w,T,g)}}}return e}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;it(o,"avgPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);let d;if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))d=Qn({inputs:{x:o},backend:e});else{const h=e.data.get(o.dataId).values,p=ct(o.shape),f=mp(h,o.shape,o.dtype,p,u,"avg");d=e.makeTensorInfo(u.outShape,o.dtype,f.values)}return d}const TE={kernelName:Ca,backendName:"cpu",kernelFunc:kE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s;it(o,"avgPool3d");const u=ss(o.shape,r,i,1,a,c,l),d=e.data.get(o.dataId).values,h=Yy(d,o.shape,o.dtype,ct(o.shape),u,"avg");return e.makeTensorInfo(h.shape,"float32",h.values)}const RE={kernelName:va,backendName:"cpu",kernelFunc:NE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $E(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,{filterSize:i,strides:a,pad:c,dimRoundingMode:l}=s;it([o,r],"avgPool3DGrad");const u=ss(r.shape,i,a,1,c,l),d=u.strideDepth,h=u.strideHeight,p=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,b=u.dilationDepth,x=u.dilationHeight,I=u.dilationWidth,y=u.effectiveFilterDepth,w=u.effectiveFilterHeight,C=u.effectiveFilterWidth,k=y-1-u.padInfo.front,S=C-1-u.padInfo.left,T=w-1-u.padInfo.top,R=wt(r.shape,"float32"),L=1/(f*m*g),V=e.bufferSync(o);for(let F=0;F=u.outDepth||Math.floor(J)!==J))for(let nt=0;nt=u.outHeight||Math.floor(q)!==q))for(let rt=0;rt=u.outWidth||Math.floor(lt)!==lt)continue;const ft=V.get(F,J,q,lt,X);Y+=ft}}}R.set(Y*L,F,A,P,B,X)}return e.makeTensorInfo(R.shape,R.dtype,R.values)}const GE={kernelName:iu,backendName:"cpu",kernelFunc:$E};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LE(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r;it([o,r],"avgPoolGrad");const{filterSize:a,strides:c,pad:l}=s,u=pn(i.shape,a,c,1,l),d=u.strideHeight,h=u.strideWidth,p=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,b=u.effectiveFilterHeight,x=u.effectiveFilterWidth,I=x-1-u.padInfo.left,y=b-1-u.padInfo.top,w=wt(i.shape,"float32"),C=1/(p*f),k=e.data.get(o.dataId).values,S=wt(o.shape,"float32",k);for(let T=0;T=u.outHeight||Math.floor(B)!==B))for(let K=0;K=u.outWidth||Math.floor(H)!==H)continue;const U=S.get(T,B,H,R);A+=U}}w.set(A*C,T,L,V,R)}return e.makeTensorInfo(w.shape,w.dtype,w.values)}const EE={kernelName:ru,backendName:"cpu",kernelFunc:LE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,scale:r,offset:i,mean:a,variance:c}=t;v(a.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(r==null||a.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),it([o,a,c,r,i],"batchNorm");let{varianceEpsilon:l}=s;l==null&&(l=.001);const u=e.data.get(o.dataId).values,d=e.data.get(a.dataId).values,h=e.data.get(c.dataId).values,p=r?e.data.get(r.dataId).values:new Float32Array([1]),f=i?e.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,b=p.length,x=h.length,I=d.length;let y=0,w=0,C=0,k=0;for(let S=0;S=g&&(y=0),w>=I&&(w=0),C>=b&&(C=0),k>=x&&(k=0);return e.makeTensorInfo(o.shape,o.dtype,m)}const WE={kernelName:Va,backendName:"cpu",kernelFunc:DE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ME(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,crops:i}=s;it([o],"batchToSpaceND");const a=r.reduce((b,x)=>b*x),c=Mi(o.shape,r,a),l=Vi(c.length,r.length),u=Fi(o.shape,r,a),d=ah(i,r.length),h=ch(u,i,r.length),p=At({inputs:{x:o},backend:e,attrs:{shape:c}}),f=Ke({inputs:{x:p},backend:e,attrs:{perm:l}}),m=At({inputs:{x:f},backend:e,attrs:{shape:u}}),g=wo({inputs:{x:m},backend:e,attrs:{begin:d,size:h}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),g}const VE={kernelName:ka,backendName:"cpu",kernelFunc:ME};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i}=s,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,l=up(a,c,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,l)}const zE={kernelName:au,backendName:"cpu",kernelFunc:FE};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XE(n){const{inputs:t,backend:e}=n,{s0:s,s1:o}=t,r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,a=gt(Array.from(r),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const AE={kernelName:xf,backendName:"cpu",kernelFunc:XE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PE=Et(Er,(n,t)=>{const e=t;return n>e.clipValueMax?e.clipValueMax:n{const{x:t}=n.inputs,e=n.backend,s=new Float32Array(Z(t.shape)),o=e.data.get(t.dataId),r=o.complexTensorInfos.real,i=o.complexTensorInfos.imag,a=e.data.get(r.dataId).values,c=e.data.get(i.dataId).values;for(let l=0;lm.shape);oh(i,r);let a=Kn(t.map(m=>m.shape),r);if(Z(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(m=>Z(m.shape)>0);if(c.length===1)return Qn({inputs:{x:c[0]},backend:e});if(c[0].dtype==="complex64"){const m=c.map(y=>yo({inputs:{input:y},backend:e})),g=c.map(y=>ar({inputs:{input:y},backend:e})),b=cr({inputs:m,backend:e,attrs:{axis:r}}),x=cr({inputs:g,backend:e,attrs:{axis:r}}),I=Qe({inputs:{real:b,imag:x},backend:e});return m.forEach(y=>e.disposeIntermediateTensorInfo(y)),g.forEach(y=>e.disposeIntermediateTensorInfo(y)),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(x),I}const l=c.map(m=>{const b=[-1,Z(m.shape.slice(r))];return At({inputs:{x:m},backend:e,attrs:{shape:b}})}),u=l.map(m=>({vals:e.data.get(m.dataId).values,shape:m.shape}));a=Kn(l.map(m=>m.shape),1);const d=l[0].shape[0]===1,h=Qx(u,a,t[0].dtype,d),p=Kn(c.map(m=>m.shape),r),f=e.makeTensorInfo(p,t[0].dtype,h);return l.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}const BE={kernelName:Na,backendName:"cpu",kernelFunc:cr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qy(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dataFormat:c,dilations:l,dimRoundingMode:u}=s;it([o,r],"conv2d");const d=os(c),h=ye(o.shape,r.shape,i,l,a,u,!1,d),p=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,b=h.padInfo.left,x=h.padInfo.top,I=h.dataFormat==="channelsLast",y=new xe(h.outShape,o.dtype),w=ct(o.shape),C=ct(r.shape),k=w[0],S=I?w[1]:w[2],T=I?w[2]:1,R=I?1:w[1],L=y.strides[0],V=I?y.strides[1]:y.strides[2],F=I?y.strides[2]:1,X=I?1:y.strides[1],A=e.data.get(o.dataId).values,P=e.data.get(r.dataId).values,B=y.values;for(let K=0;K=h.inHeight)continue;const rt=nt*C[0],lt=H+q*S;for(let ft=0;ft=h.inWidth)continue;const Pt=rt+yt*C[1],jt=lt+Dt*T;let Ot=Pt;for(let Mt=0;Mt=l.inDepth)continue;const K=P*T[0],H=L+B*S[1];for(let U=0;U=l.inHeight)continue;const q=K+J*T[1],rt=H+nt*S[2];for(let lt=0;lt=l.inWidth)continue;const Dt=q+xt*T[2],Pt=rt+yt*l.inChannels;let jt=Dt;for(let Ot=0;OtMath.cos(n)),o3={kernelName:Dr,backendName:"cpu",kernelFunc:s3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const r3=Et(Wr,n=>Math.cosh(n)),i3={kernelName:Wr,backendName:"cpu",kernelFunc:r3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a3(n){const{inputs:t,backend:e,attrs:s}=n,{image:o,boxes:r,boxInd:i}=t,{cropSize:a,method:c,extrapolationValue:l}=s,[u,d,h,p]=o.shape,f=r.shape[0],[m,g]=a,b=wt([f,m,g,p],"float32"),x=e.data.get(r.dataId).values,I=e.data.get(i.dataId).values,y=e.data.get(o.dataId).values,w=ct(o.shape),C=ct(b.shape);for(let k=0;k=u)continue;const X=m>1?(L-T)*(d-1)/(m-1):0,A=g>1?(V-R)*(h-1)/(g-1):0;for(let P=0;P1?T*(d-1)+P*X:.5*(T+L)*(d-1);if(B<0||B>d-1){for(let K=0;K1?R*(h-1)+Y*A:.5*(R+V)*(h-1);if(j<0||j>h-1){for(let rt=0;rt1?R*(h-1)+K*A:.5*(R+V)*(h-1);if(H<0||H>h-1){for(let j=0;jb+f-x-1:(b,x)=>b+x;for(let b=0;bb+f-x-1:(b,x)=>b+x;for(let b=0;b`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);const a=o.shape[0],c=o.shape[1],l=o.shape[2],u=o.shape[3],d=c*r,h=l*r,p=u/(r*r),f=e.data.get(o.dataId).values,m=new Float32Array(a*d*h*p);let g=0;for(let b=0;b`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`);const p=ye(o.shape,r.shape,i,h,a,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:b,padInfo:x}=p,I=x.left,y=x.top,w=p.outChannels/p.inChannels,C=new xe(p.outShape,o.dtype),k=e.data.get(o.dataId).values,S=e.data.get(r.dataId).values,T=C.values;for(let R=0;R=p.inHeight)continue;const K=P*d[0],H=L+B*u[1];for(let U=0;U=p.inWidth)continue;const q=K+J*d[1],rt=H+nt*p.inChannels;let lt=Y,ft=q;for(let ht=0;ht{const{x:s,filter:o}=n,{strides:r,pad:i,dilations:a}=e,c=t,l=c.data.get(s.dataId).values,u=s.shape.length,d=c.data.get(o.dataId).values,h=o.shape.length,{batchSize:p,inHeight:f,inWidth:m,inChannels:g,outHeight:b,outWidth:x,padInfo:I,strideHeight:y,strideWidth:w,filterHeight:C,filterWidth:k,dilationHeight:S,dilationWidth:T,outShape:R}=Si(s.shape,o.shape,r,i,"NHWC",a),L=Z(R),V=R.length,F=qt(s.dtype,L);for(let A=0;A=0&&nt=0&&rtY&&(Y=ht)}}}const j=Fn([A,P,K,U],V,ct(R));F[j]=Y}}}return{dataId:c.write(Ys(F,s.dtype),R,s.dtype),shape:R,dtype:s.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const k3={kernelName:Iu,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:o,dy:r}=n,{strides:i,pad:a,dilations:c}=e,l=t,u=vn(s.shape,l.data.get(s.dataId).values),d=vn(o.shape,l.data.get(o.dataId).values),{batchSize:h,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:x,strideHeight:I,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:k,dilationWidth:S,outShape:T}=Si(s.shape,o.shape,i,a,"NHWC",c);v(r.rank===T.length,()=>`Error in ${Iu}, dy must have the same rank as output ${T.length}, but got ${r.rank}`);const R=vn(T,l.data.get(r.dataId).values),L=ff(o.shape,o.dtype);for(let F=0;F=0&&J=0&&qH&&(H=rt,U=j,Y=nt)}}}L[U][Y][K]+=R[F][X][P][K]}}}return{dataId:l.write(Ys(L,s.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T3={kernelName:yu,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:o,dy:r}=n,{strides:i,pad:a,dilations:c}=e,l=t,u=vn(s.shape,l.data.get(s.dataId).values),d=vn(o.shape,l.data.get(o.dataId).values),{batchSize:h,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:x,strideHeight:I,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:k,dilationWidth:S,outShape:T}=Si(s.shape,o.shape,i,a,"NHWC",c);v(r.rank===T.length,()=>`Error in ${yu}, dy must have the same rank as output ${T.length}, but got ${r.rank}`);const R=vn(T,l.data.get(r.dataId).values),L=ff(s.shape,s.dtype);for(let F=0;F=0&&J=0&&qH&&(H=rt,U=J,Y=q)}}}L[F][U][Y][K]+=R[F][X][P][K]}}}return{dataId:l.write(Ys(L,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N3(n){const{inputs:t,backend:e,attrs:s}=n,{image:o}=t,{canvas:r,options:i}=s,{contextOptions:a,imageOptions:c}=i||{},l=(c==null?void 0:c.alpha)||1,u=(a==null?void 0:a.contextType)||"2d";if(u!=="2d")throw new Error(`Context type ${a.contextType} is not supported by the CPU backend.`);const d=r.getContext(u,(a==null?void 0:a.contextAttributes)||{});if(d==null)throw new Error(`Could not get the context with ${u} type.`);const[h,p]=o.shape.slice(0,2),f=o.shape.length===2?1:o.shape[2],m=e.data.get(o.dataId).values,g=o.dtype==="float32"?255:1,b=new Uint8ClampedArray(p*h*4);for(let I=0;I1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${k}.`)}else if(o.dtype==="int32"&&(k<0||k>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${k}.`);f===1?(y[0]=k*g,y[1]=k*g,y[2]=k*g):y[C]=k*g}const w=I*4;b[w+0]=Math.round(y[0]),b[w+1]=Math.round(y[1]),b[w+2]=Math.round(y[2]),b[w+3]=Math.round(y[3])}r.width=p,r.height=h;const x=new ImageData(b,p,h);return d.putImageData(x,0,0),o}const R3={kernelName:hw,backendName:"cpu",kernelFunc:N3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ea(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"sum");let a;o.dtype==="bool"?a=Ws({inputs:{x:o},backend:e,attrs:{dtype:"int32"}}):a=Qn({inputs:{x:o},backend:e});const c=a.shape.length,l=It(r,a.shape),u=Yt(l,c);let d=l,h=a;u!=null&&(h=Ke({inputs:{x:a},backend:e,attrs:{perm:u}}),d=ee(d.length,c)),Ie("sum",d,h.shape.length);const[p,f]=me(h.shape,d),m=_e(h.dtype,"int32");let g=pl(e,p,m);const b=Z(f),x=e.data.get(g.dataId).values,I=e.data.get(h.dataId).values;for(let y=0;y=0&&(h=ea({inputs:{x:h},backend:e,attrs:{axis:l[m]-(i.length-p),keepDims:!1}}),f.push(h)),p--)}for(const m of f)m!==h&&e.disposeIntermediateTensorInfo(m);return h}const L3={kernelName:wu,backendName:"cpu",kernelFunc:G3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function E3(n){const{inputs:t,backend:e}=n,{dy:s,y:o}=t;it([s,o],"eluGrad");const r=new Float32Array(Z(o.shape)),i=e.data.get(o.dataId).values,a=e.data.get(s.dataId).values;for(let c=0;c=0?r[c]=a[c]:r[c]=a[c]*(l+1)}return e.makeTensorInfo(o.shape,"float32",r)}const D3={kernelName:Cu,backendName:"cpu",kernelFunc:E3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W3=lh,M3=uh,V3=dh,F3=hh,z3=ph,X3=fh,A3=Et(Fr,n=>{const t=Math.sign(n),e=Math.abs(n),s=1/(1+W3*e);return t*(1-((((X3*s+z3)*s+F3)*s+V3)*s+M3)*s*Math.exp(-e*e))}),P3={kernelName:Fr,backendName:"cpu",kernelFunc:A3};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bl(n){const{inputs:t,backend:e,attrs:s}=n,{input:o}=t,{dim:r}=s,i=o.shape.length,a=o.shape.slice();let c=r;return r<0&&(v(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),c=i+r+1),a.splice(c,0,1),At({inputs:{x:o},backend:e,attrs:{shape:a}})}const O3={kernelName:Ma,backendName:"cpu",kernelFunc:bl};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const K3=oe((n,t)=>n/t),gp=pe(Mr,K3),bp={kernelName:Mr,backendName:"cpu",kernelFunc:gp};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jy(n,t,e){const s=n.shape,o=s[0],r=s[1],i=e.data.get(n.dataId),a=i.complexTensorInfos.real,c=i.complexTensorInfos.imag,l=[o,r],u=Z(l),d=Se("float32",u),h=Se("float32",u);for(let g=0;g{const{image:s}=n,o=e,r=Se(s.dtype,Z(s.shape)),[i,a,c,l]=s.shape,u=o.data.get(s.dataId).values;for(let h=0;h=0&&I=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=a;a==null&&(d=0);const h=Z(r.shape),p=Sh(o,r,c,d),f=At({inputs:{x:o},backend:e,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),m=At({inputs:{x:r},backend:e,attrs:{shape:[p.batchSize,h/p.batchSize]}}),g=[p.batchSize,p.outerSize,h/p.batchSize,p.sliceSize],b=e.bufferSync(m),x=e.bufferSync(f),I=ry(x,b,g);return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),e.makeTensorInfo(p.outputShape,I.dtype,I.values)}const rD={kernelName:Fa,backendName:"cpu",kernelFunc:oD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iD(n){const{inputs:t,backend:e}=n,{input:s}=t,o=Z(s.shape),r=s.shape[s.shape.length-1],i=o/r,a=At({inputs:{x:s},backend:e,attrs:{shape:[i,r]}}),c=jy(a,!0,e),l=At({inputs:{x:c},backend:e,attrs:{shape:s.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(c),l}const aD={kernelName:Tu,backendName:"cpu",kernelFunc:iD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cD=Et(Zr,n=>Number.isFinite(n)?1:0,"bool"),lD={kernelName:Zr,backendName:"cpu",kernelFunc:cD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uD=Et(Br,n=>Math.abs(n)===1/0?1:0,"bool"),dD={kernelName:Br,backendName:"cpu",kernelFunc:uD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hD=Et(Hr,n=>Number.isNaN(n)?1:0,"bool"),pD={kernelName:Hr,backendName:"cpu",kernelFunc:hD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fD(n){const{backend:t,attrs:e}=n,{start:s,stop:o,num:r}=e,i=uy(s,o,r);return t.makeTensorInfo([i.length],"float32",i)}const mD={kernelName:wf,backendName:"cpu",kernelFunc:fD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gD=Et(Ur,n=>Math.log1p(n)),bD={kernelName:Ur,backendName:"cpu",kernelFunc:gD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xD=oe((n,t)=>n&&t),yD=pe(Oa,xD,null,"bool"),ID={kernelName:Oa,backendName:"cpu",kernelFunc:yD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wD=Et(Ka,n=>n?0:1,"bool"),CD={kernelName:Ka,backendName:"cpu",kernelFunc:wD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vD=oe((n,t)=>n||t),SD=pe(Za,vD,null,"bool"),kD={kernelName:Za,backendName:"cpu",kernelFunc:SD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{depthRadius:r,bias:i,alpha:a,beta:c}=s;it(o,"LRN");const l=o.shape[3],u=l-1,d=e.data.get(o.dataId).values,h=Z(o.shape),p=new Float32Array(h);function f(m){const g=m%l;let b=m-g+Math.max(0,g-r);const x=m-g+Math.min(g+r,u);let I=0;for(;b<=x;b++){const y=d[b];I+=y*y}return I}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);let d;if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))d=Qn({inputs:{x:o},backend:e});else{const h=e.data.get(o.dataId).values,p=ct(o.shape),f=mp(h,o.shape,o.dtype,p,u,"max");d=e.makeTensorInfo(u.outShape,o.dtype,f.values)}return d}const ED={kernelName:_a,backendName:"cpu",kernelFunc:LD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s;it(o,"maxPool3d");const u=ss(o.shape,r,i,1,a,c,l),d=e.data.get(o.dataId).values,h=Yy(d,o.shape,o.dtype,ct(o.shape),u,"max");return e.makeTensorInfo(h.shape,"float32",h.values)}const WD={kernelName:Ua,backendName:"cpu",kernelFunc:DD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MD(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,{filterSize:i,strides:a,pad:c,dimRoundingMode:l}=s;it([o,r],"maxPool3DGrad");const u=ss(r.shape,i,a,1,c,l),d=e.bufferSync(r),h=SE(d,u),p=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,b=u.dilationHeight,x=u.dilationWidth,I=u.effectiveFilterDepth,y=u.effectiveFilterHeight,w=u.effectiveFilterWidth,C=I-1-u.padInfo.front,k=w-1-u.padInfo.left,S=y-1-u.padInfo.top,T=wt(r.shape,"float32"),R=e.bufferSync(o);for(let L=0;L=u.outDepth||Math.floor(Y)!==Y))for(let j=0;j=u.outHeight||Math.floor(J)!==J))for(let nt=0;nt=u.outWidth||Math.floor(q)!==q)continue;const rt=I*y*w-1-h.get(L,Y,J,q,V),lt=U*y*w+j*w+nt,ft=rt===lt?1:0;if(ft===0)continue;const ht=R.get(L,Y,J,q,V);H+=ht*ft}}}T.set(H,L,F,X,A,V)}return e.makeTensorInfo(T.shape,T.dtype,T.values)}const VD={kernelName:Gu,backendName:"cpu",kernelFunc:MD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FD(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r,output:i}=t,a=r;it([r,i],"maxPoolGrad");const{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=s,h=pn(a.shape,c,l,1,u,d),p=e.data.get(a.dataId).values,f=wt(h.outShape,a.dtype,Uy(p,a.shape,a.dtype,h).values),m=h.strideHeight,g=h.strideWidth,b=h.dilationHeight,x=h.dilationWidth,I=h.effectiveFilterHeight,y=h.effectiveFilterWidth,w=y-1-h.padInfo.left,C=I-1-h.padInfo.top,k=wt(a.shape,"float32"),S=e.data.get(o.dataId).values,T=wt(o.shape,"float32",S);for(let R=0;R=h.outHeight||Math.floor(K)!==K))for(let H=0;H=h.outWidth||Math.floor(U)!==U)continue;const Y=I*y-1-f.get(R,K,U,L),j=B*y+H,J=Y===j?1:0;if(J===0)continue;const nt=T.get(R,K,U,L);P+=nt*J}}k.set(P,R,V,F,L)}return e.makeTensorInfo(k.shape,k.dtype,k.values)}const zD={kernelName:$u,backendName:"cpu",kernelFunc:FD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XD(n,t,e,s,o){const r=ct(t),i=mp(n,t,e,r,o,"max"),a=Uy(n,t,e,o,!0,s);return[i.values,a.values]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const AD={kernelName:Cf,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:o,strides:r,pad:i,includeBatchInIndex:a}=t,c=e;it(s,"MaxPoolWithArgmax");const l=c.data.get(s.dataId).values,u=pn(s.shape,o,r,[1,1],i),[d,h]=XD(l,s.shape,s.dtype,a,u),p=c.write(d,u.outShape,s.dtype),f=c.write(h,u.outShape,s.dtype);return[{dataId:p,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=It(r,o.shape),l=me(o.shape,a)[1],u=Z(l),d=[],h=e.makeTensorInfo([],"float32",new Float32Array([u]));d.push(h);const p=Ws({inputs:{x:o},backend:e,attrs:{dtype:"float32"}});d.push(p);const f=gp({inputs:{a:p,b:h},backend:e});d.push(f);const m=ea({inputs:{x:f},backend:e,attrs:{axis:r,keepDims:i}});return d.forEach(g=>e.disposeIntermediateTensorInfo(g)),m}const OD={kernelName:Ya,backendName:"cpu",kernelFunc:PD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"min");const a=It(r,o.shape);let c=a;const l=Yt(c,o.shape.length);let u=o;l!=null&&(u=Ke({inputs:{x:o},backend:e,attrs:{perm:l}}),c=ee(c.length,o.shape.length)),Ie("min",c,u.shape.length);const[d,h]=me(u.shape,c),p=Z(h),f=ke(Z(d),u.dtype),m=e.data.get(u.dataId).values;for(let b=0;bI[0]+o.shape[y]+I[1]),c=r.map(I=>I[0]),l=r.map((I,y)=>I[0]+o.shape[y]),u=i==="reflect"?0:1,d=e.data.get(o.dataId).values,h=o.shape.length,p=ct(o.shape),f=Z(a),m=a.length,g=ct(a),b=Se(o.dtype,f);for(let I=0;I=l[C]&&(y[C]=(l[C]-1)*2-y[C]+u);y=y.map((C,k)=>C-c[k]);const w=Fn(y,h,p);b[I]=d[w]}return{dataId:e.write(b,a,o.dtype),shape:a,dtype:o.dtype}}const HD={kernelName:Ja,backendName:"cpu",kernelFunc:BD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _D=oe((n,t)=>{const e=n%t;return n<0&&t<0||n>=0&&t>=0?e:(e+t)%t}),UD=pe(Jr,_D),YD={kernelName:Jr,backendName:"cpu",kernelFunc:UD};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function t1(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{dim:r}=s,i=o.shape.length;let a=r;if(a===-1&&(a=i-1),a!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${a}`);const c=It([a],o.shape),l=qy({inputs:{x:o},backend:e,attrs:{reductionIndices:c,keepDims:!1}}),u=re(l.shape,c),d=At({inputs:{x:l},backend:e,attrs:{shape:u}}),h=fp({inputs:{a:o,b:d},backend:e}),p=ty({inputs:{x:h},backend:e}),f=ea({inputs:{x:p},backend:e,attrs:{axis:c,keepDims:!1}}),m=At({inputs:{x:f},backend:e,attrs:{shape:u}}),g=gp({inputs:{a:p,b:m},backend:e});return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),g}const QD={kernelName:mc,backendName:"cpu",kernelFunc:t1};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JD(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{numSamples:r,seed:i,normalized:a}=s;it(o,"multinomial");const c=a?o:t1({inputs:{logits:o},backend:e,attrs:{dim:-1}}),l=c.shape[0],u=c.shape[1],d=e.data.get(c.dataId).values,h=[l,r],p=ke(Z(h),"int32");for(let f=0;f=0&&d[h]{Hl(r,u.shape,"All tensors passed to stack must have matching shapes"),v(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],c=t.map(u=>{const d=bl({inputs:{input:u},backend:e,attrs:{dim:o}});return a.push(d),d}),l=cr({inputs:c,backend:e,attrs:{axis:o}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),l}const hW={kernelName:nc,backendName:"cpu",kernelFunc:n1};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pW(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{paddings:r,constantValue:i}=s;it(o,"pad");const a=r.map((x,I)=>x[0]+o.shape[I]+x[1]),c=r.map(x=>x[0]),l=e.data.get(o.dataId).values,u=Z(o.shape),d=o.shape.length,h=ct(o.shape),p=Z(a),f=a.length,m=ct(a),g=Se(o.dtype,p);i!==0&&g.fill(i);for(let x=0;xC+c[k]),w=Fn(y,f,m);g[w]=l[x]}return{dataId:e.write(g,a,o.dtype),shape:a,dtype:o.dtype}}const s1={kernelName:sc,backendName:"cpu",kernelFunc:pW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fW=oe((n,t)=>Math.pow(n,t)),mW=pe(qr,fW),gW={kernelName:qr,backendName:"cpu",kernelFunc:mW};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bW(n){const{inputs:t,backend:e,attrs:s}=n,{paramsNestedSplits:o,paramsDenseValues:r,indices:i}=t,a=o.map(g=>e.data.get(g.dataId).values),c=o.map(g=>g.shape),l=e.data.get(r.dataId).values,u=e.data.get(i.dataId).values,[d,h,p]=yy(a,c,l,r.shape,r.dtype,u,i.shape),f=d.map(g=>e.makeTensorInfo([g.length],"int32",g)),m=e.makeTensorInfo(p,r.dtype,h);return f.concat([m])}const xW={kernelName:Sf,backendName:"cpu",kernelFunc:bW};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yW(n){const{inputs:t,backend:e}=n,{starts:s,limits:o,deltas:r}=t,i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=wy(i,s.shape,s.dtype,a,o.shape,c,r.shape),d=e.makeTensorInfo([l.length],"int32",l),h=e.makeTensorInfo([u.length],s.dtype,u);return[d,h]}const IW={kernelName:kf,backendName:"cpu",kernelFunc:yW};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wW(n){const{inputs:t,backend:e,attrs:s}=n,{shape:o,values:r,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:c}=s,l=e.data.get(o.dataId).values,u=e.data.get(r.dataId).values,d=e.data.get(i.dataId).values,h=a.map(g=>e.data.get(g.dataId).values),p=a.map(g=>g.shape),[f,m]=Sy(l,o.shape,u,r.shape,r.dtype,d,i.shape,h,p,c);return e.makeTensorInfo(f,r.dtype,m)}const CW={kernelName:Tf,backendName:"cpu",kernelFunc:wW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vW(n){const{backend:t,attrs:e}=n,{start:s,stop:o,dtype:r,step:i}=e,a=ky(s,o,i,r);return t.makeTensorInfo([a.length],r,a)}const SW={kernelName:Wu,backendName:"cpu",kernelFunc:vW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kW=Et(ti,n=>1/n),TW={kernelName:ti,backendName:"cpu",kernelFunc:kW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NW(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s;it(o,"resizeBilinear");const c=ct(o.shape),[l,u]=a,[d,h,p,f]=o.shape,m=e.data.get(o.dataId).values,g=new Float32Array(Z([d,l,u,f])),b=[r&&l>1?h-1:h,r&&u>1?p-1:p],x=[r&&l>1?l-1:l,r&&u>1?u-1:u];let I=0;const y=b[0]/x[0],w=b[1]/x[1];for(let C=0;C1?l-1:l,i&&p>1?u-1:u],g=[i&&h>1?h-1:h,i&&p>1?p-1:p],b=m[0]/g[0],x=m[1]/g[1],I=e.data.get(r.dataId).values;let y=0;for(let w=0;w1?h-1:h,r&&u>1?p-1:p],x=[r&&l>1?l-1:l,r&&u>1?u-1:u],I=b[0]/x[0],y=b[1]/x[1];let w=0;for(let C=0;C1?u-1:u,i&&f>1?d-1:d],x=[i&&p>1?p-1:p,i&&f>1?f-1:f],I=b[0]/x[0],y=b[1]/x[1],w=1/I,C=1/y,k=Math.ceil(w)*2+2,S=Math.ceil(C)*2+2;for(let T=0;T=p)continue;const J=R+j*c[1],nt=j*I,q=Math.min(u-1,i?Math.round(nt):Math.floor(nt));if(L===q)for(let rt=0;rt=f)continue;const ft=J+lt*c[2],ht=lt*y,xt=Math.min(d-1,i?Math.round(ht):Math.floor(ht));A===xt&&(U+=g[ft+H])}}m[P+H]=U}}}}return e.makeTensorInfo(o.shape,o.dtype,m)}const WW={kernelName:Vu,backendName:"cpu",kernelFunc:DW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MW(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dims:r}=s;it(o,"reverse");const i=o.shape.length,a=It(r,o.shape);if(i===0)return Qn({inputs:{x:o},backend:e});const c=new xe(o.shape,o.dtype),l=e.bufferSync(o);for(let u=0;uh[p]=o.shape[p]-1-h[p]),c.set(l.get(...h),...d)}return e.makeTensorInfo(c.shape,c.dtype,c.values)}const VW={kernelName:lc,backendName:"cpu",kernelFunc:MW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FW={kernelName:Bu,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:o,fillValue:r,center:i}=t,a=e,c=Se(s.dtype,Z(s.shape)),[l,u,d,h]=s.shape,[p,f]=ih(i,u,d),m=255,g=Math.sin(o),b=Math.cos(o),x=a.data.get(s.dataId).values;for(let y=0;y=0&&X=0&&A{const t=Math.floor(n);return n-t<.5?Math.floor(n):n-t>.5?Math.ceil(n):t%2===0?t:t+1}),XW={kernelName:si,backendName:"cpu",kernelFunc:zW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AW(n){const{inputs:t,backend:e,attrs:s}=n,{indices:o,updates:r}=t,{shape:i}=s,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(r,o,i),h=!0,p=e.bufferSync(o),f=e.bufferSync(r),m=Io(p,f,i,d,l,c,a,u,0,h);return e.makeTensorInfo(i,m.dtype,m.values)}const PW={kernelName:Nf,backendName:"cpu",kernelFunc:AW};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OW(n,t){let e=0,s=n.length,o=0;for(;e1||o.shape.length===1?1:Z(o.shape.slice(1));for(let f=0;fn>=0?QW*n:YW*(Math.exp(n)-1)),jW={kernelName:ri,backendName:"cpu",kernelFunc:JW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qW=Et(ci,n=>n<0?-1:n>0?1:0),tM={kernelName:ci,backendName:"cpu",kernelFunc:qW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eM=Et(ii,n=>Math.sin(n)),nM={kernelName:ii,backendName:"cpu",kernelFunc:eM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sM=Et(ai,n=>Math.sinh(n)),oM={kernelName:ai,backendName:"cpu",kernelFunc:sM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const o1=Math.log(11920928955078125e-23)+2,rM=Et(ui,n=>{const t=n>-o1,e=nNumber(g)))),e.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}const uM={kernelName:Gf,backendName:"cpu",kernelFunc:lM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dM(n){const{inputs:t,backend:e}=n,{inputIndices:s,inputShape:o,newShape:r}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape + ${s.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape + ${o.shape}`);if(r.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${r.shape}`);const i=Array.from(e.data.get(o.dataId).values),a=e.data.get(s.dataId).values,c=Array.from(e.data.get(r.dataId).values),[l,u,d]=Gy(a,s.shape,s.dtype,i,c);return[e.makeTensorInfo(u,s.dtype,l),e.makeTensorInfo([d.length],r.dtype,new Int32Array(d))]}const hM={kernelName:Lf,backendName:"cpu",kernelFunc:dM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pM(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${r.shape}`);if(o.shape[0]!==r.shape[0])throw new Error("segmentIds and indices should have same size.");const i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=pp(i,s.shape,s.dtype,a,c,!0);return e.makeTensorInfo(u,s.dtype,l)}const fM={kernelName:Ef,backendName:"cpu",kernelFunc:pM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mM(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${r.shape}`);if(o.shape[0]!==r.shape[0])throw new Error("segmentIds and indices should have same size.");const i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=pp(i,s.shape,s.dtype,a,c);return e.makeTensorInfo(u,s.dtype,l)}const gM={kernelName:Df,backendName:"cpu",kernelFunc:mM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bM(n){const{inputs:t,backend:e,attrs:s}=n,{sparseIndices:o,sparseValues:r,defaultValue:i}=t,{outputShape:a}=s,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=co(r,o,a),p=!1,f=e.bufferSync(o);let m;switch(r.dtype){case"bool":{const g=e.bufferSync(r),b=!!e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"float32":{const g=e.bufferSync(r),b=e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"int32":{const g=e.bufferSync(r),b=e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"string":{const g=e.bufferSync(r),b=xs(e.data.get(i.dataId).values[0]);m=Io(f,g,a,h,u,l,c,d,b,p);break}default:throw new Error(`Unsupported type ${r.dtype}`)}return e.makeTensorInfo(a,m.dtype,m.values)}const xM={kernelName:Wf,backendName:"cpu",kernelFunc:bM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{numOrSizeSplits:r,axis:i}=s,a=It(i,o.shape)[0],c=Ch(o,r,a),l=new Array(o.shape.length).fill(0),u=o.shape.slice();return c.map(d=>{const h=[...u];h[a]=d;const p=wo({inputs:{x:o},backend:e,attrs:{begin:l,size:h}});return l[a]+=d,p})}const IM={kernelName:fc,backendName:"cpu",kernelFunc:yM};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wM={kernelName:zu,backendName:"cpu",kernelFunc:({inputs:n,backend:t})=>{const{x:e}=n,s=t;it(e,"square");const o=s.data.get(e.dataId).values,r=new Float32Array(o.length);for(let a=0;a{const e=t;return isNaN(n)?NaN:n>0?1:e.alpha}),vM={kernelName:bi,backendName:"cpu",kernelFunc:CM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,end:i,strides:a,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=s;it(o,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:x,end:I,strides:y}=sh(o.shape,r,i,a,c,l,u,d,h);let w;if(m)w=At({inputs:{x:o},backend:e,attrs:{shape:f}});else if(g||b){v(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);const C=th(x,I,y),k=wo({inputs:{x:o},backend:e,attrs:{begin:x,size:C}});w=At({inputs:{x:k},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(k)}else{const C=e.bufferSync(o),k=Dy(p,C,y,x);w=e.makeTensorInfo(f,k.dtype,k.values)}return w}const kM={kernelName:Au,backendName:"cpu",kernelFunc:SM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TM(n){const{inputs:t,backend:e,attrs:s}=n,{separator:o,nGramWidths:r,leftPad:i,rightPad:a,padWidth:c,preserveShortSequences:l}=s,{data:u,dataSplits:d}=t,h=e.data.get(u.dataId).values,p=e.data.get(d.dataId).values,[f,m]=Wy(h,p,o,r,i,a,c,l);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(d.shape,"int32",m)]}const NM={kernelName:Mf,backendName:"cpu",kernelFunc:TM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RM(n){const{inputs:t,backend:e,attrs:s}=n,{skipEmpty:o}=s,{input:r,delimiter:i}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(r.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${r.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const a=e.data.get(r.dataId).values,c=e.data.get(i.dataId).values[0],[l,u,d]=My(a,c,o),h=u.length;return[e.makeTensorInfo([h,2],"int32",l),e.makeTensorInfo([h],"string",u),e.makeTensorInfo([2],"int32",new Int32Array(d))]}const $M={kernelName:Vf,backendName:"cpu",kernelFunc:RM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GM(n){const{inputs:t,backend:e,attrs:s}=n,{numBuckets:o}=s,{input:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");const i=e.data.get(r.dataId).values,a=Vy(i,o);return e.makeTensorInfo(r.shape,"int32",a)}const LM={kernelName:Ff,backendName:"cpu",kernelFunc:GM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EM=Et(fi,n=>Math.tan(n)),DM={kernelName:fi,backendName:"cpu",kernelFunc:EM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WM=Et(mi,n=>Math.tanh(n)),MM={kernelName:mi,backendName:"cpu",kernelFunc:WM};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VM(n){const{inputs:t,backend:e}=n,{tensor:s,indices:o,updates:r}=t,{sliceRank:i,numUpdates:a,sliceSize:c,strides:l,outputSize:u}=co(r,o,s.shape),d=!1,h=e.bufferSync(o),p=e.bufferSync(r),f=e.bufferSync(s),m=Io(h,p,s.shape,u,c,a,i,l,f,d);return e.makeTensorInfo(s.shape,m.dtype,m.values)}const FM={kernelName:Rf,backendName:"cpu",kernelFunc:VM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reps:r}=s;it(o,"tile");const i=zy(e.bufferSync(o),r);return e.makeTensorInfo(i.shape,i.dtype,i.values)}const XM={kernelName:gi,backendName:"cpu",kernelFunc:zM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{k:r,sorted:i}=s;it(o,"topk");const a=e.data.get(o.dataId).values,[c,l]=Ay(a,o.shape,o.dtype,r,i);return[e.makeTensorInfo(c.shape,c.dtype,c.values),e.makeTensorInfo(l.shape,l.dtype,l.values)]}const PM={kernelName:Pu,backendName:"cpu",kernelFunc:AM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OM(n){const{inputs:t,attrs:e,backend:s}=n,{image:o,transforms:r}=t,{interpolation:i,fillMode:a,fillValue:c,outputShape:l}=e,[u,d,h,p]=o.shape,[f,m]=l??[d,h],g=[u,f,m,p],b=ct(o.shape),x=b[0],I=b[1],y=b[2],w=ct(g),C=w[0],k=w[1],S=w[2],T=Se(o.dtype,Z(g));T.fill(c);const R=s.data.get(o.dataId).values,L=s.data.get(r.dataId).values;for(let F=0;Ft-1)if(t<=1)e=0;else{const s=2*t;e-=s*Math.trunc(e/s),e>=t&&(e=s-e-1)}return Ks(0,e,t-1)}function BM(n,t){let e=n;if(e<0)if(t<=1)e=0;else{const s=t-1;e+=t*(Math.trunc(-e/s)+1)}else if(e>t-1)if(t<=1)e=0;else{const s=t-1;e-=t*Math.trunc(e/s)}return Ks(0,e,t-1)}function HM(n,t){return n}function _M(n,t){return Ks(0,n,t-1)}function na(n,t,e,s,o,r,i,a,c,l,u){const d=i*s+a*o+c*r+l;return 0<=a&&ae.disposeIntermediateTensorInfo(f)),p}const eV={kernelName:bc,backendName:"cpu",kernelFunc:tV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nV=[jL,EG,tE,nE,zG,oE,iE,cE,uE,hE,fE,gE,xE,wE,vE,TE,RE,GE,EE,QL,WE,VE,zE,AG,AE,VG,OG,OE,DG,KE,BE,HE,UE,QE,jE,t3,n3,o3,i3,c3,u3,h3,f3,g3,b3,y3,w3,v3,S3,k3,T3,R3,L3,KL,D3,KG,P3,ZG,O3,HG,U3,Y3,J3,UG,QG,q3,eD,sD,rD,jG,tL,WG,aD,ZE,lD,dD,pD,ZL,nL,oL,mD,iL,bD,ID,CD,kD,ND,$D,GD,cL,ED,WD,VD,zD,AD,OD,ZD,uL,HD,YD,jD,hL,fL,eW,oW,aW,gL,lW,dW,hW,s1,gW,HL,yL,xW,IW,CW,SW,MG,bp,TW,_L,UL,YL,RW,GW,EW,WW,VW,FW,XW,NL,PW,HW,UW,jW,$L,tM,nM,oM,GL,QD,iM,cM,uM,hM,fM,gM,xM,IM,DL,wM,ML,FL,vM,kM,NM,$M,LM,PL,$3,DM,MM,FM,XM,PM,KM,bL,JM,qM,eV,uW];for(const n of nV)qe(n);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Co={},yl={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function sV(n,t){Co[n]=t}function Mn(n,t){if(!(n in Co)||t!=null){const s=rV(n,t);if(s!==null)Co[n]=s;else return console.log("Could not get context for WebGL version",n),null}const e=Co[n];return e==null||e.isContextLost()?(delete Co[n],Mn(n)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Co[n])}function oV(n){if(!z().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&n===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function rV(n,t){if(n!==1&&n!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const e=t??oV(n);return e.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete Co[n]},!1),z().getBool("SOFTWARE_WEBGL_ENABLED")&&(yl.failIfMajorPerformanceCaveat=!1),n===1?e.getContext("webgl",yl)||e.getContext("experimental-webgl",yl):e.getContext("webgl2",yl)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var sa;(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(sa||(sa={}));var an;(function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"})(an||(an={}));var we;(function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(we||(we={}));function oa(n,t){return[t,n]}function iV(n,t){return n*t}function Il(n){const t=Z(n),e=Math.ceil(t/4);return Ul(e)}function lr(n,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(n/2))]}function aV(n,t){const[e,s]=lr(n,t);return e*s*4}function Ip(n,t){const e=n;let s,o,r,i,a,c,l,u,d,h;return z().getNumber("WEBGL_VERSION")===2?(s=e.R32F,o=e.R16F,r=e.RGBA16F,i=e.RGBA32F,a=e.RED,l=4,u=1,d=e.HALF_FLOAT,h=e.FLOAT,c=e.RGBA8):(s=n.RGBA,o=n.RGBA,r=n.RGBA,i=e.RGBA,a=n.RGBA,l=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,h=n.FLOAT,c=n.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:r,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:c,downloadUnpackNumChannels:l,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:h}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ot(n,t){const e=t();return z().getBool("DEBUG")&&cV(n),e}function cV(n){const t=n.getError();if(t!==n.NO_ERROR)throw new Error("WebGL Error: "+hV(n,t))}const lV=596e-10,uV=65504;function dV(n){return!!(z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||lVn.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function pV(n,t){const e=ds(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(ot(n,()=>n.shaderSource(e,t)),ot(n,()=>n.compileShader(e)),n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(e)),new Error("Failed to compile vertex shader.");return e}function fV(n,t){const e=ds(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(ot(n,()=>n.shaderSource(e,t)),ot(n,()=>n.compileShader(e)),z().get("ENGINE_COMPILE_ONLY"))return e;if(n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw i1(t,n.getShaderInfoLog(e)),new Error("Failed to compile fragment shader.");return e}const mV=/ERROR: [0-9]+:([0-9]+):/g;function i1(n,t){const e=mV.exec(t);if(e==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(n);return}const s=+e[1],o=n.split(` +`),r=o.length.toString().length+2,i=o.map((d,h)=>Wo((h+1).toString(),r)+d);let a=0;for(let d=0;dn.createProgram(),"Unable to create WebGLProgram.")}function bV(n,t){if(ot(n,()=>n.linkProgram(t)),!z().get("ENGINE_COMPILE_ONLY")&&n.getProgramParameter(t,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function wp(n,t){if(ot(n,()=>n.validateProgram(t)),n.getProgramParameter(t,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function xV(n,t){const e=ds(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),ot(n,()=>n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function yV(n,t){const e=ds(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return ot(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)),ot(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function IV(n){return ds(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function wV(n,t){const e=z().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){const s=`[${n}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(n>e||t>e){const s=`[${n}x${t}]`,o=`[${e}x${e}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+o+".")}}function CV(n){return ds(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function a1(n,t,e,s,o,r,i){const a=n.getAttribLocation(t,e);return a===-1?!1:(ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,s)),ot(n,()=>n.vertexAttribPointer(a,o,n.FLOAT,!1,r,i)),ot(n,()=>n.enableVertexAttribArray(a)),!0)}function vV(n,t,e){RV(n,e),ot(n,()=>n.activeTexture(n.TEXTURE0+e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,t))}function SV(n,t,e){return ds(n,()=>n.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function kV(n,t,e){return n.getUniformLocation(t,e)}function TV(n,t,e,s){ot(n,()=>vV(n,t,s)),ot(n,()=>n.uniform1i(e,s))}function Cp(n,t,e){ot(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),ot(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0))}function c1(n,t){ot(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),ot(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function Cl(n){const t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+NV(n,t))}function NV(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function ds(n,t,e){const s=ot(n,()=>t());if(s==null)throw new Error(e);return s}function RV(n,t){const e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+n.TEXTURE0;if(se){const o=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${o}.`)}}function ur(n,t=2){return Z(n.slice(0,n.length-t))}function dr(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function vl(n){let t=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(t=[ur(n),...dr(n)]),t}function $V(n,t=!1){let e=z().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=z().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&z().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=e/2),t&&(e=e*2,s=s*2,n=n.map((a,c)=>c>=n.length-2?Bl(n[c]):n[c]),n.length===1&&(n=[2,n[0]])),n.length!==2&&(n=fs(n).newShape);let o=Z(n),r=null;n.length<=1&&o<=e?r=[1,o]:n.length===2&&n[0]<=e&&n[1]<=e?r=n:n.length===3&&n[0]*n[1]<=e&&n[2]<=e?r=[n[0]*n[1],n[2]]:n.length===3&&n[0]<=e&&n[1]*n[2]<=e?r=[n[0],n[1]*n[2]]:n.length===4&&n[0]*n[1]*n[2]<=e&&n[3]<=e?r=[n[0]*n[1]*n[2],n[3]]:n.length===4&&n[0]<=e&&n[1]*n[2]*n[3]<=e&&(r=[n[0],n[1]*n[2]*n[3]]);const i=r!=null&&Math.max(...r)>s&&Math.min(...r)<=(t?2:1)&&Math.min(...r)>0;if(r==null||i)if(t){const a=ur(n);let c=2,l=2;n.length&&([c,l]=dr(n)),o=a*(c/2)*(l/2),r=Ul(o).map(u=>u*2)}else r=Ul(o);return r}function Sl(n){return n%2===0}function kl(n,t){if(n=n.slice(-2),t=t.slice(-2),Rt(n,t)||!n.length||!t.length||n[0]===0||n[1]===0||t[0]===0||t[1]===0)return!0;if(n.length!==t.length){const e=n[n.length-1],s=t[t.length-1];if(e===s||Sl(e)&&Sl(s)&&(n[0]===1||t[0]===1))return!0}return n[1]===t[1]&&Sl(n[0])&&Sl(t[0])}let vp,Sp;function GV(n){if(vp==null){const t=Mn(n);vp=t.getParameter(t.MAX_TEXTURE_SIZE)}return vp}function LV(n){if(Sp==null){const t=Mn(n);Sp=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Sp)}function EV(n){if(n===0)return 0;let t;const e=Mn(n);return wn(e,"EXT_disjoint_timer_query_webgl2")&&n===2?t=2:wn(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function wn(n,t){return n.getExtension(t)!=null}function l1(n){try{if(Mn(n)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function DV(n){if(n===0)return!1;const t=Mn(n);if(n===1){if(!wn(t,"OES_texture_float"))return!1}else if(!wn(t,"EXT_color_buffer_float"))return!1;return kp(t)}function WV(n){if(n===0)return!1;const t=Mn(n);if(n===1){if(!wn(t,"OES_texture_float")||!wn(t,"WEBGL_color_buffer_float"))return!1}else{if(wn(t,"EXT_color_buffer_float"))return kp(t);const s="EXT_color_buffer_half_float";if(wn(t,s)){const o=t.getExtension(s);return MV(t,o)}return!1}return kp(t)}function kp(n){const t=Ip(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,r),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);const i=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(r),i}function MV(n,t){const e=Ip(n,t),s=n.createTexture();n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,1,1,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);const i=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,i),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,s,0);const a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(s),n.deleteFramebuffer(i),a}function VV(n){return n!==2?!1:Mn(n).fenceSync!=null}function ra(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&v(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const at=z();at.registerFlag("HAS_WEBGL",()=>at.getNumber("WEBGL_VERSION")>0),at.registerFlag("WEBGL_VERSION",()=>l1(2)?2:l1(1)?1:0),at.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),at.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>at.get("WEBGL_VERSION")===2),at.registerFlag("WEBGL_CPU_FORWARD",()=>!0),at.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),at.registerFlag("WEBGL_PACK",()=>at.getBool("HAS_WEBGL")),at.registerFlag("WEBGL_PACK_NORMALIZATION",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_CLIP",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_REDUCE",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_LAZILY_UNPACK",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_CONV_IM2COL",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>GV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>LV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=at.getNumber("WEBGL_VERSION");return n===0?0:EV(n)}),at.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>at.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!hm()),at.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>DV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>at.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:at.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),at.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>WV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_FENCE_API_ENABLED",()=>VV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>at.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),at.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)}),at.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>hm()?1:-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)}),at.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),at.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),at.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),at.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),at.registerFlag("WEBGL_EXP_CONV",()=>!1),at.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>at.getBool("IS_TEST")),at.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),at.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),at.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),at.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function De(){let n,t,e,s,o,r,i,a,c,l;return z().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",s="in",o="texture",r="outputColor",i="out vec4 outputColor;",a=z().getBool("WEBGL2_ISNAN_CUSTOM")?` + bool isnan_custom(float val) { + uint floatToUint = floatBitsToUint(val); + return (floatToUint & 0x7fffffffu) > 0x7f800000u; + } + + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan_custom(val.x), + isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); + } + + #define isnan(value) isnan_custom(value) + `:"",c="",l=` + #define round(value) newRound(value) + int newRound(float value) { + return int(floor(value + 0.5)); + } + + ivec4 newRound(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `):(n="",t="attribute",e="varying",s="varying",o="texture2D",r="gl_FragColor",i="",a=` + #define isnan(value) isnan_custom(value) + bool isnan_custom(float val) { + return (val > 0. || val < 1. || val == 0.) ? false : true; + } + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); + } + `,c=` + uniform float INFINITY; + + bool isinf(float val) { + return abs(val) == INFINITY; + } + bvec4 isinf(vec4 val) { + return equal(abs(val), vec4(INFINITY)); + } + `,l=` + int round(float value) { + return int(floor(value + 0.5)); + } + + ivec4 round(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `),{version:n,attribute:t,varyingVs:e,varyingFs:s,texture2D:o,output:r,defineOutput:i,defineSpecialNaN:a,defineSpecialInf:c,defineRound:l}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vo(n,t,e="index"){const s=ct(t);return s.map((o,r)=>{const i=`int ${n[r]} = ${e} / ${o}`,a=r===s.length-1?`int ${n[r+1]} = ${e} - ${n[r]} * ${o}`:`index -= ${n[r]} * ${o}`;return`${i}; ${a};`}).join("")}function Tl(n,t,e="index"){const s=ct(t);return s.map((o,r)=>{const i=`int ${n[r]} = ${e} / outShapeStrides[${r}]`,a=r===s.length-1?`int ${n[r+1]} = ${e} - ${n[r]} * outShapeStrides[${r}]`:`index -= ${n[r]} * outShapeStrides[${r}]`;return`${i}; ${a};`}).join("")}function FV(n,t){const e=n.length,s=n.map(r=>`${t}[${r}]`),o=new Array(e-1);o[e-2]=s[e-1];for(let r=e-3;r>=0;--r)o[r]=`(${o[r+1]} * ${s[r+1]})`;return o}function zV(n,t,e="index"){const s=n.map((r,i)=>i),o=FV(s,t);return o.map((r,i)=>{const a=`int ${n[i]} = ${e} / ${o[i]}`,c=i===o.length-1?`int ${n[i+1]} = ${e} - ${n[i]} * ${o[i]}`:`index -= ${n[i]} * ${o[i]}`;return`${a}; ${c};`}).join("")}function Tp(n){const t=ct(n).map(e=>e.toString());return` + int getFlatIndex(ivec3 coords) { + return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z; + } +`}function Np(){return` + int getFlatIndex(ivec3 coords) { + return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z; + } +`}const u1=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + lowp vec4 encode_float(highp float v) { + if (isnan(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } +`;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{getBroadcastDims:d1}=DT;function XV(n,t,e){const s=[];if(n.forEach(p=>{const f=Z(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?s.push(`uniform float ${p.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${p.name};`),s.push(`uniform int offset${p.name};`)),e.enableShapeUniforms){const{uniformShape:m}=Rp(e.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(m.length){case 1:s.push(`uniform int ${p.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${p.name}Shape;`);break}s.push(`uniform ivec2 ${p.name}TexShape;`)}}),e.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break}s.push("uniform ivec2 outTexShape;")}e.customUniforms&&e.customUniforms.forEach(p=>{s.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});const o=s.join(` +`),r=n.map(p=>AV(p,t,e.packedInputs,e.enableShapeUniforms)).join(` +`),i=t.texShape,a=De(),c=KV(a);let l,u,d=HV(a);return t.isPacked?(l=PV(t.logicalShape,i,e.enableShapeUniforms),u=BV(a)):(l=OV(t.logicalShape,i,e.enableShapeUniforms),u=ZV(a)),e.packedInputs&&(d+=QV),[d,c,u,o,l,r,e.userCode].join(` +`)}function hr(n,t=!1){const e=n.shapeInfo.logicalShape;switch(e.length){case 0:return cF(n,t);case 1:return uF(n,t);case 2:return hF(n,t);case 3:return fF(n,t);case 4:return gF(n,t);case 5:return bF(n);case 6:return xF(n);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function h1(n,t){switch(n.shapeInfo.logicalShape.length){case 0:return aF(n);case 1:return lF(n,t);case 2:return dF(n,t);case 3:return pF(n,t);default:return mF(n,t)}}function AV(n,t,e=!1,s){let o="";e?o+=h1(n,s):o+=hr(n,s);const r=n.shapeInfo.logicalShape,i=t.logicalShape;return r.length<=i.length&&(e?o+=yF(n,t):o+=IF(n,t)),o}function PV(n,t,e){switch(n.length){case 0:return p1();case 1:return JV(n,t,e);case 2:return rF(n,t,e);case 3:return qV(n,t,e);default:return eF(n,t,e)}}function OV(n,t,e){switch(n.length){case 0:return p1();case 1:return jV(n,t,e);case 2:return iF(n,t,e);case 3:return tF(n,t,e);case 4:return nF(n,t,e);case 5:return sF(n,t);case 6:return oF(n,t);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function KV(n){return` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${n.texture2D}(textureSampler, uv).r; + } + `}function ZV(n){return` + void setOutput(float val) { + ${n.output} = vec4(val, 0, 0, 0); + } + `}function BV(n){return` + void setOutput(vec4 val) { + ${n.output} = val; + } + `}function HV(n){return`${n.version} + precision highp float; + precision highp int; + precision highp sampler2D; + ${n.varyingFs} vec2 resultUV; + ${n.defineOutput} + const vec2 halfCR = vec2(0.5, 0.5); + + struct ivec5 + { + int x; + int y; + int z; + int w; + int u; + }; + + struct ivec6 + { + int x; + int y; + int z; + int w; + int u; + int v; + }; + + uniform float NAN; + ${n.defineSpecialNaN} + ${n.defineSpecialInf} + ${n.defineRound} + + int imod(int x, int y) { + return x - y * (x / y); + } + + int idiv(int a, int b, float sign) { + int res = a / b; + int mod = imod(a, b); + if (sign < 0. && mod != 0) { + res -= 1; + } + return res; + } + + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + #define HASHSCALE1 443.8975 + float random(float seed){ + vec2 p = resultUV * seed; + vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 += dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${_V} + ${UV} + ${YV} + `}const _V=` +vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,UV=` +vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, + int texNumC, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,YV=` +vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,QV=` + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + float getChannel(vec4 frag, int dim) { + float modCoord = mod(float(dim), 2.); + return modCoord == 0. ? frag.r : frag.g; + } +`;function p1(){return` + int getOutputCoords() { + return 0; + } + `}function JV(n,t,e){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?e?` + int getOutputCoords() { + return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.x * ${s[1]}.0); + } + `:s[1]===1?e?` + int getOutputCoords() { + return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.y * ${s[0]}.0); + } + `:e?` + int getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + return 2 * (resTexRC.x * ${s[1]} + resTexRC.y); + } + `}function jV(n,t,e){return t[0]===1?e?` + int getOutputCoords() { + return int(resultUV.x * float(outTexShape[1])); + } + `:` + int getOutputCoords() { + return int(resultUV.x * ${t[1]}.0); + } + `:t[1]===1?e?` + int getOutputCoords() { + return int(resultUV.y * float(outTexShape[0])); + } + `:` + int getOutputCoords() { + return int(resultUV.y * ${t[0]}.0); + } + `:e?` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + return resTexRC.x * outTexShape[1] + resTexRC.y; + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${t[0]}, ${t[1]})); + return resTexRC.x * ${t[1]} + resTexRC.y; + } + `}function qV(n,t,e){if(e)return` + ivec3 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec3(b, r, c); + } + `;const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(n[2]/2),r=o*Math.ceil(n[1]/2);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + int index = resTexRC.x * ${s[1]} + resTexRC.y; + + int b = index / ${r}; + index -= b * ${r}; + + int r = 2 * (index / ${o}); + int c = imod(index, ${o}) * 2; + + return ivec3(b, r, c); + } + `}function tF(n,t,e){if(e)return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + int index = resTexRC.x * outTexShape[1] + resTexRC.y; + ${Tl(["r","c","d"],n)} + return ivec3(r, c, d); + } +`;const s=vo(["r","c","d"],n);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.x * ${t[1]} + resTexRC.y; + ${s} + return ivec3(r, c, d); + } + `}function eF(n,t,e){if(e)return` + ivec4 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatchN = texelsInBatch * outShape[1]; + + int b2 = index / texelsInBatchN; + index -= b2 * texelsInBatchN; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec4(b2, b, r, c); + } + `;const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(n[n.length-1]/2),r=o*Math.ceil(n[n.length-2]/2);let i=r,a="",c="b, r, c";for(let l=2;l=1?u="coords = 0;":u=a.map(x=>`coords.${d[x+l]} = 0;`).join(` +`);let h="";i<2&&r>0?h="coords":h=n.shapeInfo.logicalShape.map((x,I)=>`coords.${d[I+l]}`).join(", ");let p="return outputValue;";const m=Z(n.shapeInfo.logicalShape)===1,b=Z(t.logicalShape)===1;if(r===1&&!m&&!b)p=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(m&&!b)i===1?p=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:p=` + return vec4(outputValue.x); + `;else if(a.length){const x=r-2,I=r-1;a.indexOf(x)>-1&&a.indexOf(I)>-1?p="return vec4(outputValue.x);":a.indexOf(x)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(I)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return` + vec4 ${o}() { + ${c} coords = getOutputCoords(); + ${u} + vec4 outputValue = get${s}(${h}); + ${p} + } + `}function IF(n,t){const e=n.name,s=e.charAt(0).toUpperCase()+e.slice(1),o="get"+s+"AtOutCoords",r=t.texShape,i=n.shapeInfo.texShape,a=n.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!n.shapeInfo.isUniform&&a===c&&n.shapeInfo.flatOffset==null&&Rt(i,r))return` + float ${o}() { + return sampleTexture(${e}, resultUV); + } + `;const l=Wt(c),u=d1(n.shapeInfo.logicalShape,t.logicalShape),d=c-a;let h;const p=["x","y","z","w","u","v"];a===0?h="":c<2&&u.length>=1?h="coords = 0;":h=u.map(m=>`coords.${p[m+d]} = 0;`).join(` +`);let f="";return c<2&&a>0?f="coords":f=n.shapeInfo.logicalShape.map((m,g)=>`coords.${p[g+d]}`).join(", "),` + float ${o}() { + ${l} coords = getOutputCoords(); + ${h} + return get${s}(${f}); + } + `}function Wt(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function Rp(n,t,e){const{newShape:s,keptDims:o}=fs(t),r=t.length,i=n&&r===3&&t[0]===1,a=i?t.slice(1):s,c=!n&&r>1&&!Rt(t,e)&&s.lengthn[e]).join(", ")}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wF(n,t,e,s){const o=e.map((u,d)=>{const h={logicalShape:u.shape,texShape:u.isUniform?null:u.texData.texShape,isUniform:u.isUniform,isPacked:u.isUniform?!1:u.texData.isPacked,flatOffset:null};return u.texData!=null&&u.texData.slice!=null&&u.texData.slice.flatOffset>0&&(h.flatOffset=u.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:h}}),r=o.map(u=>u.shapeInfo),i={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},a=XV(o,i,t),c=fV(n.gl,a),l=n.createProgram(c);return z().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:c,source:a,webGLProgram:l,inShapeInfos:r,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(n.buildVao(l),Object.assign({program:t,fragmentShader:c,source:a,webGLProgram:l,inShapeInfos:r,outShapeInfo:i},f1(n,t,l)))}function f1(n,t,e){const s=[],o=[];let r,i,a,c=null,l=null;l=n.getUniformLocation(e,"NAN",!1),z().getNumber("WEBGL_VERSION")===1&&(c=n.getUniformLocation(e,"INFINITY",!1));const u=!1;for(const d of t.variableNames){const h={name:d,uniform:n.getUniformLocation(e,d,u),offset:n.getUniformLocation(e,`offset${d}`,u)};t.enableShapeUniforms&&(h.shape=n.getUniformLocation(e,`${d}Shape`,u),h.texShape=n.getUniformLocation(e,`${d}TexShape`,u)),s.push(h)}if(t.enableShapeUniforms&&(r=n.getUniformLocation(e,"outShape",u),a=n.getUniformLocation(e,"outShapeStrides",u),i=n.getUniformLocation(e,"outTexShape",u)),t.customUniforms)for(const d of t.customUniforms)o.push(n.getUniformLocation(e,d.name,u));return{variablesLocations:s,customUniformLocations:o,infLoc:c,nanLoc:l,outShapeLocation:r,outShapeStridesLocation:a,outTexShapeLocation:i}}function m1(n,t){if(n.length!==t.length)throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${t.length} inputs`);n.forEach((e,s)=>{const o=e.logicalShape,r=t[s],i=r.shape;if(!Rt(o,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);if(e.isUniform&&r.isUniform)return;const a=e.texShape,c=r.isUniform?null:r.texData.texShape;if(!Rt(a,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${c} must match`)})}function CF(n,t,e,s,o){t.program.enableShapeUniforms||(m1(t.inShapeInfos,e),m1([t.outShapeInfo],[s]));const r=s.texData.texture,i=s.texData.texShape;s.texData.isPacked?n.setOutputPackedMatrixTexture(r.texture,i[0],i[1]):n.setOutputMatrixTexture(r.texture,i[0],i[1]),n.setProgram(t.webGLProgram),n.bindVertexArray(t.webGLProgram.vao),z().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&n.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&n.gl.uniform1f(t.nanLoc,NaN);for(let c=0;c{const a=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(n.enableShapeUniforms&&!i.isUniform){const c=i.texData.texShape,{useSqueezeShape:l,uniformShape:u,keptDims:d}=Rp(n.packedInputs,i.shape,c);let h="",p="",f="";if(u.length===1&&n.packedInputs){const w=[Math.ceil(c[0]/2),Math.ceil(c[1]/2)];h=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!n.packedInputs)p=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!n.packedInputs){const w=ct(u);f=`${w[0]===c[1]}_${w[w.length-1]===c[1]}`}const m=i.shape.length,g=u.length===2&&Rt(i.shape,c),b=Z(i.shape)===1,x=Uo(i.shape,e.shape),I=!n.packedInputs&&m===e.shape.length&&Rt(c,e.texData.texShape),y=n.packedInputs||u.length>2?"":`${c[0]>1}_${c[1]>1}`;s+=`${m}_${I}_${l?d:""}_${u.length}_${b}_${x}_${g}_${h}_${p}_${f}_${y}_${a}`}else{const c=i.isUniform?"uniform":i.texData.texShape;s+=`${i.shape}_${c}_${a}`}});const o=n.userCode;let r=n.constructor.name;return r+="_"+s+"_"+o+`${z().getNumber("WEBGL_VERSION")}`,r}function Ne(n){return z().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class SF{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=sa.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?Tl(["r","c","d"],t):vo(["r","c","d"],t)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getA(rc.x, rc.y, rc.z); + } + + ${e.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kF{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=sa.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?Tl(["r","c","d"],t):vo(["r","c","d"],t)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z)); + } + + ${e.output} = result; + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class TF{constructor(t){this.variableNames=["A"],this.outTexUsage=an.DOWNLOAD;const e=De();this.outputShape=t,this.userCode=` + ${u1} + + void main() { + float x = getAAtOutCoords(); + ${e.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class NF{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=an.DOWNLOAD;const e=De();this.outputShape=t,this.userCode=` + ${u1} + + void main() { + ivec3 coords = getOutputCoords(); + float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); + ${e.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RF={R:0,G:1,B:2,A:3};class g1{constructor(t,e=!1,s="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const o=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);let r="result";e&&(r="floor(result * 255. + 0.5)");let i="";for(let a=0;an.bindTexture(a,i)),ot(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),ot(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),ot(n,()=>n.texParameteri(a,n.TEXTURE_MIN_FILTER,n.NEAREST)),ot(n,()=>n.texParameteri(a,n.TEXTURE_MAG_FILTER,n.NEAREST)),z().getNumber("WEBGL_VERSION")===1?ot(n,()=>n.texImage2D(a,0,s,t,e,0,o,r,null)):ot(n,()=>n.texStorage2D(a,1,s,t,e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:i,texShape:[e,t]}}function b1(n){return n.internalFormatFloat}function DF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,b1(s),s.textureFormatFloat,n.FLOAT)}function x1(n){return n.internalFormatHalfFloat}function WF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,x1(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function y1(n){return n.downloadTextureFormat}function MF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,y1(s),n.RGBA,n.UNSIGNED_BYTE)}function I1(n){return n.internalFormatPackedFloat}function VF(n,t,e,s){const[o,r]=lr(t,e);return ia(n,o,r,I1(s),n.RGBA,n.FLOAT)}function w1(n){return n.internalFormatPackedHalfFloat}function FF(n,t,e,s){const[o,r]=lr(t,e);return ia(n,o,r,w1(s),n.RGBA,s.textureTypeHalfFloat)}function zF(n,t,e){return ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),a1(n,t,"clipSpacePos",e,3,20,0)&&a1(n,t,"uv",e,2,20,12)}function XF(n,t,e,s,o,r){ot(n,()=>n.bindTexture(n.TEXTURE_2D,t));let i,a,c;o instanceof Uint8Array?(i=new Uint8Array(e*s*4),a=n.UNSIGNED_BYTE,c=n.RGBA):(i=new Float32Array(e*s*4),a=n.FLOAT,c=r.internalFormatPackedFloat),i.set(o),z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,s,n.RGBA,a,i)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,c,e,s,0,n.RGBA,a,i)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function AF(n,t,e){ot(n,()=>n.bindTexture(n.TEXTURE_2D,t)),e.data instanceof Uint8Array?z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,e.data)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)):z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,e)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function PF(n,t,e,s){const o=n.createBuffer();ot(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,o));const a=4*4*t*e;return ot(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,a,n.STREAM_READ)),ot(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)),ot(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),o}function OF(n,t,e){const s=n,o=new Float32Array(e);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,o),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),o}function KF(n,t,e,s){const[o,r]=oa(t,e),i=4,a=new Uint8Array(iV(t*e,i));return ot(n,()=>n.readPixels(0,0,o,r,s.downloadTextureFormat,n.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function ZF(n,t,e,s,o,r,i,a){const c=n,l=new Float32Array(aV(r,i));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function BF(n,t,e){const s=new Float32Array(t*e*4);return ot(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,s)),s}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $p{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const e=z().getNumber("WEBGL_VERSION");if(t!=null?(this.gl=t,sV(e,t)):this.gl=Mn(e),t=this.gl,z().getNumber("WEBGL_VERSION")===2){const r=t;this.createVertexArray=()=>ot(r,()=>r.createVertexArray()),this.bindVertexArray=i=>ot(r,()=>r.bindVertexArray(i)),this.deleteVertexArray=i=>ot(r,()=>r.deleteVertexArray(i)),this.getVertexArray=()=>ot(r,()=>r.getParameter(r.VERTEX_ARRAY_BINDING))}else if(t!=null){const r=t.getExtension("OES_vertex_array_object");if(r==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>ot(t,()=>r.createVertexArrayOES()),this.bindVertexArray=i=>ot(t,()=>r.bindVertexArrayOES(i)),this.deleteVertexArray=i=>ot(t,()=>r.deleteVertexArrayOES(i)),this.getVertexArray=()=>ot(t,()=>t.getParameter(r.VERTEX_ARRAY_BINDING_OES))}let s="WEBGL_color_buffer_float";const o="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),z().getNumber("WEBGL_VERSION")===1){const r="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=wl(this.gl,r),wn(this.gl,i))this.textureHalfFloatExtension=wl(this.gl,i);else if(z().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(s),wn(this.gl,o))this.colorBufferHalfFloatExtension=wl(this.gl,o);else if(z().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(s="EXT_color_buffer_float",wn(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(wn(this.gl,o))this.colorBufferHalfFloatExtension=this.gl.getExtension(o);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=LF(this.gl),this.indexBuffer=EF(this.gl),this.framebuffer=CV(this.gl),this.textureConfig=Ip(this.gl,this.textureHalfFloatExtension)}get debug(){return z().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const t=this.gl;ot(t,()=>t.finish()),ot(t,()=>t.bindFramebuffer(t.FRAMEBUFFER,null)),ot(t,()=>t.deleteFramebuffer(this.framebuffer)),ot(t,()=>t.bindBuffer(t.ARRAY_BUFFER,null)),ot(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),ot(t,()=>t.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(t,e){return this.throwIfDisposed(),DF(this.gl,t,e,this.textureConfig)}createFloat16MatrixTexture(t,e){return this.throwIfDisposed(),WF(this.gl,t,e,this.textureConfig)}createUnsignedBytesMatrixTexture(t,e){return this.throwIfDisposed(),MF(this.gl,t,e,this.textureConfig)}uploadPixelDataToTexture(t,e){this.throwIfDisposed(),AF(this.gl,t,e)}uploadDenseMatrixToTexture(t,e,s,o){this.throwIfDisposed(),XF(this.gl,t,e,s,o,this.textureConfig)}createFloat16PackedMatrixTexture(t,e){return this.throwIfDisposed(),FF(this.gl,t,e,this.textureConfig)}createPackedMatrixTexture(t,e){return this.throwIfDisposed(),VF(this.gl,t,e,this.textureConfig)}deleteMatrixTexture(t){this.throwIfDisposed(),this.outputTexture===t&&(c1(this.gl,this.framebuffer),this.outputTexture=null),ot(this.gl,()=>this.gl.deleteTexture(t))}downloadByteEncodedFloatMatrixFromOutputTexture(t,e,s){return this.downloadMatrixDriver(t,()=>KF(this.gl,e,s,this.textureConfig))}downloadPackedMatrixFromBuffer(t,e,s,o,r,i){return ZF(this.gl,t,e,s,o,r,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(t,e){return OF(this.gl,t,e)}createBufferFromTexture(t,e,s){this.bindTextureToFrameBuffer(t);const o=PF(this.gl,e,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),o}createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,s;if(z().getBool("WEBGL_FENCE_API_ENABLED")){const o=t,r=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),s=()=>{const i=o.clientWaitSync(r,0,0);return i===o.ALREADY_SIGNALED||i===o.CONDITION_SATISFIED},e=r}else z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(e,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:e,isFencePassed:s}}downloadMatrixFromPackedTexture(t,e,s){return this.downloadMatrixDriver(t,()=>BF(this.gl,e,s))}createProgram(t){this.throwIfDisposed();const e=this.gl;this.vertexShader==null&&(this.vertexShader=GF(e));const s=gV(e);ot(e,()=>e.attachShader(s,this.vertexShader)),ot(e,()=>e.attachShader(s,t)),bV(e,s);const o=Object.assign(s,{vao:this.createVertexArray()});return this.debug&&wp(e,o),o}buildVao(t){this.setProgram(t),this.bindVertexArray(t.vao);const e=this.gl;ot(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),zF(e,t,this.vertexBuffer)}deleteProgram(t){this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&(ot(this.gl,()=>this.gl.deleteProgram(t)),this.deleteVertexArray(t.vao))}setProgram(t){this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&wp(this.gl,this.program),ot(this.gl,()=>this.gl.useProgram(t))}getUniformLocation(t,e,s=!0){return this.throwIfDisposed(),s?SV(this.gl,t,e):kV(this.gl,t,e)}getAttributeLocation(t,e){return this.throwIfDisposed(),ot(this.gl,()=>this.gl.getAttribLocation(t,e))}getUniformLocationNoThrow(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)}setInputMatrixTexture(t,e,s){this.throwIfDisposed(),this.throwIfNoProgram(),TV(this.gl,t,e,s)}setOutputMatrixTexture(t,e,s){this.setOutputMatrixTextureDriver(t,s,e)}setOutputPackedMatrixTexture(t,e,s){this.throwIfDisposed();const[o,r]=lr(e,s);this.setOutputMatrixTextureDriver(t,o,r)}setOutputMatrixWriteRegion(t,e,s,o){this.setOutputMatrixWriteRegionDriver(s,t,o,e)}setOutputPackedMatrixWriteRegion(t,e,s,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&wp(this.gl,this.program),Cl(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const t=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}ot(t,()=>t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ot(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=wl(this.gl,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,o=this.getQueryTimerExtensionWebGL2(),r=s.createQuery();return s.beginQuery(o.TIME_ELAPSED_EXT,r),r}const t=this.getQueryTimerExtensionWebGL1(),e=t.createQueryEXT();return t.beginQueryEXT(t.TIME_ELAPSED_EXT,e),e}endQuery(){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const e=this.gl,s=this.getQueryTimerExtensionWebGL2();e.endQuery(s.TIME_ELAPSED_EXT);return}const t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(t){return await uf(()=>this.disposed||this.isQueryAvailable(t,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(t,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(t,e){if(e===0)return null;if(e===2){const s=this.gl;return s.getQueryParameter(t,s.QUERY_RESULT)/1e6}else{const s=this.getQueryTimerExtensionWebGL1();return s.getQueryObjectEXT(t,s.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(t,e){if(e===0)return!0;if(e===2){const s=this.gl,o=this.getQueryTimerExtensionWebGL2(),r=s.getQueryParameter(t,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),o=s.getQueryObjectEXT(t,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),o&&!this.disjoint}}pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){const t=HF(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){const{resolveFn:s}=this.itemsToPoll[e];s()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}addItemToPoll(t,e){if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;let s;"setTimeoutCustom"in z().platform&&(s=z().platform.setTimeoutCustom.bind(z().platform)),uf(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,s)}bindTextureToFrameBuffer(t){this.throwIfDisposed(),Cp(this.gl,t,this.framebuffer),this.debug&&Cl(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Cp(this.gl,this.outputTexture,this.framebuffer),this.debug&&Cl(this.gl)):c1(this.gl,this.framebuffer)}downloadMatrixDriver(t,e){this.bindTextureToFrameBuffer(t);const s=e();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(t,e,s){this.throwIfDisposed();const o=this.gl;Cp(o,t,this.framebuffer),this.debug&&Cl(o),this.outputTexture=t,ot(o,()=>o.viewport(0,0,e,s)),ot(o,()=>o.scissor(0,0,e,s))}setOutputMatrixWriteRegionDriver(t,e,s,o){this.throwIfDisposed(),ot(this.gl,()=>this.gl.scissor(t,e,s,o))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function HF(n){let t=0;for(;t`${n}.${e}`)}function We(n,t){return t===1?[n]:k1(n,t)}function zz(n,t){if(n===1)return"rc";let e="";for(let s=0;s ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let e="";for(let s=this.rank-2;s= ${this.enableShapeUniforms?`outShape[${s}]`:this.outputShape[s]}`,s= ${s}; + bool rEdge = rp1 >= ${o}; + `}getOutput(t){const e=this.getSourceCoordsArr(t);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${e[0]}), + cEdge ? 0. : getA(${e[1]}), + rEdge ? 0. : getA(${e[2]}), + rEdge || cEdge ? 0. : getA(${e[3]})`}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class T1{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);let s="";for(let o=0;o<4;o++){let r="thisRC = rc;";o%2===1&&(r+="thisRC.z += 1;"),o>1&&(r+="thisRC.y += 1;"),s+=` + ${r} + ${o>0?"if(thisRC.y < rows && thisRC.z < cols){":""} + int flatIndex = getFlatIndex(thisRC); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); + vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${o}] = + getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); + ${o>0?"}":""} + `}this.userCode=` + ${Az(e,this.enableShapeUniforms)} + ${this.enableShapeUniforms?Np():Tp(t)} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.); + + ivec3 thisRC; + int rows = ${this.enableShapeUniforms?"outShape[1]":t[1]}; + int cols = ${this.enableShapeUniforms?"outShape[2]":t[2]}; + + ${s} + + setOutput(result); + } + `}}function Az(n,t){return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${t?zV(["r","c","d"],"inputShape"):vo(["r","c","d"],n)} + return ivec3(r, c, d); + } + `}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Pz{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(t,e,s){const o=R1(e,s),r=$1(t,o,s);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const i=N1(t,o,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();const c=this.freeTextures[r].pop();return this.usedTextures[r].push(c),c}let a;return o===we.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===we.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===we.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===we.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===we.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[r].push(a),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),a}releaseTexture(t,e,s,o){if(this.freeTextures==null)return;const r=R1(s,o),i=$1(e,r,o);i in this.freeTextures||(this.freeTextures[i]=[]);const a=N1(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,o),c=z().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(t.texture),this._numBytesAllocated-=a):(this.freeTextures[i].push(t),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const l=this.usedTextures[i],u=l&&l.indexOf(t);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),this.log()}log(){if(!this.logEnabled)return;const t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);const e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(const t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(const t in this.usedTextures)this.usedTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function Oz(n,t){const e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;if(t===e.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function N1(n,t,e,s,o){const r=Kz(t,s);let i;if(o){const[c,l]=lr(n[0],n[1]);i=c*l}else{const[c,l]=oa(n[0],n[1]);i=c*l}const a=Oz(e,r);return i*a}function Kz(n,t){switch(n){case we.PACKED_2X2_FLOAT32:return I1(t);case we.PACKED_2X2_FLOAT16:return w1(t);case we.UNPACKED_FLOAT32:return b1(t);case we.UNPACKED_FLOAT16:return x1(t);case we.PACKED_4X1_UNSIGNED_BYTE:return y1(t);default:throw new Error(`Unknown physical texture type ${n}`)}}function Zz(n){return z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?we.PACKED_2X2_FLOAT32:we.UNPACKED_FLOAT32:n?we.PACKED_2X2_FLOAT16:we.UNPACKED_FLOAT16}function R1(n,t){if(n===an.UPLOAD)return we.PACKED_2X2_FLOAT32;if(n===an.RENDER||n==null)return Zz(t);if(n===an.DOWNLOAD||n===an.PIXELS)return we.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function $1(n,t,e){return`${n[0]}_${n[1]}_${t}_${e}`}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jn{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=` + float unaryOperation(float x) { + ${e} + } + + void main() { + float x = getAAtOutCoords(); + float y = unaryOperation(x); + + setOutput(y); + } + `}}const Cn="if (isnan(x)) return x;",Bz="return x;",G1="return abs(x);",Hz="return (x >= 0.0) ? x : (exp(x) - 1.0);",_z=Cn+` + return (x < 0.0) ? 0.0 : x; +`,Uz=Cn+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,Vs="return x;",Yz="return 1.0 / (1.0 + exp(-1.0 * x));";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qz="return x;",Jz=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,jz=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,qz=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,tX="return 1.0 / (1.0 + exp(-1.0 * x));";class Fs{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=` + vec4 unaryOperation(vec4 x) { + ${e} + } + + void main() { + vec4 x = getAAtOutCoords(); + vec4 y = unaryOperation(x); + + setOutput(y); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eX{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);const e=t.length,s=We("rc",e),o=Wt(e),r=zz(e,s),i=s.slice(-2),a=e<=1?"rc":`vec2(${i.join(",")})`;this.userCode=` + void main() { + ${o} rc = getOutputCoords(); + vec4 packedInput = getA(${r}); + + setOutput(getChannel(packedInput, ${a})); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nX=rg,sX=1e-7,oX=1e-4,Nl={};function rX(n){return n in Nl||(Nl[n]={}),Nl[n]}const iX=z().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),aX=600;function cX(){return z().global.screen==null?1024:z().global.screen.height*z().global.screen.width*window.devicePixelRatio*aX/1024/1024}class Rl extends Zl{nextDataId(){return Rl.nextDataId++}constructor(t){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!z().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let e;if(t!=null){if(t instanceof $p)e=t;else{const s=Mn(z().getNumber("WEBGL_VERSION"),t);e=new $p(s)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const s=Mn(z().getNumber("WEBGL_VERSION"));e=new $p(s),this.binaryCache=rX(z().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=e,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Pz(this.gpgpu),this.numMBBeforeWarning=cX(),this.texData=new lf(this,zt())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,e,s,o,r,i){const a=this.makeTensorInfo(e,s),c=this.texData.get(a.dataId);c.isPacked=!1,c.texture={texture:t,texShape:[o,r]},c.texShape=[o,r];const l=vl(e),u=new g1(l,!1,i),d=this.runWebGLProgram(u,[a],s,[[o,r]]);return d.shape=e,c.texture=null,this.disposeIntermediateTensorInfo(a),d.dataId}write(t,e,s){if((z().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||z().getBool("DEBUG"))&&this.checkNumericalProblems(t),s==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const o={id:this.nextDataId()};return this.texData.set(o,{shape:e,dtype:s,values:t,usage:an.UPLOAD,refCount:1}),o}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){const e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){const e=this.texData.get(t);e.refCount--}}move(t,e,s,o,r){if(z().getBool("DEBUG")&&this.checkNumericalProblems(e),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:s,dtype:o,values:e,usage:an.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){const e=this.texData.get(t),{values:s,dtype:o,complexTensorInfos:r,slice:i,shape:a,isPacked:c}=e;if(i!=null){let h;c?h=new Fs(a,Vs):h=new jn(a,Vs);const p=this.runWebGLProgram(h,[{dataId:t,shape:a,dtype:o}],o),f=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),f}if(s!=null)return this.convertAndCacheOnCPU(t);if(o==="string")return s;const l=this.activeTimers!=null;let u;l&&(u=Ve());let d;if(o==="complex64"){const h=this.readSync(r.real.dataId),p=this.readSync(r.imag.dataId);d=as(h,p)}else d=this.getValuesFromTexture(t);return l&&(this.downloadWaitMs+=Ve()-u),this.convertAndCacheOnCPU(t,d)}async read(t){if(this.pendingRead.has(t)){const f=this.pendingRead.get(t);return new Promise(m=>f.push(m))}const e=this.texData.get(t),{values:s,shape:o,slice:r,dtype:i,complexTensorInfos:a,isPacked:c}=e;if(r!=null){let f;c?f=new Fs(o,Vs):f=new jn(o,Vs);const m=this.runWebGLProgram(f,[{dataId:t,shape:o,dtype:i}],i),g=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),g}if(s!=null)return this.convertAndCacheOnCPU(t);if(z().getBool("DEBUG")&&!z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&z().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,u;if(i!=="complex64"&&z().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(t);const f=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(f.texture.texture,...Il(o))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(i==="complex64"){const f=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),m=f[0],g=f[1];d=as(m,g)}else if(l==null)d=this.getValuesFromTexture(t);else{const f=Z(o);d=this.gpgpu.downloadFloat32MatrixFromBuffer(l,f)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){const f=this.gpgpu.gl;ot(f,()=>f.deleteBuffer(l))}const h=this.convertAndCacheOnCPU(t,d),p=this.pendingRead.get(t);return this.pendingRead.delete(t),p.forEach(f=>f(h)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&zt().removeDataId(t,this),this.pendingDeletes--),h}readToGPU(t,e={}){const s=this.texData.get(t),{values:o,shape:r,slice:i,dtype:a,isPacked:c,texture:l}=s;if(a==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let p;c?p=new Fs(r,Vs):p=new jn(r,Vs);const f=this.runWebGLProgram(p,[{dataId:t,shape:r,dtype:a}],a),m=this.readToGPU(f,e);return this.disposeIntermediateTensorInfo(f),m}if(l==null)throw o!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(t,e.customTexShape),d=zt().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:d},h.texture)}bufferSync(t){const e=this.readSync(t.dataId);if(t.dtype==="string")try{const s=e.map(o=>xs(o));return wt(t.shape,t.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}checkNumericalProblems(t){if(t!=null)for(let e=0;e0}time(t){const e=this.activeTimers,s=[];let o=!1;this.programTimersStack==null?(this.programTimersStack=s,o=!0):this.activeTimers.push(s),this.activeTimers=s,t();const r=Qs(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),i=Qs(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=e,o&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(r);a.kernelMs=qI(c),a.getExtraProfileInfo=()=>c.map((l,u)=>({name:i[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Ve(),endMs:null}}endTimer(t){return z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=Ve(),t)}async getQueryTime(t){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);const e=t;return e.endMs-e.startMs}disposeData(t,e=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(e?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!e&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);const{complexTensorInfos:s}=this.texData.get(t);return s!=null&&(this.disposeData(s.real.dataId,e),this.disposeData(s.imag.dataId,e)),this.texData.delete(t),!0}releaseGPUData(t){const{texture:e,dtype:s,texShape:o,usage:r,isPacked:i,slice:a}=this.texData.get(t),c=a&&a.origDataId||t,l=this.dataRefCount.get(c);l>1?this.dataRefCount.set(c,l-1):(this.dataRefCount.delete(c),e!=null&&(this.numBytesInGPU-=this.computeBytes(o,s),this.textureManager.releaseTexture(e,o,r,i)));const u=this.texData.get(t);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,e=iX){return z().getBool("WEBGL_CPU_FORWARD")&&t.every(s=>this.texData.get(s.dataId).texture==null&&Z(s.shape)0&&Cr(s[0])){const r=s.map(i=>bs(i));o=this.write(r,t,e)}else o=this.write(s,t,e);return this.texData.get(o).usage=null,{dataId:o,shape:t,dtype:e}}makeOutput(t,e,s){return zt().makeTensorFromTensorInfo(this.makeTensorInfo(t,e,s),this)}unpackTensor(t){const e=new eX(t.shape);return this.runWebGLProgram(e,[t],t.dtype)}packTensor(t){const e=new Xz(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)}packedReshape(t,e){const s=[ur(t.shape),...dr(t.shape)],o={dtype:t.dtype,shape:s,dataId:t.dataId},r=[ur(e),...dr(e)],i=new T1(r,s),a=!0,c=[s],l=this.runWebGLProgram(i,[o],t.dtype,c,a);return{dataId:l.dataId,shape:e,dtype:l.dtype}}decode(t,e){const s=this.texData.get(t),{isPacked:o,shape:r,dtype:i}=s;if(e!=null){const h=Z(r),p=e[0]*e[1]*4;v(h<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}const a=vl(r);let c;o?c=new kF(a):c=new SF(a);const l=!0,u=[e??Il(a)],d=this.runWebGLProgram(c,[{shape:a,dtype:i,dataId:t}],i,u,l,e);return{dtype:i,shape:r,dataId:d.dataId}}runWebGLProgram(t,e,s,o,r=!1,i){const a=this.makeTensorInfo(t.outputShape,s),c=this.texData.get(a.dataId);if(t.packedOutput&&(c.isPacked=!0),t.outPackingScheme===sa.DENSE){const b=i??Il(t.outputShape);c.texShape=b.map(x=>x*2)}if(t.outTexUsage!=null&&(c.usage=t.outTexUsage),Z(a.shape)===0)return c.values=Se(a.dtype,0),a;const l=[],u=e.map(b=>{if(b.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let x=this.texData.get(b.dataId);if(x.texture==null){if(!t.packedInputs&&Z(b.shape)<=z().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:b.shape,texData:null,isUniform:!0,uniformValues:x.values};t.packedInputs&&(x.isPacked=!0,x.shape=b.shape)}if(this.uploadToGPU(b.dataId),!!x.isPacked!=!!t.packedInputs)b=x.isPacked?this.unpackTensor(b):this.packTensor(b),l.push(b),x=this.texData.get(b.dataId);else if(x.isPacked&&!kl(x.shape,b.shape)){const I=b,y=b.shape;b.shape=x.shape,b=this.packedReshape(b,y),l.push(b),x=this.texData.get(b.dataId),I.shape=y}return{shape:b.shape,texData:x,isUniform:!1}});this.uploadToGPU(a.dataId);const d={shape:a.shape,texData:c,isUniform:!1},h=vF(t,u,d),p=this.getAndSaveBinary(h,()=>wF(this.gpgpu,t,u,d)),f=this.activeTimers!=null;let m;f&&(m=this.startTimer()),z().get("ENGINE_COMPILE_ONLY")||CF(this.gpgpu,p,u,d,o),l.forEach(b=>this.disposeIntermediateTensorInfo(b)),f&&(m=this.endTimer(m),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(m)}));const g=z().getNumber("WEBGL_FLUSH_THRESHOLD");if(g>0){const b=Ve();b-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=b)}if(!z().getBool("WEBGL_LAZILY_UNPACK")&&c.isPacked&&r===!1){const b=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),b}return a}compileAndRun(t,e,s,o,r=!1){return s=s||e[0].dtype,this.runWebGLProgram(t,e,s,o,r)}getAndSaveBinary(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(z().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=M(()=>{if(!z().get("WEBGL_RENDER_FLOAT32_ENABLED")){const t=z().getBool("DEBUG");z().set("DEBUG",!1);const e=this.abs(Gt(1e-8)).dataSync()[0];if(z().set("DEBUG",t),e>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?sX:oX}uploadToGPU(t){const e=this.texData.get(t),{shape:s,dtype:o,values:r,texture:i,usage:a,isPacked:c}=e;if(i!=null)return;const l=this.activeTimers!=null;let u;l&&(u=Ve());let d=e.texShape;if(d==null&&(d=$V(s,c),e.texShape=d),r!=null){const h=vl(s);let p,f=d[1],m=d[0];const g=r instanceof Uint8Array||r instanceof Uint8ClampedArray;(c||!g)&&([f,m]=lr(d[0],d[1])),c?p=new $F(h,g):p=new g1(h,g);const b=g?[m,f]:d,x=this.makeTensorInfo(b,o),I=this.texData.get(x.dataId);g?I.usage=an.PIXELS:I.usage=an.UPLOAD,I.texShape=b,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),f,m,r);const y=[[m,f]],C=this.runWebGLProgram(p,[x],o,y,!0),k=this.texData.get(C.dataId);e.texShape=k.texShape,e.isPacked=k.isPacked,e.usage=k.usage,z().get("ENGINE_COMPILE_ONLY")?this.disposeData(C.dataId):(e.texture=k.texture,e.values=null,this.texData.delete(C.dataId)),this.disposeIntermediateTensorInfo(x),l&&(this.uploadWaitMs+=Ve()-u)}else{const h=this.acquireTexture(d,a,o,c);e.texture=h}}convertAndCacheOnCPU(t,e){const s=this.texData.get(t),{dtype:o}=s;return e!=null&&(s.values=lX(e,o)),s.values}acquireTexture(t,e,s,o){if(this.numBytesInGPU+=this.computeBytes(t,s),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,e,o)}computeBytes(t,e){return t[0]*t[1]*xa(e)}checkCompileCompletion(){for(const[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){const t=[];if(this.gpgpu.parallelCompilationExtension){for(const[,e]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(e));return Promise.all(t)}else{for(const[,e]of Object.entries(this.binaryCache)){const s=new Promise(o=>{try{this.checkCompletion_(e),o(!0)}catch(r){throw r}});t.push(s)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await Xc(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(i1(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(const t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);const{variablesLocations:e,customUniformLocations:s,infLoc:o,nanLoc:r,outShapeLocation:i,outShapeStridesLocation:a,outTexShapeLocation:c}=f1(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=e,t.customUniformLocations=s,t.infLoc=o,t.nanLoc=r,t.outShapeLocation=i,t.outShapeStridesLocation=a,t.outTexShapeLocation=c}}createTensorFromGPUData(t,e,s){t.channels=t.channels||"RGBA";const{texture:o,height:r,width:i,channels:a}=t,c=zt().backend;if(!c.gpgpu.gl.isTexture(o))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const l=c.writeTexture(o,e,s,r,i,a);return zt().makeTensorFromDataId(l,e,s,c)}}Rl.nextDataId=0;function lX(n,t){if(t==="float32"||t==="complex64")return n;if(t==="int32"||t==="bool"){const e=t==="int32"?new Int32Array(n.length):new Uint8Array(n.length);for(let s=0;snew Rl,2);/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lp=` + if (isnan(a)) return a; + if (isnan(b)) return b; +`;class ko{constructor(t,e,s){this.variableNames=["A","B"],this.outputShape=gt(e,s),this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=` + float binaryOperation(float a, float b) { + ${t} + } + + void main() { + float a = getAAtOutCoords(); + float b = getBAtOutCoords(); + setOutput(binaryOperation(a, b)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const To=` + result.r = isNaN.r ? NAN : result.r; + result.g = isNaN.g ? NAN : result.g; + result.b = isNaN.b ? NAN : result.b; + result.a = isNaN.a ? NAN : result.a; +`;class gr{constructor(t,e,s,o=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=gt(e,s);const r=this.outputShape.length;this.enableShapeUniforms=Ne(r);let i="";if(o)if(r===0||Z(this.outputShape)===1)i=` + result.y = 0.; + result.z = 0.; + result.w = 0.; + `;else if(i=` + ${Wt(r)} coords = getOutputCoords(); + `,r===1)this.enableShapeUniforms?i+=` + result.y = (coords + 1) >= outShape ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `:i+=` + result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `;else{const c=We("coords",r);this.enableShapeUniforms?i+=` + bool nextRowOutOfBounds = + (${c[r-2]} + 1) >= outShape[${r} - 2]; + bool nextColOutOfBounds = + (${c[r-1]} + 1) >= outShape[${r} - 1]; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `:i+=` + bool nextRowOutOfBounds = + (${c[r-2]} + 1) >= ${this.outputShape[r-2]}; + bool nextColOutOfBounds = + (${c[r-1]} + 1) >= ${this.outputShape[r-1]}; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `}this.userCode=` + vec4 binaryOperation(vec4 a, vec4 b) { + ${t} + } + + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + + vec4 result = binaryOperation(a, b); + ${i} + + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Je(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const uX={kernelName:Kr,backendName:"webgl",kernelFunc:Je};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zs(n){const{inputs:t,backend:e}=n,{real:s,imag:o}=t,r=e.makeTensorInfo(s.shape,"complex64"),i=e.texData.get(r.dataId),a=Je({inputs:{x:s},backend:e}),c=Je({inputs:{x:o},backend:e});return i.complexTensorInfos={real:a,imag:c},r}const dX={kernelName:lu,backendName:"webgl",kernelFunc:zs};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const L1="return (a < 0.) ? b * a : a;",E1=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function hX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{alpha:r}=s,i=e.makeTensorInfo([],"float32",gs(r,"float32")),a=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(E1,o.shape,i.shape):new ko(L1,o.shape,i.shape),c=e.runWebGLProgram(a,[o,i],"float32");return e.disposeIntermediateTensorInfo(i),c}const pX={kernelName:Xa,backendName:"webgl",kernelFunc:hX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const D1="return (a < 0.) ? b * a : a;",W1=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function fX(n){const{inputs:t,backend:e}=n,{x:s,alpha:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(W1,s.shape,o.shape):new ko(D1,s.shape,o.shape);return e.runWebGLProgram(r,[s,o],"float32")}const mX={kernelName:oc,backendName:"webgl",kernelFunc:fX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const br="if (isnan(x)) return x;";function Tt({opSnippet:n,packedOpSnippet:t,cpuKernelImpl:e,dtype:s}){return({inputs:o,backend:r})=>{const{x:i}=o,a=r,c=s||i.dtype;if(a.shouldExecuteOnCPU([i])&&e!=null){const d=a.texData.get(i.dataId),h=e(d.values,c);return a.makeTensorInfo(i.shape,c,h)}const l=z().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null;let u;return l?u=new Fs(i.shape,t):u=new jn(i.shape,n),a.runWebGLProgram(u,[i],c)}}function Ce({opSnippet:n,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:s=!1,cpuKernelImpl:o,dtype:r}){return({inputs:i,backend:a})=>{const{a:c,b:l}=i,u=a;if(s&&c.dtype==="complex64"){const f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(I=>{const[y,w]=I,C={dataId:y.dataId,dtype:y.dtype,shape:c.shape},k={dataId:w.dataId,dtype:w.dtype,shape:l.shape},S=new ko(n,c.shape,l.shape);return u.runWebGLProgram(S,[C,k],_e(y.dtype,w.dtype))}),x=zs({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),x}const d=r||_e(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&o!=null){const f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?cs(f):f,b=c.dtype==="string"?cs(m):m,[x,I]=o(c.shape,l.shape,g,b,d),y=u.makeTensorInfo(I,d),w=u.texData.get(y.dataId);return w.values=x,y}const h=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let p;return h?p=new gr(t,c.shape,l.shape,e):p=new ko(n,c.shape,l.shape),u.runWebGLProgram(p,[c,l],d)}}function aa(n,t=!1){if(n==="linear")return t?Qz:Bz;if(n==="relu")return t?jz:_z;if(n==="elu")return t?Jz:Hz;if(n==="relu6")return t?qz:Uz;if(n==="prelu")return t?W1:D1;if(n==="leakyrelu")return t?E1:L1;if(n==="sigmoid")return t?tX:Yz;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class M1{constructor(t,e,s,o=!1,r=!1,i=!1,a=null,c=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s,this.enableShapeUniforms=Ne(this.outputShape.length);const u=o?t[1]:t[2],d=Math.ceil(u/2),h=o?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",f=o?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let g="",b="";a&&(c?g=`vec4 activation(vec4 a) { + vec4 b = getPreluActivationWeightsAtOutCoords(); + ${a} + }`:l?g=`vec4 activation(vec4 a) { + vec4 b = getLeakyreluAlphaAtOutCoords(); + ${a} + }`:g=`vec4 activation(vec4 x) { + ${a} + }`,b="result = activation(result);");const x=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let I="rc.x",y="rc.x";t[0]`The new shape (${c}) has ${l} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const u=i.texData.get(o.dataId);return u.isPacked&&!kl(o.shape,c)&&!(u.texture!==null&&kl(u.shape,c))?bX(o,c,i):(i.incRef(o.dataId),{dataId:o.dataId,shape:c,dtype:o.dtype})}const xX={kernelName:ic,backendName:"webgl",kernelFunc:tt};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class X1{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:o,inSize:r,outSize:i}=t;this.outputShape=[o,i];const a=Math.floor(s/4)*4,c=s%4;let l="sumValue += dot(values, ones);";if(e!=null){const d=1/e;l=`sumValue += dot(values * ${Do(d)?d.toPrecision(2):d}, ones);`}let u="";r%s>0&&(u=` + if (inIdx < 0 || inIdx >= ${r}) { + return 0.0; + } + `),this.userCode=` + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${u} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + float sumValue = 0.0; + + for (int i = 0; i < ${a}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${l} + } + + int inIdx = inOffset + ${a}; + if (${c===1}) { + vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); + + ${l} + } else if (${c===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), 0.0, 0.0); + + ${l} + } else if (${c===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), 0.0); + + ${l} + } + setOutput(sumValue); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yX{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:o,inSize:r,outSize:i}=t;this.outputShape=[o,i];let a="0.0",c="";e==="prod"?a="1.0":e==="min"?(a="1.0 / 1e-20",c="min"):e==="max"&&(a="-1.0 / 1e-20",c="max");let l=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?l="sumValue":e==="prod"?l="prodValue":e==="all"?l="allValue":e==="any"&&(l="anyValue");const u=Math.floor(s/4)*4,d=s%4;let h=` + if (${e==="sum"}) { + sumValue += dot(values, ones); + } else if (${e==="prod"}) { + vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); + prodValue *= tmp[0] * tmp[1]; + } else { + minMaxValue = ${c}(values, minMaxValue); + if (${e==="min"} || ${e==="max"}) { + minMaxValue = ${c}(values, minMaxValue); + bvec4 isNaN = isnan(values); + if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) { + minMaxValue = vec4(NAN); + } + } + } + `,p="vec4";e==="all"?(a="1.0",h=` + bool reducedAllValue = all(values); + float floatedReducedAllValue = float(reducedAllValue); + allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); + `,p="bvec4"):e==="any"&&(a="0.0",h=` + bool reducedAnyValue = any(values); + float floatedReducedAnyValue = float(reducedAnyValue); + anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); + `,p="bvec4");let f="";r%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${r}) { + return initializationValue; + } + `),this.userCode=` + const float initializationValue = ${a}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${f} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + vec4 minMaxValue = vec4(${a}); + float prodValue = 1.0; + float sumValue = 0.0; + float allValue = 1.0; + float anyValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${h} + } + + int inIdx = inOffset + ${u}; + if (${d===1}) { + ${p} values = ${p}( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + ${h} + } else if (${d===2}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + ${h} + } else if (${d===3}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + ${h} + } + setOutput(${l}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IX(n){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const e=t.length?t[t.length-1].outSize:n[1],s=Ac(e);t.push({inSize:e,windowSize:s,outSize:Math.ceil(e/s)})}return t}function No(n,t,e,s){const o=IX(n.shape);let r=n;for(let i=0;i6)throw Error(`Transpose for rank ${t} is not yet supported`);const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let o=0;o6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const o=Wt(this.rank),r=k1("rc",this.rank),i=new Array(this.rank);for(let u=0;u`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${n.shape} and ${t.shape} and transposeA=${e} and transposeB=${s} must match.`);const w=e?[b,d,p]:[b,p,d],C=s?[x,f,h]:[x,h,f],k=tt({inputs:{x:n},backend:o,attrs:{shape:w}}),S=tt({inputs:{x:t},backend:o,attrs:{shape:C}}),T=[k,S],R=Math.max(b,x),L=e?k.shape[1]:k.shape[2],V=r!=null,F=i!=null,X=c==="leakyrelu",A=c!=null?aa(c,!0):null,P=V||F||X||A!=null;let B;if((p===1||f===1)&&L>A1&&P===!1){let H=k,U=S;e&&(H=Me({inputs:{x:k},backend:o,attrs:{perm:[0,2,1]}}),T.push(H)),s&&(U=Me({inputs:{x:S},backend:o,attrs:{perm:[0,2,1]}}),T.push(U));const Y=f!==1,j=f===1;let J=H;Y&&(J=tt({inputs:{x:H},backend:o,attrs:{shape:[R,L,1]}}),T.push(J));const nt=f===1?2:1;let q=U;j&&(q=tt({inputs:{x:U},backend:o,attrs:{shape:[R,1,L]}}),T.push(q));const rt=Ep({inputs:{a:J,b:q},backend:o});B=Gl({inputs:{x:rt},backend:o,attrs:{axis:nt,keepDims:!0}}),T.push(rt)}else{const H=_e(n.dtype,t.dtype),U=new M1(w,C,[R,p,f],e,s,V,A,F,X),Y=[k,S];if(r!=null&&Y.push(r),F&&Y.push(i),X){const j=o.makeTensorInfo([],"float32",gs(a,"float32"));Y.push(j),T.push(j)}B=o.runWebGLProgram(U,Y,H)}const K=tt({inputs:{x:B},backend:o,attrs:{shape:y}});T.push(B);for(const H of T)o.disposeIntermediateTensorInfo(H);return K}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NX(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r,bias:i,preluActivationWeights:a}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=s;return Ll({a:o,b:r,transposeA:c,transposeB:l,backend:e,bias:i,preluActivationWeights:a,leakyreluAlpha:d,activation:u})}const RX={kernelName:yc,backendName:"webgl",kernelFunc:NX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const P1="return abs(x);";function $X(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){const r=e.texData.get(s.dataId),i=v1(r.values);return e.makeTensorInfo(s.shape,s.dtype,i)}let o;return z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fs(s.shape,P1):o=new jn(s.shape,P1),e.runWebGLProgram(o,[s],s.dtype)}const GX={kernelName:ya,backendName:"webgl",kernelFunc:$X};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LX=Cn+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,EX=Tt({opSnippet:LX}),DX={kernelName:vr,backendName:"webgl",kernelFunc:EX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WX=Cn+` + if (x < 1.0) return NAN; +return log(x + sqrt(x * x - 1.0));`,MX=Tt({opSnippet:WX}),VX={kernelName:Sr,backendName:"webgl",kernelFunc:MX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const O1="return a + b;",FX=Ce({opSnippet:O1,packedOpSnippet:O1,supportsComplex:!0,cpuKernelImpl:_F}),zX={kernelName:Fo,backendName:"webgl",kernelFunc:FX};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class XX{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((r,i)=>`T${i}`);const s=[];this.variableNames.forEach(r=>{s.push(`float v${r} = get${r}AtOutCoords();`)});const o=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + float result = ${o}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class AX{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((r,i)=>`T${i}`);const s=[];this.variableNames.forEach(r=>{s.push(`vec4 v${r} = get${r}AtOutCoords();`)});const o=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + vec4 result = ${o}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function El(n){const{inputs:t,backend:e}=n,s=t;if(s.length===1)return Je({inputs:{x:s[0]},backend:e});if(s.length>z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const c=Math.floor(s.length/2),l=El({inputs:s.slice(0,c),backend:e}),u=El({inputs:s.slice(c),backend:e});return El({inputs:[l,u],backend:e})}const o=s.map(c=>c.dtype).reduce((c,l)=>_e(c,l)),r=s.map(c=>c.shape),a=z().getBool("WEBGL_PACK")?new AX(s[0].shape,r):new XX(s[0].shape,r);return e.runWebGLProgram(a,s,o)}const PX={kernelName:nu,backendName:"webgl",kernelFunc:El};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),l=ee(l.length,a)),Ie("all",l,a);const[h,p]=me(d.shape,l),f=Z(p),m=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,f]}}),g=No(m,m.dtype,"all",e);let b;if(i){const x=re(h,c);b=tt({inputs:{x:g},backend:e,attrs:{shape:x}})}else b=tt({inputs:{x:g},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),u!=null&&e.disposeIntermediateTensorInfo(d),b}const KX={kernelName:su,backendName:"webgl",kernelFunc:OX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),l=ee(l.length,a)),Ie("any",l,a);const[h,p]=me(d.shape,l),f=Z(p),m=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,f]}}),g=No(m,m.dtype,"any",e);let b;if(i){const x=re(h,c);b=tt({inputs:{x:g},backend:e,attrs:{shape:x}})}else b=tt({inputs:{x:g},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),u!=null&&e.disposeIntermediateTensorInfo(d),b}const BX={kernelName:ou,backendName:"webgl",kernelFunc:ZX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class HX{constructor(t,e,s){this.variableNames=["A"];const{windowSize:o,batchSize:r,outSize:i}=t;s||this.variableNames.push("bestIndicesA"),this.outputShape=[r,i];const a=e==="max"?">":"<",c=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${o}; + + int bestIndex = inOffset; + float bestValue = getA(batch, bestIndex); + + for (int i = 0; i < ${o}; i++) { + int inIdx = ${c}; + float candidate = getA(batch, inIdx); + if (candidate ${a} bestValue) { + bestValue = candidate; + bestIndex = inIdx; + } + } + setOutput(float(bestIndex)); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _X{constructor(t,e,s,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v(t.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const r=t[t.length-1],i=Math.ceil(r/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),o||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,l=Wt(c),u=We("coords",c);let d,h;if(i===1){h=c+1;const S=Wt(h);d=` + ${S} sourceLocR = ${S}(${u.join()}, 0); + ++${u[c-1]}; + ${S} sourceLocG = ${S}(${u.join()}, 0); + ++${u[c-2]}; + ${S} sourceLocA = ${S}(${u.join()}, 0); + --${u[c-1]}; + ${S} sourceLocB = ${S}(${u.join()}, 0); + --${u[c-2]};`}else h=c,d=` + ${l} sourceLocR = coords; + ++${u[c-1]}; + ${l} sourceLocG = coords; + ++${u[c-2]}; + ${l} sourceLocA = coords; + --${u[c-1]}; + ${l} sourceLocB = coords; + --${u[c-2]};`;const p=["x","y","z","w","u","v"].slice(0,h),f="."+p[h-1],m=p.map(S=>"int "+S),g=We("sourceLocR",h-1).concat("inIdx.r"),b=We("sourceLocG",h-1).concat("inIdx.g"),x=We("sourceLocB",h-1).concat("inIdx.b"),I=We("sourceLocA",h-1).concat("inIdx.a"),y=s==="max"?"greaterThan":"lessThan",w=o?"":` + inIdx = round(vec4(getBestIndicesAChannel(${g.join()}), + getBestIndicesAChannel(${b.join()}), + getBestIndicesAChannel(${x.join()}), + getBestIndicesAChannel(${I.join()})));`,C=`vec4( + getAChannel(${g.join()}), + hasNextCol ? getAChannel(${b.join()}) : 0., + hasNextRow ? getAChannel(${x.join()}) : 0., + hasNextRow && hasNextCol ? getAChannel(${I.join()}) : 0.)`,k=o?"":` + float getBestIndicesAChannel(${m.join()}) { + return getChannel(getBestIndicesA(${p.join()}), + vec2(${p.slice(-2).join()})); + }`;this.userCode=` + float getAChannel(${m.join()}) { + return getChannel(getA(${p.join()}), + vec2(${p.slice(-2).join()})); + } + ${k} + void main() { + ${l} coords = getOutputCoords(); + bool hasNextCol = ${u[c-1]} < ${a[c-1]-1}; + bool hasNextRow = ${u[c-2]} < ${a[c-2]-1}; + ${d} + ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f}, + sourceLocB${f}, sourceLocA${f}) * ${e}; + ivec4 inIdx = srcIdx; + vec4 bestIndex = vec4(inIdx); + vec4 bestValue = ${C}; + + for (int i = 0; i < ${e}; i++) { + inIdx = srcIdx; + ${w} + vec4 candidate = ${C}; + bvec4 nan = isnan(candidate); + bvec4 replace = bvec4( + vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); + + bestValue = vec4(replace.x ? candidate.x : bestValue.x, + replace.y ? candidate.y : bestValue.y, + replace.z ? candidate.z : bestValue.z, + replace.w ? candidate.w : bestValue.w); + bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); + srcIdx++; + } + setOutput(bestIndex); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function K1(n,t,e,s=null){let o=t.shape[0],r=t.shape[1];s!=null&&(o=s.shape[0],r=s.shape[1]);const i=Ac(r),a={windowSize:i,inSize:r,batchSize:o,outSize:Math.ceil(r/i)},c=new HX(a,e,s==null),l=[t];s!=null&&l.push(s);const u=n.runWebGLProgram(c,l,"int32");if(u.shape[1]===1)return u;const d=K1(n,t,e,u);return n.disposeIntermediateTensorInfo(u),d}function Z1(n,t,e,s=null){const o=s!=null?s.shape:t.shape,r=o[o.length-1],i=Ac(r),a=new _X(o,i,e,s==null),c=s==null?[t]:[t,s],l=n.runWebGLProgram(a,c,"int32");if(l.shape.length===t.shape.length){const u=Z1(n,t,e,l);return n.disposeIntermediateTensorInfo(l),u}return l}function B1(n,t,e,s){const o=[e];if(Ie("arg"+s.charAt(0).toUpperCase()+s.slice(1),o,t.shape.length),!z().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const r=[],i=n.texData.get(t.dataId),a=i!==null&&i.isPacked;let c=t;a&&(c=n.unpackTensor(t),r.push(c));const[l,u]=me(c.shape,o),d=Z(u),h=tt({inputs:{x:c},backend:n,attrs:{shape:[-1,d]}});r.push(h);const p=K1(n,h,s);r.push(p);const f=tt({inputs:{x:p},backend:n,attrs:{shape:l}});return r.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}return Z1(n,t,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Me({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),Ie("argMax",[i[0]],c.shape.length);const u=B1(e,c,i[0],"max");return l.forEach(d=>e.disposeIntermediateTensorInfo(d)),u}const YX={kernelName:Ia,backendName:"webgl",kernelFunc:UX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Me({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),Ie("argMin",[i[0]],c.shape.length);const u=B1(e,c,i[0],"min");return l.forEach(d=>e.disposeIntermediateTensorInfo(d)),u}const JX={kernelName:wa,backendName:"webgl",kernelFunc:QX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jX=Cn+` + if (abs(x) > 1.) { + return NAN; + } + return asin(x); +`,qX=Tt({opSnippet:jX}),tA={kernelName:kr,backendName:"webgl",kernelFunc:qX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eA=Cn+"return log(x + sqrt(x * x + 1.0));",nA=Tt({opSnippet:eA}),sA={kernelName:Tr,backendName:"webgl",kernelFunc:nA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oA=Cn+` + return atan(x); +`,rA=Tt({opSnippet:oA}),iA={kernelName:Nr,backendName:"webgl",kernelFunc:rA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aA=Lp+` + return atan(a, b); +`,cA=` + vec4 result = atan(a, b); + bvec4 isNaNA = isnan(a); + bvec4 isNaNB = isnan(b); + bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w); + `+To+` + return result; +`,lA=Ce({opSnippet:aA,packedOpSnippet:cA}),uA={kernelName:$r,backendName:"webgl",kernelFunc:lA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dA=Cn+` + if ((x < -1.0) || (x > 1.0)) return NAN; +return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,hA=Tt({opSnippet:dA}),pA={kernelName:Rr,backendName:"webgl",kernelFunc:hA};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ca{constructor(t,e,s,o=!1,r=!1){if(this.variableNames=["x"],e==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const i=t.filterWidth,a=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;const m=e==="avg",g=`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,b=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`;let x="0.0";if(m||(x="-1.0 / 1e-20"),s){const S=">=";this.userCode=` + const ivec2 strides = ivec2(${a}, ${c}); + const ivec2 pads = ivec2(${p}, ${f}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + float avgValue = 0.0; + + for (int wR = 0; wR < ${d}; + wR += ${l}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${h}; + wC += ${u}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float value = getX(batch, xR, xC, d); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${S} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${o?r?g:b:`wR * ${h} + wC`}; + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const I="max";let y=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(y="avgValue / max(count, 1.0)");const w=Math.floor(i/4)*4,C=i%4,k=` + if (${m}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${I}(values, minMaxValue); + } + `;this.userCode=` + const ivec2 strides = ivec2(${a}, ${c}); + const ivec2 pads = ivec2(${p}, ${f}); + const float initializationValue = ${x}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xR, int xC, int d) { + if (xC < 0 || xC >= ${t.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xR, xC, d); + } + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + vec4 minMaxValue = vec4(${x}); + float avgValue = 0.0; + count = 0.0; + + for (int wR = 0; wR < ${d}; + wR += ${l}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${w}; wC += 4) { + int xC = xCCorner + wC * ${u}; + + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + getValue(batch, xR, xC + 3 * ${u}, d) + ); + + ${k} + } + + int xC = xCCorner + ${w}; + if (${C===1}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + initializationValue, + initializationValue, + initializationValue + ); + + ${k} + } else if (${C===2}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + initializationValue, + initializationValue + ); + + ${k} + } else if (${C===3}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + initializationValue + ); + + ${k} + } + } + setOutput(${y}); + } + `}}class Dp{constructor(t,e,s,o=!1,r=!1){if(this.variableNames=["x"],e==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const i=t.filterWidth,a=t.strideDepth,c=t.strideHeight,l=t.strideWidth,u=t.dilationDepth,d=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,g=t.padInfo.front,b=t.padInfo.top,x=t.padInfo.left;this.outputShape=t.outShape;const I=e==="avg";let y="0.0";if(I||(y="-1.0 / 1e-20"),s){const R=">=";this.userCode=` + const ivec3 strides = + ivec3(${a}, ${c}, ${l}); + const ivec3 pads = ivec3(${g}, ${b}, ${x}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + + for (int wD = 0; wD < ${p}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${d}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${m}; + wC += ${h}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float value = getX(batch, xD, xR, xC, ch); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${R} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${o?r?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${f} * ${m} + + wR * ${m} + wC`}; + } + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const w="max";let C=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(C="avgValue / max(count, 1.0)");const k=Math.floor(i/4)*4,S=i%4,T=` + if (${I}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${w}(values, minMaxValue); + } + `;this.userCode=` + const ivec3 strides = + ivec3(${a}, ${c}, ${l}); + const ivec3 pads = ivec3(${g}, ${b}, ${x}); + const float initializationValue = ${y}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xD, int xR, int xC, int ch) { + if (xC < 0 || xC >= ${t.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xD, xR, xC, ch); + } + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). + // ? = to be determined + vec4 minMaxValue = vec4(${y}); + float avgValue = 0.0; + count = 0.0; + + for (int wD = 0; wD < ${p}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${d}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${k}; wC += 4) { + int xC = xCCorner + wC * ${h}; + + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${h}, ch), + getValue(batch, xD, xR, xC + 2 * ${h}, ch), + getValue(batch, xD, xR, xC + 3 * ${h}, ch) + ); + + ${T} + } + + int xC = xCCorner + ${k}; + if (${S===1}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + initializationValue, + initializationValue, + initializationValue + ); + + ${T} + } else if (${S===2}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${h}, ch), + initializationValue, + initializationValue + ); + + ${T} + } else if (${S===3}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${h}, ch), + getValue(batch, xD, xR, xC + 2 * ${h}, ch), + initializationValue + ); + + ${T} + } + } + } + setOutput(${C}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;ra(o,"avgPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))return Je({inputs:{x:o},backend:e});const d=new ca(u,"avg",!1);return e.runWebGLProgram(d,[o],"float32")}const mA={kernelName:Ca,backendName:"webgl",kernelFunc:fA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s,u=[1,1,1],d=ss(o.shape,r,i,u,a,c,l),h=new Dp(d,"avg",!1);return e.runWebGLProgram(h,[o],"float32")}const bA={kernelName:va,backendName:"webgl",kernelFunc:gA};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xA{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,c=t.effectiveFilterHeight,l=t.effectiveFilterWidth,u=c-1-t.padInfo.top,d=l-1-t.padInfo.left,h=1/(e*s);this.userCode=` + const ivec2 pads = ivec2(${u}, ${d}); + const float avgMultiplier = float(${h}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${c}; + wR += ${i}) { + float dyR = float(dyRCorner + wR) / ${o}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${l}; + wC+= ${a}) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + + dotProd += dyValue * avgMultiplier; + } + } + setOutput(dotProd); + } + `}}class yA{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const e=t.filterDepth,s=t.filterHeight,o=t.filterWidth,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,d=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=d-1-t.padInfo.front,m=h-1-t.padInfo.top,g=p-1-t.padInfo.left,b=1/(e*s*o);this.userCode=` + const ivec3 pads = ivec3(${f}, ${m}, ${g}); + const float avgMultiplier = float(${b}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${d}; + wD += ${c}) { + float dyD = float(dyDCorner + wD) / ${r}.0; + + if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${h}; + wR += ${l}) { + float dyR = float(dyRCorner + wR) / ${i}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${p}; + wC += ${u}) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + + dotProd += dyValue * avgMultiplier; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IA(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r,{filterSize:a,strides:c,pad:l,dimRoundingMode:u}=s,d=[1,1,1],h=ss(i.shape,a,c,d,l,u),p=new yA(h);return e.runWebGLProgram(p,[o],i.dtype)}const wA={kernelName:iu,backendName:"webgl",kernelFunc:IA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CA(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r;ra([o,r],"avgPoolGrad");const{filterSize:a,strides:c,pad:l}=s,u=pn(i.shape,a,c,1,l),d=new xA(u);return e.runWebGLProgram(d,[o],i.dtype)}const vA={kernelName:ru,backendName:"webgl",kernelFunc:CA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SA(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r}=t,{transposeA:i,transposeB:a}=s;return Ll({a:o,b:r,transposeA:i,transposeB:a,backend:e})}const kA={kernelName:Sa,backendName:"webgl",kernelFunc:SA};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class TA{constructor(t,e,s,o,r,i){this.outputShape=[],this.variableNames=["x","mean","variance"],gt(t,e),gt(t,s);let a="0.0";o!=null&&(gt(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";r!=null&&(gt(t,r),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` + void main() { + float x = getXAtOutCoords(); + float mean = getMeanAtOutCoords(); + float variance = getVarianceAtOutCoords(); + float offset = ${a}; + float scale = ${c}; + float inv = scale * inversesqrt(variance + float(${i})); + setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class NA{constructor(t,e,s,o,r,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],gt(t,e),gt(t,s);let a="vec4(0.0)";o!=null&&(gt(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";r!=null&&(gt(t,r),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` + void main() { + vec4 offset = ${a}; + vec4 scale = ${c}; + + vec4 x = getXAtOutCoords(); + vec4 mean = getMeanAtOutCoords(); + vec4 variance = getVarianceAtOutCoords(); + + vec4 inv = scale * inversesqrt(variance + vec4(${i})); + + setOutput((x - mean) * inv + offset); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RA={kernelName:Va,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,mean:o,variance:r,offset:i,scale:a}=n;v(o.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=e;c==null&&(c=.001);const l=[s,o,r];let u=null;i!=null&&(u=i.shape,l.push(i));let d=null;a!=null&&(d=a.shape,l.push(a));const h=z().getBool("WEBGL_PACK_NORMALIZATION")?new NA(s.shape,o.shape,r.shape,u,d,c):new TA(s.shape,o.shape,r.shape,u,d,c);return t.runWebGLProgram(h,l,l[0].dtype)}};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $A{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;const e=Wt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const s=GA(this.rank);let o;const r=t.map((i,a)=>`sourceLoc.${Wp[a]} = start[${a}] + coords.${Wp[a]};`);o=` + ${e} sourceLoc; + ${e} coords = getOutputCoords(); + ${r.join(` +`)} + `,this.userCode=` + void main() { + ${o} + setOutput(getSource(${s})); + } + `}}const Wp=["x","y","z","w","u","v"];function GA(n){if(n===1)return"sourceLoc";if(n<=6)return Wp.slice(0,n).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LA{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const e=Wt(this.rank),s=We("coords",this.rank),o=We("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,i=`getChannel(getSource(${o.join()}), ${r})`,a=` + result.x = ${i}; + if (++${s[this.rank-1]} < ${t[this.rank-1]}) { + ++${o[this.rank-1]}; + result.y = ${i}; + --${o[this.rank-1]}; + } + `,c=this.rank===1?"":` + --${s[this.rank-1]}; + if (++${s[this.rank-2]} < ${t[this.rank-2]}) { + ++${o[this.rank-2]}; + result.z = ${i}; + if (++${s[this.rank-1]} < ${t[this.rank-1]}) { + ++${o[this.rank-1]}; + result.w = ${i}; + } + } + `,l=this.rank<=4?`sourceLoc = coords + + ${e}(${t.map((u,d)=>`start[${d}]`).join()});`:t.map((u,d)=>`${o[d]} = ${s[d]} + start[${d}];`).join(` +`);this.userCode=` + void main() { + ${e} coords = getOutputCoords(); + ${e} sourceLoc; + ${l} + vec4 result = vec4(0.); + ${a} + ${c} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EA(n,t,e,s){const o=s.texData.get(n.dataId),r=s.makeTensorInfo(e,n.dtype),i=s.texData.get(r.dataId);Object.assign(i,o),i.refCount=1,i.shape=e,i.dtype=n.dtype;let a=nh(t,ct(n.shape));o.slice&&(a+=o.slice.flatOffset),i.slice={flatOffset:a,origDataId:o.slice&&o.slice.origDataId||n.dataId};const c=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,c+1),r}function xr(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,size:i}=s,[a,c]=zc(o,r,i);if(qd(o,a,c),Z(c)===0)return e.makeTensorInfo(c,o.dtype,[]);if(e.shouldExecuteOnCPU([o])||o.dtype==="string"){const d=e.texData.get(o.dataId),h=kz(d.values,a,c,o.shape,o.dtype);return e.makeTensorInfo(c,o.dtype,h)}const{isPacked:l}=e.texData.get(o.dataId),u=eh(o.shape,a,c);if(l||!u){const d=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new LA(c):new $A(c),h=[a];return e.runWebGLProgram(d,[o],o.dtype,h)}return e.uploadToGPU(o.dataId),EA(o,a,c,e)}const DA={kernelName:dc,backendName:"webgl",kernelFunc:xr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WA={kernelName:ka,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,crops:i}=s;v(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const a=r.reduce((x,I)=>x*I),c=Mi(o.shape,r,a),l=Vi(c.length,r.length),u=Fi(o.shape,r,a),d=ah(i,r.length),h=ch(u,i,r.length),p=[],f=tt({inputs:{x:o},backend:e,attrs:{shape:c}}),m=Me({inputs:{x:f},backend:e,attrs:{perm:l}}),g=tt({inputs:{x:m},backend:e,attrs:{shape:u}}),b=xr({inputs:{x:g},backend:e,attrs:{begin:d,size:h}});return p.push(f),p.push(m),p.push(g),p.forEach(x=>e.disposeIntermediateTensorInfo(x)),b}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i}=s,a=e.readSync(o.dataId),c=e.readSync(r.dataId),l=C1(a,c,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,l)}const VA={kernelName:au,backendName:"webgl",kernelFunc:MA};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FA=` + int r = int(a.r) & int(b.r); + int g = int(a.g) & int(b.g); + int rb = int(a.b) & int(b.b); + int ra = int(a.a) & int(b.a); + return vec4(r, g, rb, ra); +`,zA=` + return float(int(a.r) & int(b.r)); +`;function XA(n){const{inputs:t,backend:e}=n,{a:s,b:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=z().getNumber("WEBGL_VERSION");if(e.shouldExecuteOnCPU([s,o])||i===1){const c=e.texData.get(s.dataId).values,l=e.texData.get(o.dataId).values,[u,d]=YF(s.shape,o.shape,c,l,s.dtype),h=e.makeTensorInfo(d,s.dtype),p=e.texData.get(h.dataId);return p.values=u,h}let a;return r?a=new gr(FA,s.shape,o.shape,!1):a=new ko(zA,s.shape,o.shape),e.runWebGLProgram(a,[s,o],s.dtype)}const AA={kernelName:cu,backendName:"webgl",kernelFunc:XA};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PA(n){const{inputs:t,backend:e}=n,{s0:s,s1:o}=t,r=e.readSync(s.dataId),i=e.readSync(o.dataId),a=gt(Array.from(r),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const OA={kernelName:xf,backendName:"webgl",kernelFunc:PA};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const H1=Ce({opSnippet:"return float(a != b);",cpuKernelImpl:gz,dtype:"bool"}),KA={kernelName:qa,backendName:"webgl",kernelFunc:H1};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function la(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.texData.get(s.dataId);return Je({inputs:{x:o.complexTensorInfos.real},backend:e})}const ZA={kernelName:Mu,backendName:"webgl",kernelFunc:la};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BA="return float(int(x));";function HA(n,t){const e=new jn(n.shape,BA),s=t.runWebGLProgram(e,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mp(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dtype:r}=s;if(r==="complex64"){if(o.dtype==="complex64")return Je({inputs:{x:o},backend:e});const i=ge(o.shape),a=Mp({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),c=zs({inputs:{real:a,imag:i},backend:e});return i.dispose(),e.disposeIntermediateTensorInfo(a),c}if(o.dtype==="complex64"){const i=la({inputs:{input:o},backend:e}),a=Mp({inputs:{x:i},backend:e,attrs:{dtype:r}});return e.disposeIntermediateTensorInfo(i),a}if(!hf(o.dtype,r)){const i=Je({inputs:{x:o},backend:e});return{dataId:i.dataId,shape:i.shape,dtype:r}}if(e.shouldExecuteOnCPU([o])){const i=e.texData.get(o.dataId).values,[a,c,l]=QF(i,o.shape,o.dtype,r);return e.makeTensorInfo(a,c,l)}if(r==="int32")return HA(o,e);if(r==="bool"){const i=e.makeTensorInfo([],"bool",Se("bool",1)),c=H1({inputs:{a:o,b:i},backend:e});return e.disposeIntermediateTensorInfo(i),c}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${r}`)}const _A={kernelName:Gr,backendName:"webgl",kernelFunc:Mp};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _1="return ceil(x);",UA=Tt({opSnippet:_1,packedOpSnippet:_1,cpuKernelImpl:JF}),YA={kernelName:Lr,backendName:"webgl",kernelFunc:UA};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class QA{constructor(t){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=` + + void main() { + float value = getAAtOutCoords(); + if (isnan(value)) { + setOutput(value); + return; + } + + setOutput(clamp(value, minVal, maxVal)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class JA{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=` + void main() { + vec4 value = getAAtOutCoords(); + + if (any(isnan(value))) { + setOutput(value); + return; + } + + setOutput(clamp(value, vec4(minVal), vec4(maxVal))); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{clipValueMin:r,clipValueMax:i}=s;let a;z().getBool("WEBGL_PACK_CLIP")?a=new JA(o.shape):a=new QA(o.shape);const c=[[r],[i]];return e.runWebGLProgram(a,[o],o.dtype,c)}const qA={kernelName:Er,backendName:"webgl",kernelFunc:jA};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class tP{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=` + void main() { + float re = abs(getRealAtOutCoords()); + float im = abs(getImagAtOutCoords()); + float mx = max(re, im); + + // sadly the length function in glsl is not underflow-safe + // (at least not on Intel GPUs). So the safe solution is + // to ensure underflow-safety in all cases. + setOutput( + mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) + ); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function U1(n,t){return{dataId:t.dataId,dtype:t.dtype,shape:n.shape}}function eP(n){const{inputs:t,backend:e}=n,{x:s}=t,o=e.texData.get(s.dataId),r=new tP(s.shape),i=[U1(s,o.complexTensorInfos.real),U1(s,o.complexTensorInfos.imag)];return e.runWebGLProgram(r,i,i[0].dtype)}const nP={kernelName:Ta,backendName:"webgl",kernelFunc:eP};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class sP{constructor(t){this.outputShape=[],this.outputShape=Kn(t,1),this.variableNames=t.map((i,a)=>`T${a}`);const e=new Array(t.length-1);e[0]=t[0][1];for(let i=1;i`T${g}`);const c=new Array(t.length-1);c[0]=t[0][e];for(let m=1;m= ${c[m-1]}) { + return getChannel( + getT${m}(${Dl(a,l,g)}), + vec2(${Dl(u,l,g)})); + }`}const p=c.length,f=c[c.length-1];h+=` + return getChannel( + getT${p}(${Dl(a,l,f)}), + vec2(${Dl(u,l,f)}));`,this.userCode=` + float getValue(${a.map(m=>"int "+m)}) { + ${h} + } + + void main() { + ${r} coords = getOutputCoords(); + vec4 result = vec4(getValue(${i}), 0., 0., 0.); + + ${i[o-1]} = ${i[o-1]} + 1; + if (${i[o-1]} < ${s[o-1]}) { + result.g = getValue(${i}); + } + + ${i[o-2]} = ${i[o-2]} + 1; + if (${i[o-2]} < ${s[o-2]}) { + result.a = getValue(${i}); + } + + ${i[o-1]} = ${i[o-1]} - 1; + if (${i[o-2]} < ${s[o-2]} && + ${i[o-1]} < ${s[o-1]}) { + result.b = getValue(${i}); + } + setOutput(result); + } + `}}function Dl(n,t,e){const s=n.indexOf(t);return n.map((r,i)=>i===s?`${r} - ${e}`:r).join()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wl(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.texData.get(s.dataId);return Je({inputs:{x:o.complexTensorInfos.imag},backend:e})}const rP={kernelName:Nu,backendName:"webgl",kernelFunc:Wl};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ua(n,t,e){const s=n[0].dtype;if(s==="complex64"){const p=n.map(x=>la({inputs:{input:x},backend:e})),f=n.map(x=>Wl({inputs:{input:x},backend:e})),m=ua(p,t,e),g=ua(f,t,e),b=zs({inputs:{real:m,imag:g},backend:e});return p.forEach(x=>e.disposeIntermediateTensorInfo(x)),f.forEach(x=>e.disposeIntermediateTensorInfo(x)),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),b}let o=e.shouldExecuteOnCPU(n);if(s==="string"&&(o=!0),o){const p=n.map(y=>{const C=[-1,Z(y.shape.slice(t))];return tt({inputs:{x:y},backend:e,attrs:{shape:C}})}),f=p.map(y=>({vals:e.readSync(y.dataId),shape:y.shape})),m=Kn(p.map(y=>y.shape),1),g=p[0].shape[0]===1,b=jF(f,m,s,g),x=Kn(n.map(y=>y.shape),t),I=e.makeTensorInfo(x,s,b);return p.forEach(y=>e.disposeIntermediateTensorInfo(y)),I}const r=n.filter(p=>Z(p.shape)>0),i=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1;if(r.length===1){const p=i?new jn(n[0].shape,Vs):new Fs(n[0].shape,Vs);return e.runWebGLProgram(p,n,s)}const a=z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(r.length>a){const p=[];for(let m=0;mf.shape),t);return e.runWebGLProgram(p,r,s)}const{tensors2D:c,outShape:l}=iP(r,t,e),u=new sP(c.map(p=>p.shape)),d=e.runWebGLProgram(u,c,s);c.forEach(p=>e.disposeIntermediateTensorInfo(p));const h=tt({inputs:{x:d},attrs:{shape:l},backend:e});return e.disposeIntermediateTensorInfo(d),h}function iP(n,t,e){const s=Kn(n.map(r=>r.shape),t);return{tensors2D:n.map(r=>tt({inputs:{x:r},attrs:{shape:[-1,Z(r.shape.slice(t))]},backend:e})),outShape:s}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y1(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s,r=It(o,t[0].shape)[0],i=t.map(l=>l.shape);oh(i,r);const a=Kn(t.map(l=>l.shape),r);if(Z(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(l=>Z(l.shape)>0);return c.length===1?Je({inputs:{x:c[0]},backend:e}):ua(c,r,e)}const aP={kernelName:Na,backendName:"webgl",kernelFunc:Y1};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Q1{constructor(t,e=!1,s=null,o=!1,r=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;const i=t.padInfo.top,a=t.padInfo.left,c=t.strideHeight,l=t.strideWidth,u=t.dilationHeight,d=t.dilationWidth,h=t.filterHeight,p=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4,g=t.dataFormat==="channelsLast",b=g?1:2,x=g?2:3,I=g?3:1;let y="",w="";s&&(o?y=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:r?y=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:y=` + float activation(float x) { + ${s} + } + `,w="result = activation(result);");const C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${y} + + const ivec2 strides = ivec2(${c}, ${l}); + const ivec2 pads = ivec2(${i}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d2 = coords[${I}]; + + ivec2 xRCCorner = + ivec2(coords[${b}], coords[${x}]) * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${h}; wR++) { + int xR = xRCorner + wR * ${u}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${d}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 wValues = vec4( + getW(wR, wC, d1, d2), + getW(wR, wC, d1 + 1, d2), + getW(wR, wC, d1 + 2, d2), + getW(wR, wC, d1 + 3, d2) + ); + + if (${g}) { + vec4 xValues = vec4( + getX(batch, xR, xC, d1), + getX(batch, xR, xC, d1 + 1), + getX(batch, xR, xC, d1 + 2), + getX(batch, xR, xC, d1 + 3) + ); + dotProd += dot(xValues, wValues); + } else { + vec4 xValues = vec4( + getX(batch, d1, xR, xC), + getX(batch, d1 + 1, xR, xC), + getX(batch, d1 + 2, xR, xC), + getX(batch, d1 + 3, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + } + + if (${m===1}) { + + if (${g}) { + dotProd += + getX(batch, xR, xC, ${f}) * + getW(wR, wC, ${f}, d2); + } else { + dotProd += + getX(batch, ${f}, xR, xC) * + getW(wR, wC, ${f}, d2); + } + + } else if (${m===2}) { + vec2 wValues = vec2( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2) + ); + + if (${g}) { + vec2 xValues = vec2( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1) + ); + dotProd += dot(xValues, wValues); + } else { + vec2 xValues = vec2( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } else if (${m===3}) { + vec3 wValues = vec3( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2), + getW(wR, wC, ${f} + 2, d2) + ); + + if (${g}) { + vec3 xValues = vec3( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1), + getX(batch, xR, xC, ${f} + 2) + ); + dotProd += dot(xValues, wValues); + } else { + vec3 xValues = vec3( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC), + getX(batch, ${f} + 2, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } + } + } + + float result = dotProd; + ${C} + ${w} + setOutput(result); + } + `}}class cP{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const e=t.padInfo.front,s=t.padInfo.top,o=t.padInfo.left,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,d=t.filterDepth,h=t.filterHeight,p=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4;this.userCode=` + const ivec3 strides = ivec3(${r}, ${i}, ${a}); + const ivec3 pads = ivec3(${e}, ${s}, ${o}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d2 = coords.u; + + ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xFCorner = xFRCCorner.x; + int xRCorner = xFRCCorner.y; + int xCCorner = xFRCCorner.z; + + // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get + // y(yF, yR, yC, d2). ? = to be determined. : = across all + // values in that axis. + float dotProd = 0.0; + for (int wF = 0; wF < ${d}; wF++) { + int xF = xFCorner + wF * ${c}; + + if (xF < 0 || xF >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${h}; wR++) { + int xR = xRCorner + wR * ${l}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${u}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3) + ); + vec4 wValues = vec4( + getW(wF, wR, wC, d1, d2), + getW(wF, wR, wC, d1 + 1, d2), + getW(wF, wR, wC, d1 + 2, d2), + getW(wF, wR, wC, d1 + 3, d2) + ); + + dotProd += dot(xValues, wValues); + } + + if (${m===1}) { + dotProd += + getX(batch, xF, xR, xC, ${f}) * + getW(wF, wR, wC, ${f}, d2); + } else if (${m===2}) { + vec2 xValues = vec2( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1) + ); + vec2 wValues = vec2( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (${m===3}) { + vec3 xValues = vec3( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1), + getX(batch, xF, xR, xC, ${f} + 2) + ); + vec3 wValues = vec3( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2), + getW(wF, wR, wC, ${f} + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class J1{constructor(t,e=!1,s=null,o=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.padInfo.left,a=t.strideWidth,c=t.dilationWidth,l=t.filterHeight,u=t.filterWidth,d=u;let h=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g=0 && xR < inDims[0]) { + `;for(let g=0;g<(d+1)/2;g++){const b=g*2;if(h+=` + xC = xCCorner + ${b*c}; + `,a===1){if(b= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + `,c===1&&b>0?h+=` + xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy); + `:h+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${b} = vec4(previous.zw, xTexelC${b}.xy); + } else { + xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy); + } + `):h+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + xC${b} = xTexelC${b}; + `,b+1= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + `,c>1?h+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy); + } else { + xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy); + } + `:h+=` + xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy); + `):x===1?h+=` + xC${b+1} = xTexelC${b}; + `:h+=` + xCOffset = xC + ${x}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + + xC${b+1} = xTexelC${b+1}; + `}}else b= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + + xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw); + `,b+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy); + `)):(h+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.); + } + xTexelC${b+1}Ready = 1; + } + + xC${b} = vec4( + xTexelC${b}.xy, xTexelC${b+1}.xy); + `,b+1= 0) { + // Use custom imod instead mod. On Intel GPU, mod may generate + // unexpected value. + // https://github.com/tensorflow/tfjs/issues/5447 + offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1]; + d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) / + inChannels); + + if(d1 < inputShape[${a}] && d1 >= 0) { + + ch = imod(pos, inChannels); + + if (${r}) { + innerDims = vec2(d1, ch); + result[${u*2+d}] = getChannel( + getA(rc.x, d0, int(innerDims.x), + int(innerDims.y)), innerDims); + } else { + innerDims = vec2(d0, d1); + result[${u*2+d}] = getChannel( + getA(rc.x, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + } + `;this.userCode=` + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0); + + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + + ${l} + + ${o.output} = result; + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ml(n,t){const e=n.length;return e>=3?t?[...n.slice(0,-3),n[e-3]*n[e-2],n[e-1]]:[...n.slice(0,-3),n[e-3],n[e-2]*n[e-1]]:!t&&e===1&&n[0]>1?[n[0],1]:null}function j1({x:n,filter:t,convInfo:e,backend:s,bias:o=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:a=null}){const c=n.shape,l=s.texData.get(n.dataId),u=e.inChannels,d=c[0]*c[1]*c[2],h=e.outChannels,p=e.dataFormat==="channelsLast",f=!1,m=!1;let g;const b=[];if(r!=null){const y=Ml(r.shape,p);y!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:y}}),b.push(r))}if(o!=null){const y=Ml(o.shape,p);y!=null&&(o=tt({inputs:{x:o},backend:s,attrs:{shape:y}}),b.push(o))}if(!((d===1||h===1)&&u>A1)&&l.isPacked&&p&&l.texture!=null&&c[2]%2!==0&&Rt(l.shape.slice(-3),c.slice(-3))){const y=c[0]*c[1]*(c[2]+1),w={dataId:n.dataId,shape:[1,y,e.inChannels],dtype:n.dtype},C=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,v(kl(l.shape,w.shape),()=>`packed reshape ${l.shape} to ${w.shape} isn't free`);const k=tt({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}});b.push(k);const S=Ll({a:w,b:k,backend:s,transposeA:f,transposeB:m,bias:o,activation:a,preluActivationWeights:r,leakyreluAlpha:i}),T=s.texData.get(S.dataId);v(T.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=C,T.shape=e.outShape,g=Je({inputs:{x:S},backend:s}),g.shape=e.outShape,b.push(S)}else{const y=e.outHeight*e.outWidth,w=tt({inputs:{x:n},backend:s,attrs:{shape:p?[e.batchSize,y,e.inChannels]:[e.batchSize,e.inChannels,y]}}),C=tt({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}}),k=Ll({a:p?w:C,b:p?C:w,transposeA:!p,transposeB:m,backend:s,bias:o,activation:a,preluActivationWeights:r,leakyreluAlpha:i});g=tt({inputs:{x:k},backend:s,attrs:{shape:e.outShape}}),b.push(w),b.push(C),b.push(k)}for(const y of b)s.disposeIntermediateTensorInfo(y);return g}function q1({x:n,filter:t,convInfo:e,backend:s,bias:o=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:a=null}){const{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:h,dataFormat:p}=e,f=p==="channelsLast",m=c*l*u,g=h*d,b=[e.batchSize,m,g],x=!0,I=!1,y=[];if(r!=null){const K=Ml(r.shape,f);K!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:K}}),y.push(r))}if(o!=null){const K=Ml(o.shape,f);K!=null&&(o=tt({inputs:{x:o},backend:s,attrs:{shape:K}}),y.push(o))}const w=tt({inputs:{x:t},backend:s,attrs:{shape:[1,m,Z(t.shape)/m]}});y.push(w);const C=new lP(b,e),k=[n.shape,[e.padInfo.top,e.padInfo.left],[e.strideHeight,e.strideWidth],[e.dilationHeight,e.dilationWidth],[e.inChannels],[e.filterWidth*e.inChannels],[e.outWidth]],S=s.runWebGLProgram(C,[n],"float32",k),T=tt({inputs:{x:S},backend:s,attrs:{shape:b}});y.push(S),y.push(T);const R=o!=null,L=r!=null,V=a==="leakyrelu",F=a?aa(a,!0):null,X=new M1(f?T.shape:w.shape,f?w.shape:T.shape,f?[e.batchSize,g,e.outChannels]:[e.batchSize,e.outChannels,g],x,I,R,F,L,V),A=f?[T,w]:[w,T];if(o&&A.push(o),L&&A.push(r),V){const K=s.makeTensorInfo([],"float32",gs(i,"float32"));A.push(K),y.push(K)}const P=s.runWebGLProgram(X,A,"float32"),B=tt({inputs:{x:P},backend:s,attrs:{shape:e.outShape}});y.push(P);for(const K of y)s.disposeIntermediateTensorInfo(K);return B}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dataFormat:c,dilations:l,dimRoundingMode:u}=s,d=os(c),h=ye(o.shape,r.shape,i,l,a,u,!1,d);let p;if(h.filterHeight===1&&h.filterWidth===1&&h.dilationHeight===1&&h.dilationWidth===1&&h.strideHeight===1&&h.strideWidth===1&&(h.padInfo.type==="SAME"||h.padInfo.type==="VALID"))p=j1({x:o,filter:r,convInfo:h,backend:e});else if(h.strideWidth<=2&&d==="channelsLast"&&z().getBool("WEBGL_EXP_CONV")){const m=new J1(h),g=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];p=e.runWebGLProgram(m,[o,r],"float32",g)}else if(z().getBool("WEBGL_CONV_IM2COL"))p=q1({x:o,filter:r,convInfo:h,backend:e});else{const m=new Q1(h);p=e.runWebGLProgram(m,[o,r],"float32")}const f=tt({inputs:{x:p},backend:e,attrs:{shape:h.outShape}});return e.disposeIntermediateTensorInfo(p),f}const dP={kernelName:Ra,backendName:"webgl",kernelFunc:uP};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class hP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideHeight,s=t.strideWidth,o=t.padInfo.top,r=t.padInfo.left,i=t.dataFormat==="channelsLast";this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int d2 = coords.w; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${e} - ${o}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${r}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + ${i?`float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC); + float xValue = getX(b, d1, xR, xC); + dotProd += (xValue * dyValue);`} + } + } + } + setOutput(dotProd); + } + `}}class pP{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=t.dataFormat==="channelsLast",a=e-1-t.padInfo.top,c=s-1-t.padInfo.left,l=i?1:2,u=i?2:3,d=i?3:1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${c}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[${d}]; + + ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${e}; wR++) { + float dyR = float(dyRCorner + wR) / ${o}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${e} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + for (int d2 = 0; d2 < ${t.outChannels}; d2++) { + + if (${i}) { + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } else { + float xValue = getDy(batch, d2, idyR, idyC); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + + } + } + } + setOutput(dotProd); + } + `}}class fP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideDepth,s=t.strideHeight,o=t.strideWidth,r=t.padInfo.front,i=t.padInfo.top,a=t.padInfo.left;this.userCode=` + void main() { + ivec5 coords = getOutputCoords(); + int wF = coords.x; + int wR = coords.y; + int wC = coords.z; + int d1 = coords.w; + int d2 = coords.u; + + float dotProd = 0.0; + + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yF = 0; yF < ${t.outDepth}; yF++) { + int xF = wF + yF * ${e} - ${r}; + + if (xF < 0 || xF >= ${t.inDepth}) { + continue; + } + + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${s} - ${i}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${o} - ${a}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float dyValue = getDy(b, yF, yR, yC, d2); + float xValue = getX(b, xF, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + } + setOutput(dotProd); + } + `}}class mP{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterDepth,s=t.filterHeight,o=t.filterWidth,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=e-1-t.padInfo.front,l=s-1-t.padInfo.top,u=o-1-t.padInfo.left;this.userCode=` + const ivec3 pads = ivec3(${c}, ${l}, ${u}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.u; + + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyFCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + float dotProd = 0.0; + for (int wF = 0; wF < ${e}; wF++) { + float dyF = float(dyFCorner + wF) / ${r}.0; + + if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) { + continue; + } + int idyF = int(dyF); + + int wFPerm = ${e} - 1 - wF; + + for (int wR = 0; wR < ${s}; wR++) { + float dyR = float(dyRCorner + wR) / ${i}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${s} - 1 - wR; + + for (int wC = 0; wC < ${o}; wC++) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${o} - 1 - wC; + + for (int d2 = 0; d2 < ${t.outChannels}; d2++) { + float xValue = getDy(batch, idyF, idyR, idyC, d2); + float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,dataFormat:c,dimRoundingMode:l,filterShape:u}=s,d=os(c),h=ye(o.shape,u,i,1,a,l,!1,d),p=new hP(h);return e.runWebGLProgram(p,[o,r],"float32")}const bP={kernelName:uu,backendName:"webgl",kernelFunc:gP};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xP{constructor(t){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=t.inShape,this.enableShapeUniforms=Ne(this.outputShape.length);const e=t.filterHeight,s=t.filterWidth,o=e-1-t.padInfo.top,r=s-1-t.padInfo.left;this.userCode=` + const ivec2 pads = ivec2(${o}, ${r}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + + ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + vec4 result = vec4(0.); + for (int wR = 0; wR < ${e}; wR++) { + float dyR = float(dyRCorner + wR) / strides[0]; + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + int wRPerm = ${e} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + int wCPerm = ${s} - 1 - wC; + + float dyC = float(dyCCorner + wC) / strides[1]; + bool idyCVal = (dyC >= 0.0) && (dyC < ${t.outWidth}.0) + && (fract(dyC) == 0.0); + int idyC = int(dyC); + + float dyC2 = float(dyCCorner + wC + 1) / strides[1]; + bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${t.outWidth}.0) + && (fract(dyC2) == 0.0); + int idyC2 = int(dyC2); + + if (idyCVal && idyCVal2) { + for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec4 dySample2 = (idyC / 2 == idyC2 / 2) ? + dySample : getDy(batch, idyR, idyC2, d2); + + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + + dyValue = mod(float(idyC2), 2.) == 0. ? + dySample2.xy : dySample2.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal) { + for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal2) { + for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC2, d2); + vec2 dyValue = mod(float(idyC2), 2.) == 0. ? + dySample.xy : dySample.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } + } + } + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{inputShape:i,strides:a,pad:c,dataFormat:l,dimRoundingMode:u}=s,d=os(l),h=ye(i,r.shape,a,1,c,u,!1,d);if(z().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&d==="channelsLast"){const p=[[h.strideHeight,h.strideWidth]],f=new xP(h);return e.runWebGLProgram(f,[o,r],"float32",p)}else{const p=new pP(h);return e.runWebGLProgram(p,[o,r],"float32")}}const IP={kernelName:$a,backendName:"webgl",kernelFunc:yP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c}=s,l=ws(o.shape,r.shape,i,c,a),u=new cP(l);return e.runWebGLProgram(u,[o,r],"float32")}const CP={kernelName:Ga,backendName:"webgl",kernelFunc:wP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,filterShape:c}=s,l=ws(o.shape,c,i,1,a),u=new fP(l);return e.runWebGLProgram(u,[o,r],"float32")}const SP={kernelName:du,backendName:"webgl",kernelFunc:vP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{pad:i,strides:a,inputShape:c}=s,l=ws(c,r.shape,a,1,i),u=new mP(l);return e.runWebGLProgram(u,[o,r],"float32")}const TP={kernelName:hu,backendName:"webgl",kernelFunc:kP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NP=br+` + return cos(x); +`,RP=` + vec4 result = cos(x); + bvec4 isNaN = isnan(x); + ${To} + return result; +`,$P=Tt({opSnippet:NP,packedOpSnippet:RP}),GP={kernelName:Dr,backendName:"webgl",kernelFunc:$P};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LP=Tt({opSnippet:` + float e2x = exp(-x); + return (e2x + 1.0 / e2x) / 2.0; +`}),EP={kernelName:Wr,backendName:"webgl",kernelFunc:LP};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class DP{constructor(t,e,s,o,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[i,a,c,l]=t,[u]=e,[d,h]=s;this.outputShape=[u,d,h,l];const p=o==="bilinear"?1:0,[f,m]=[`${a-1}.0`,`${c-1}.0`],[g,b,x]=d>1?[`${(a-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[I,y,w]=h>1?[`${(c-1)/(h-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=` + const float height_ratio = float(${g}); + const float width_ratio = float(${I}); + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int y = coords[1]; + int x = coords[2]; + int d = coords[3]; + + // get box vals + float y1 = getBoxes(b,0); + float x1 = getBoxes(b,1); + float y2 = getBoxes(b,2); + float x2 = getBoxes(b,3); + + // get image in batch index + int bInd = round(getBoxInd(b)); + if(bInd < 0 || bInd >= ${i}) { + return; + } + + float height_scale = ${b}; + float width_scale = ${y}; + + float in_y = ${x}; + if( in_y < 0.0 || in_y > ${f} ) { + setOutput(float(${r})); + return; + } + float in_x = ${w}; + if( in_x < 0.0 || in_x > ${m} ) { + setOutput(float(${r})); + return; + } + + vec2 sourceFracIndexCR = vec2(in_x,in_y); + if(${p} == 1) { + // Compute the four integer indices. + ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); + ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); + + float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); + float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); + float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); + float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); + + vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + + float top = topLeft + (topRight - topLeft) * fracCR.x; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + float newValue = top + (bottom - top) * fracCR.y; + setOutput(newValue); + } else { + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestCR = ivec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); + setOutput(newValue); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WP={kernelName:fu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{image:o,boxes:r,boxInd:i}=t,{cropSize:a,method:c,extrapolationValue:l}=s,u=new DP(o.shape,r.shape,a,c,l);return e.runWebGLProgram(u,[o,r,i],"float32")}};var da;(function(n){n.Prod="*",n.Sum="+"})(da||(da={}));class tI{constructor(t,e,s,o){this.op=t,this.outputShape=e,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const r=this.outputShape.length,i=this.op===da.Prod?"1.0":"0.0",a=s?i:`getX(${eI(r,"coords",this.op)})`,c=this.outputShape[this.outputShape.length-1];let l="",u="";s?(l=o?`end != ${c-1}`:"end != 0",u=o?"end + 1":"end - 1"):(l=o?`end + pow2 < ${c}`:"end >= pow2",u=o?"end + pow2":"end - pow2"),this.userCode=` + void main() { + ${Wt(r)} coords = getOutputCoords(); + int end = ${nI(r,"coords",this.op)}; + float val = ${a}; + int pow2 = int(pow(2.0, index)); + if (${l}) { + int idx = ${u}; + ${nI(r,"coords",this.op)} = idx; + val ${this.op}= getX(${eI(r,"coords",this.op)}); + } + setOutput(val); + } + `}}function eI(n,t,e){if(n===1)return`${t}`;if(n===2)return`${t}.x, ${t}.y`;if(n===3)return`${t}.x, ${t}.y, ${t}.z`;if(n===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}function nI(n,t,e){if(n===1)return`${t}`;if(n===2)return`${t}.y`;if(n===3)return`${t}.z`;if(n===4)return`${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sI(n,t,e,s,o,r){const i=t.shape.length,a=Yt([s],i);let c=t;a!=null&&(c=Me({inputs:{x:t},backend:e,attrs:{perm:a}}));const l=ee(1,i)[0];if(l!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);const u=c.shape[l];let d=Je({inputs:{x:c},backend:e});for(let h=0;h<=Math.ceil(Math.log2(u))-1;h++){const p=new tI(n,c.shape,!1,r),f=[[h]],m=d;d=e.runWebGLProgram(p,[d],d.dtype,f),e.disposeIntermediateTensorInfo(m)}if(o){const h=new tI(n,c.shape,o,r),p=d;d=e.runWebGLProgram(h,[d],d.dtype),e.disposeIntermediateTensorInfo(p)}if(a!=null){const h=Cs(a),p=Me({inputs:{x:d},backend:e,attrs:{perm:h}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(c),p}return d}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;return sI(da.Prod,o,e,r,i,a)}const VP={kernelName:pu,backendName:"webgl",kernelFunc:MP};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;return sI(da.Sum,o,e,r,i,a)}const zP={kernelName:La,backendName:"webgl",kernelFunc:FP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i,binaryOutput:a}=s;if(o.shape.length===1){const c=e.readSync(o.dataId),l=e.readSync(r.dataId),u=C1(c,l,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,u)}else if(o.shape.length===2){const c=e.bufferSync(o),l=e.bufferSync(r),u=UF(c,l,i,a);return e.makeTensorInfo(u.shape,r.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}const AP={kernelName:mu,backendName:"webgl",kernelFunc:XP};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class PP{constructor(t,e,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=s,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int h = ${this.getHeightCoordString()}; + int w = ${this.getWidthCoordString()}; + int d = ${this.getDepthCoordString()}; + + int in_h = h / ${e}; + int offset_h = imod(h, ${e}); + int in_w = w / ${e}; + int offset_w = imod(w, ${e}); + int offset_d = (offset_h * ${e} + offset_w) * + ${this.getOutputDepthSize()}; + int in_d = d + offset_d; + + float result = ${this.getInputSamplingString()}; + setOutput(result); + } + `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockSize:r,dataFormat:i}=s,a=o.shape[0],c=i==="NHWC"?o.shape[1]:o.shape[2],l=i==="NHWC"?o.shape[2]:o.shape[3],u=i==="NHWC"?o.shape[3]:o.shape[1],d=c*r,h=l*r,p=u/(r*r),f=i==="NHWC"?[a,d,h,p]:[a,p,d,h],m=new PP(f,r,i);return e.runWebGLProgram(m,[o],o.dtype)}const KP={kernelName:gu,backendName:"webgl",kernelFunc:OP};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oI{constructor(t,e=!1,s=null,o=!1,r=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.filterHeight,a=t.filterWidth,c=t.outChannels/t.inChannels;let l="",u="";s&&(o?l=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:r?l=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:l=` + float activation(float x) { + ${s} + } + `,u="result = activation(result);");const d=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${l} + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + ivec2 xRCCorner = coords.yz * strides - pads; + int d2 = coords.w; + int d1 = d2 / ${c}; + int q = d2 - d1 * ${c}; + + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations. + for (int wR = 0; wR < ${i}; wR++) { + int xR = xRCorner + wR * dilations[0]; + + if (xR < 0 || xR >= inDims[0]) { + continue; + } + + for (int wC = 0; wC < ${a}; wC++) { + int xC = xCCorner + wC * dilations[1]; + + if (xC < 0 || xC >= inDims[1]) { + continue; + } + + float xVal = getX(batch, xR, xC, d1); + float wVal = getW(wR, wC, d1, q); + dotProd += xVal * wVal; + } + } + + float result = dotProd; + ${d} + ${u} + setOutput(result); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rI{constructor(t,e=!1,s=null,o=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.outChannels/t.inChannels,a=t.padInfo.left,c=t.strideWidth,l=t.dilationWidth,u=t.filterHeight,d=t.filterWidth,h=d;let p=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let b=0;b=0 && xR < inDims[0]) { + `;for(let b=0;b<(h+1)/2;b++){const x=b*2;if(p+=` + xC = xCCorner + ${x*l}; + `,c===1){if(x= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) { + xTexelC${x} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${x}.zw = vec2(0.0); + } + xTexelC${x}Ready = 1; + } + `,l===1&&x>0?p+=` + xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.xy); + `:p+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${x} = vec4(previous.zw, xTexelC${x}.xy); + } else { + xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy); + } + `):p+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) { + xTexelC${x} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${x}.zw = vec2(0.0); + } + xTexelC${x}Ready = 1; + } + + xC${x} = xTexelC${x}; + `,x+1= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) { + xTexelC${x+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${x+1}.zw = vec2(0.0); + } + xTexelC${x+1}Ready = 1; + } + `,l>1?p+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy); + } else { + xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy); + } + `:p+=` + xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy); + `):I===1?p+=` + xC${x+1} = xTexelC${x}; + `:p+=` + xCOffset = xC + ${I}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) { + xTexelC${x+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${x+1}.zw = vec2(0.0); + } + xTexelC${x+1}Ready = 1; + } + + xC${x+1} = xTexelC${x+1}; + `}}else x= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) { + xTexelC${x} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${x}.zw = vec2(0.0); + } + xTexelC${x}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) { + xTexelC${x+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${x+1}.zw = vec2(0.0); + } + xTexelC${x+1}Ready = 1; + } + + xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw); + `,x+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy); + `)):(p+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) { + xTexelC${x} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${x}.zw = vec2(0.0); + } + xTexelC${x}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) { + xTexelC${x+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${x+1}.zw = vec2(0.); + } + xTexelC${x+1}Ready = 1; + } + + xC${x} = vec4( + xTexelC${x}.xy, xTexelC${x+1}.xy); + `,x+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);const d=ye(o.shape,r.shape,i,u,a,l,!0);let h;z().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?h=new rI(d):h=new oI(d);const p=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return e.runWebGLProgram(h,[o,r],"float32",p)}const BP={kernelName:Ea,backendName:"webgl",kernelFunc:ZP};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class HP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideHeight,s=t.strideWidth,o=t.padInfo.top,r=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int dm = coords.w; + int d2 = d1 * ${i} + dm; + + float dotProd = 0.0; + + // TO DO: Vec4 over the batch size + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${e} - ${o}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${r}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + setOutput(dotProd); + } + `}}class _P{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=e-1-t.padInfo.top,a=s-1-t.padInfo.left,c=t.outChannels/t.inChannels;this.userCode=` + const ivec2 pads = ivec2(${i}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + ivec2 dyCorner = coords.yz - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + float dotProd = 0.0; + + for (int wR = 0; wR < ${e}; wR++) { + float dyR = float(dyRCorner + wR) / ${o}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${e} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + // TO DO: Vec4 over the channelMul + for (int dm = 0; dm < ${c}; dm++) { + int d2 = d1 * ${c} + dm; + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,filterShape:u}=s,d=ye(o.shape,u,i,a,c,l,!0),h=new HP(d);return e.runWebGLProgram(h,[o,r],"float32")}const YP={kernelName:bu,backendName:"webgl",kernelFunc:UP};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,inputShape:u}=s,d=ye(u,r.shape,i,a,c,l,!0),h=new _P(d);return e.runWebGLProgram(h,[o,r],"float32")}const JP={kernelName:xu,backendName:"webgl",kernelFunc:QP};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jP{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; + setOutput(val); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qP(n){const{inputs:t,backend:e}=n,{x:s}=t,o=[...s.shape,...s.shape],r=Z(s.shape),i=tt({inputs:{x:s},backend:e,attrs:{shape:[r]}}),a=new jP(r),c=e.runWebGLProgram(a,[i],i.dtype),l=tt({inputs:{x:c},backend:e,attrs:{shape:o}});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(c),l}const tO={kernelName:yf,backendName:"webgl",kernelFunc:qP};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eO{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const{inHeight:e,inWidth:s,padInfo:o,strideHeight:r,strideWidth:i,filterHeight:a,filterWidth:c,dilationHeight:l,dilationWidth:u}=t,{top:d,left:h}=o;this.userCode=` + const ivec2 strides = ivec2(${r}, ${i}); + const ivec2 pads = ivec2(${d}, ${h}); + const float neg_infinity = -3.4e38; + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.w; + ivec2 outTopLeftCorner = + coords.yz * strides - pads; + int hBeg = outTopLeftCorner.x; + int wBeg = outTopLeftCorner.y; + + float curVal = neg_infinity; + for (int h = 0; h < ${a}; h++) { + int hIn = hBeg + h * ${l}; + + if (hIn >= 0 && hIn < ${e}) { + for (int w = 0; w < ${c}; w++) { + int wIn = wBeg + w * ${u}; + + if (wIn >= 0 && wIn < ${s}) { + float xVal = getX(batch, hIn, wIn, d1); + float wVal = getW(h, w, d1); + + float val = xVal + wVal; + if (val > curVal) { + curVal = val; + } + } + } + } + } + + float result = curVal; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c}=s,l=Si(o.shape,r.shape,i,a,"NHWC",c);let u;const d=new eO(l);u=e.runWebGLProgram(d,[o,r],"float32");const h=tt({inputs:{x:u},backend:e,attrs:{shape:l.outShape}});return e.disposeIntermediateTensorInfo(u),h}const sO={kernelName:Da,backendName:"webgl",kernelFunc:nO};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oO(n){const{inputs:t,backend:e,attrs:s}=n,{equation:o}=s,r=t,{allDims:i,summedDims:a,idDims:c}=bh(o,r.length);yh(i.length,c,r);const{path:l,steps:u}=Ih(a,c),d=u.length;let h=null,p=i.length;const f=[];for(let m=0;m=0&&(h=Gl({inputs:{x:h},backend:e,attrs:{axis:l[m]-(i.length-p),keepDims:!1}}),f.push(h)),p--)}for(const m of f)m!==h&&e.disposeIntermediateTensorInfo(m);return h}const rO={kernelName:wu,backendName:"webgl",kernelFunc:oO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iO=Tt({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`}),aO={kernelName:Vr,backendName:"webgl",kernelFunc:iO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cO="return (b >= 0.0) ? a : a * (b + 1.0);",lO=` + vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); + return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); +`,uO={kernelName:Cu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e}=n,{dy:s,y:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(lO,s.shape,o.shape):new ko(cO,s.shape,o.shape);return e.runWebGLProgram(r,[s,o],s.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dO=Ce({opSnippet:"return float(a == b);",packedOpSnippet:` + return vec4(equal(a, b)); +`,dtype:"bool",cpuKernelImpl:qF}),hO={kernelName:Wa,backendName:"webgl",kernelFunc:dO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pO=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + float p = ${lh}; + float a1 = ${uh}; + float a2 = ${dh}; + float a3 = ${hh}; + float a4 = ${ph}; + float a5 = ${fh}; + + float sign = sign(x); + x = abs(x); + float t = 1.0 / (1.0 + p * x); + return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); +`,fO=Tt({opSnippet:pO}),mO={kernelName:Fr,backendName:"webgl",kernelFunc:fO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gO=br+` + return exp(x); +`,iI=Tt({opSnippet:gO,packedOpSnippet:` + vec4 result = exp(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,cpuKernelImpl:tz,dtype:"float32"}),bO={kernelName:zr,backendName:"webgl",kernelFunc:iI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vp(n){const{inputs:t,attrs:e,backend:s}=n,{dim:o}=e,{input:r}=t,i=r.shape.length,a=r.shape.slice();let c=o;return o<0&&(v(-(i+1)<=o,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),c=i+o+1),a.splice(c,0,1),tt({inputs:{x:r},backend:s,attrs:{shape:a}})}const xO={kernelName:Ma,backendName:"webgl",kernelFunc:Vp};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aI="return exp(x) - 1.0;",yO=Tt({opSnippet:aI,packedOpSnippet:aI,cpuKernelImpl:ez}),IO={kernelName:Xr,backendName:"webgl",kernelFunc:yO};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cI{constructor(t,e,s){this.variableNames=["real","imag"];const o=e[1];this.outputShape=e;const r=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=s?`${o}.0`:"1.0";let a;if(t==="real")a="return real * expR - imag * expI;";else if(t==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=` + const float exponentMultiplier = ${r}; + + float unaryOpComplex(float real, float expR, float imag, float expI) { + ${a} + } + + float mulMatDFT(int batch, int index) { + float indexRatio = float(index) / float(${o}); + float exponentMultiplierTimesIndexRatio = + exponentMultiplier * indexRatio; + + float result = 0.0; + + for (int i = 0; i < ${o}; i++) { + // x = (-2|2 * PI / N) * index * i; + float x = exponentMultiplierTimesIndexRatio * float(i); + float expR = cos(x); + float expI = sin(x); + float real = getReal(batch, i); + float imag = getImag(batch, i); + + result += + unaryOpComplex(real, expR, imag, expI) / ${i}; + } + + return result; + } + + void main() { + ivec2 coords = getOutputCoords(); + setOutput(mulMatDFT(coords[0], coords[1])); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lI(n,t,e){const s=e.texData.get(n.dataId),o=Z(n.shape),r=n.shape[n.shape.length-1],i=o/r,a=tt({inputs:{x:n},backend:e,attrs:{shape:[i,r]}}),c=a.shape,l=new cI("real",c,t),u=new cI("imag",c,t),d=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:c},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:c}],h=e.runWebGLProgram(l,d,"float32"),p=e.runWebGLProgram(u,d,"float32"),f=zs({inputs:{real:h,imag:p},backend:e});e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p);const m=tt({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(f),m}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wO(n){const{inputs:t,backend:e}=n,{input:s}=t;return lI(s,!1,e)}const CO={kernelName:vu,backendName:"webgl",kernelFunc:wO};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vO{constructor(t,e){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=t,this.userCode=` + void main() { + // Input can be obtained from uniform value. + setOutput(value); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ha(n){const{backend:t,attrs:e}=n,{shape:s,value:o}=e;let{dtype:r}=e;if(r=r||Mo(o),r==="string"){const i=qt(r,Z(s));return i.fill(o),t.makeTensorInfo(s,r,i)}else{const i=new vO(s,o),a=[[o]];return t.runWebGLProgram(i,[],r,a)}}const SO={kernelName:Su,backendName:"webgl",kernelFunc:ha};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kO{constructor(t){this.variableNames=["Image"],this.outputShape=[];const e=t[2];this.outputShape=t,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + + int coordX = ${e} - x - 1; + float outputValue; + if(coordX >= 0 && coordX < ${e}) { + outputValue = getImage(coords[0], coords[1], coordX, coords[3]); + } else { + outputValue = getImage(coords[0], coords[1], coords[2], coords[3]); + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TO={kernelName:ku,backendName:"webgl",kernelFunc:({inputs:n,backend:t})=>{const{image:e}=n,s=t,o=new kO(e.shape);return s.runWebGLProgram(o,[e],e.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uI="return floor(x);",NO=Tt({opSnippet:uI,packedOpSnippet:uI,cpuKernelImpl:nz}),RO={kernelName:Ar,backendName:"webgl",kernelFunc:NO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $O=Ce({opSnippet:` + float s = sign(a) * sign(b); + int ia = round(a); + int ib = round(b); + if (ib != 0) { + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + return float(idiv(ia, ib, s)); + } else { + return NAN; + } +`,packedOpSnippet:` + ivec4 ia = round(a); + ivec4 ib = round(b); + bvec4 cond = notEqual(ib, ivec4(0)); + ivec4 result = ivec4(0); + vec4 s = sign(a) * sign(b); + + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + if (cond[0]) { + result[0] = idiv(ia[0], ib[0], s[0]); + } + if (cond[1]) { + result[1] = idiv(ia[1], ib[1], s[1]); + } + if (cond[2]) { + result[2] = idiv(ia[2], ib[2], s[2]); + } + if (cond[3]) { + result[3] = idiv(ia[3], ib[3], s[3]); + } + return vec4(result); +`,dtype:"int32"}),GO={kernelName:Pr,backendName:"webgl",kernelFunc:$O};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LO{constructor(t){this.variableNames=["A"];const e=De(),[s,o]=t;this.outputShape=t,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}.0, ${s}.0); + + vec4 values = ${e.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + setOutput(floor(value * 255.0 + 0.5)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class EO{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const e=De(),[s,o]=t;this.outputShape=t,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + + vec4 result = vec4(0.); + + for(int row=0; row<=1; row++) { + for(int col=0; col<=1; col++) { + texC = coords[1] + row; + depth = coords[2] + col; + + vec2 uv = (vec2(texC, texR) + halfCR) / + vec2(${o}.0, ${s}.0); + vec4 values = ${e.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + result[row * 2 + col] = floor(value * 255.0 + 0.5); + } + } + + ${e.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DO={kernelName:Zu,backendName:"webgl",kernelFunc:WO};let yr,Fp=z().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function WO(n){const{inputs:t,backend:e,attrs:s}=n;let{pixels:o}=t;const{numChannels:r}=s,i=typeof HTMLVideoElement<"u"&&o instanceof HTMLVideoElement,a=typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement,[c,l]=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],u=[l,c],d=[l,c,r];if(a||i){const m=z().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(yr==null||m!==Fp)&&(Fp=m,yr=document.createElement("canvas").getContext("2d",{willReadFrequently:Fp})),yr.canvas.width=c,yr.canvas.height=l,yr.drawImage(o,0,0,c,l),o=yr.canvas}const h=e.makeTensorInfo(u,"int32");e.texData.get(h.dataId).usage=an.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(h.dataId),o);const p=z().getBool("WEBGL_PACK")?new EO(d):new LO(d),f=e.runWebGLProgram(p,[h],"int32");return e.disposeData(h.dataId),f}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:f}=s,m=os(u),g=ye(o.shape,r.shape,c,d,l,h,!1,m);let b;const x=[],I=i!=null,y=a!=null,w=p==="leakyrelu",C=()=>{const S=[o,r],T=(R,L)=>{if(L==="NCHW"&&R.shape.length===1&&R.shape[0]!==1){const V=tt({inputs:{x:R},backend:e,attrs:{shape:[R.shape[0],1,1]}});return x.push(V),V}return R};if(I&&S.push(T(i,u)),y&&S.push(T(a,u)),w){const R=e.makeTensorInfo([],"float32",gs(f,"float32"));S.push(R),x.push(R)}return S};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=j1({x:o,filter:r,convInfo:g,backend:e,bias:i,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&z().getBool("WEBGL_EXP_CONV")){const S=p?aa(p,!0):null,T=new J1(g,I,S,y,w),R=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],L=C();b=e.runWebGLProgram(T,L,"float32",R)}else if(z().getBool("WEBGL_CONV_IM2COL"))b=q1({x:o,filter:r,convInfo:g,backend:e,bias:i,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else{const S=p?aa(p,!1):null,T=new Q1(g,I,S,y,w),R=C();b=e.runWebGLProgram(T,R,"float32")}const k=tt({inputs:{x:b},backend:e,attrs:{shape:g.outShape}});return x.push(b),x.forEach(S=>e.disposeIntermediateTensorInfo(S)),k}const VO={kernelName:Ic,backendName:"webgl",kernelFunc:MO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:h,leakyreluAlpha:p}=s,f=[];let m=u;m==null&&(m=[1,1]),v(Te(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);const g=ye(o.shape,r.shape,c,m,l,d,!0),b=z().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,x=h?aa(h,b):null,I=[o,r],y=i!=null,w=a!=null,C=h==="leakyrelu";if(y&&I.push(i),w&&I.push(a),C){const R=e.makeTensorInfo([],"float32",gs(p,"float32"));I.push(R),f.push(R)}let k;b?k=new rI(g,y,x,w,C):k=new oI(g,y,x,w,C);const S=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],T=e.runWebGLProgram(k,I,"float32",S);return f.forEach(R=>e.disposeIntermediateTensorInfo(R)),T}const zO={kernelName:zf,backendName:"webgl",kernelFunc:FO};class XO{constructor(t,e,s,o){this.sliceDim=t,this.strides=e,this.paramsShape=o,this.variableNames=["x","indices"],this.outputShape=s;const r=Wt(s.length);let i=` + int index;`;for(let a=0;a= ${this.paramsShape[a]}; + flattenIndex += index * ${this.strides[a]};`;this.userCode=` + void main() { + ${r} coords = getOutputCoords(); + int flattenIndex = 0; + bool out_of_bounds = false; + + ${i} + + setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1])); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AO(n){const{inputs:t,backend:e}=n,{params:s,indices:o}=t,r=o.shape,i=r[r.length-1],a=Z(s.shape),[c,l,u,d]=Jd(s,o),h=tt({inputs:{x:o},backend:e,attrs:{shape:[l,i]}}),p=tt({inputs:{x:s},backend:e,attrs:{shape:[Z(s.shape)/u,u]}});if(e.shouldExecuteOnCPU([s,o])||s.dtype==="string"){const b=e.readSync(o.dataId),x=e.bufferSync(s),I=sz(b,x,s.dtype,l,i,u,d,s.shape,a);return e.makeTensorInfo(c,s.dtype,I.values)}const f=new XO(i,d,[l,u],s.shape),m=e.runWebGLProgram(f,[p,h],p.dtype),g=tt({inputs:{x:m},backend:e,attrs:{shape:c}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),g}const PO={kernelName:If,backendName:"webgl",kernelFunc:AO};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class OO{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;const s=Wt(this.rank),o=KO(t);this.userCode=` + void main() { + ${s} resRC = getOutputCoords(); + int index = int(getIndices(resRC.x, resRC.z)); + float inBounds = (index >= 0) && (index < ${t[2]}) ? 1.0 : 0.0; + setOutput(inBounds * getA(${o})); + } + `}}function KO(n,t){const e=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let o=0;o=0,()=>`GatherV2: the index value ${w} is not in [0, ${I-1}]`)}}const l=Sh(o,r,c,a),u=Z(r.shape),d=[],h=tt({inputs:{x:o},backend:e,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),p=tt({inputs:{x:r},backend:e,attrs:{shape:[l.batchSize,u/l.batchSize]}});d.push(h),d.push(p);const f=[l.batchSize,l.outerSize,u/l.batchSize,l.sliceSize];if(e.shouldExecuteOnCPU([o,r])||o.dtype==="string"){const x=e.bufferSync(p),I=e.bufferSync(h),y=oz(I,x,f);return d.forEach(w=>e.disposeIntermediateTensorInfo(w)),e.makeTensorInfo(l.outputShape,y.dtype,y.values)}const m=new OO(h.shape,f),g=e.runWebGLProgram(m,[h,p],h.dtype);d.push(g);const b=tt({inputs:{x:g},backend:e,attrs:{shape:l.outputShape}});return d.forEach(x=>e.disposeIntermediateTensorInfo(x)),b}const ZO={kernelName:Fa,backendName:"webgl",kernelFunc:dI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BO=Ce({opSnippet:"return float(a > b);",packedOpSnippet:` + return vec4(greaterThan(a, b)); +`,cpuKernelImpl:rz,dtype:"bool"}),HO={kernelName:za,backendName:"webgl",kernelFunc:BO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _O=Ce({opSnippet:"return float(a >= b);",packedOpSnippet:` + return vec4(greaterThanEqual(a, b)); +`,dtype:"bool",cpuKernelImpl:iz}),UO={kernelName:Or,backendName:"webgl",kernelFunc:_O};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YO(n){const{inputs:t,backend:e}=n,{input:s}=t;return lI(s,!0,e)}const QO={kernelName:Tu,backendName:"webgl",kernelFunc:YO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JO=Tt({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),jO={kernelName:Zr,backendName:"webgl",kernelFunc:JO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qO=Tt({opSnippet:"return float(isinf(x));",dtype:"bool"}),tK={kernelName:Br,backendName:"webgl",kernelFunc:qO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eK=Tt({opSnippet:"return float(isnan(x));",dtype:"bool"}),nK={kernelName:Hr,backendName:"webgl",kernelFunc:eK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sK=Ce({opSnippet:"return float(a < b);",packedOpSnippet:` + return vec4(lessThan(a, b)); +`,cpuKernelImpl:az,dtype:"bool"}),oK={kernelName:Aa,backendName:"webgl",kernelFunc:sK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rK=Ce({opSnippet:"return float(a <= b);",packedOpSnippet:` + return vec4(lessThanEqual(a, b)); +`,cpuKernelImpl:cz,dtype:"bool"}),iK={kernelName:Pa,backendName:"webgl",kernelFunc:rK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aK(n){const{backend:t,attrs:e}=n,{start:s,stop:o,num:r}=e,i=lz(s,o,r);return t.makeTensorInfo([i.length],"float32",i)}const cK={kernelName:wf,backendName:"webgl",kernelFunc:aK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lK=br+` + return x < 0.0 ? 0./0. : log(x); +`,uK=Tt({opSnippet:lK,packedOpSnippet:` + vec4 result = log(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r); + result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g); + result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b); + result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a); + return result; +`,cpuKernelImpl:uz}),dK={kernelName:_r,backendName:"webgl",kernelFunc:uK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hK=br+` + return log(1.0 + x); +`,pK=Tt({opSnippet:hK}),fK={kernelName:Ur,backendName:"webgl",kernelFunc:pK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mK=Ce({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:` + return vec4( + vec4(greaterThanEqual(a, vec4(1.0))) * + vec4(greaterThanEqual(b, vec4(1.0)))); +`,dtype:"bool"}),gK={kernelName:Oa,backendName:"webgl",kernelFunc:mK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bK=Tt({opSnippet:"return float(!(x >= 1.0));"}),xK={kernelName:Ka,backendName:"webgl",kernelFunc:bK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yK=Ce({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:` + return min( + vec4(greaterThanEqual(a, vec4(1.0))) + + vec4(greaterThanEqual(b, vec4(1.0))), + vec4(1.0)); +`,dtype:"bool"}),IK={kernelName:Za,backendName:"webgl",kernelFunc:yK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wK{constructor(t,e,s,o,r){this.variableNames=["x"],this.outputShape=[];const i=e,a=t[3]-1;this.outputShape=t;let c;const l=`float(${s}) + float(${o}) * sum`;r===.5?c=`inversesqrt(${l})`:r===1?c=`1.0/(${l})`:c=`exp(log(${l}) * float(-${r}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + int d = coords[3]; + float x = getX(b, r, c, d); + float sum = 0.0; + for (int j = -${i}; j <= ${i}; j++) { + int idx = d + j; + if (idx >= 0 && idx <= ${a}) { + float z = getX(b, r, c, idx); + sum += z * z; + } + } + float val = x * ${c}; + setOutput(val); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class CK{constructor(t,e,s,o,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const i=e,a=t[3]-1;this.outputShape=t;let c;const l=`float(${s}) + float(${o}) * sum`;r===.5?c=`inversesqrt(${l})`:r===1?c=`1.0/(${l})`:c=`exp(log(${l}) * float(-${r}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords.x; + int r = coords.y; + int c = coords.z; + int d = coords.w; + + bool hasNextCol = d < ${this.outputShape[3]}; + bool hasNextRow = c < ${this.outputShape[2]}; + + vec4 sum = vec4(0.); + vec4 xFragAtOutputCoords = getX(b, r, c, d); + + vec4 xAtOutputCoords = vec4( + getChannel(xFragAtOutputCoords, vec2(c, d)), + hasNextCol ? + getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, + hasNextRow ? + getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, + (hasNextRow && hasNextCol) ? + getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 + ); + + int firstChannel = d - ${i}; + vec2 cache = vec2(0.); + if(firstChannel >= 0){ + vec4 firstChannelFrag = getX(b, r, c, firstChannel); + cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); + if(hasNextRow){ + cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); + } + } + + ivec2 depth = ivec2(d, d + 1); + for (int j = - ${i}; j <= ${i}; j++) { + ivec2 idx = depth + j; + bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); + bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a})); + + bool depthInRange = aboveLowerBound.x && belowUpperBound.x; + bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; + + if(depthInRange || depthPlusOneInRange){ + vec4 z = vec4(0.); + vec4 xFragAtCurrentDepth; + z.xz = cache.xy; + if(depthPlusOneInRange && hasNextCol){ + xFragAtCurrentDepth = idx.y != d ? + getX(b, r, c, idx.y) : xFragAtOutputCoords; + z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); + if(hasNextRow){ + z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); + } + } + cache.xy = z.yw; + sum += z * z; + } + } + vec4 result = xAtOutputCoords * ${c}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vK={kernelName:Ba,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{depthRadius:r,bias:i,alpha:a,beta:c}=s,l=z().getBool("WEBGL_PACK_NORMALIZATION")?new CK(o.shape,r,i,a,c):new wK(o.shape,r,i,a,c);return e.runWebGLProgram(l,[o],o.dtype)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class SK{constructor(t,e,s,o,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=s,this.alpha=o,this.beta=r,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + + float result = 0.0; + for (int d = 0; d < ${this.depth}; ++d) { + int depthBegin = int(max(0.0, float(d - ${e}))); + int depthEnd = int(min(float(${this.depth}), + float(d + ${e} + 1))); + + const int MIN_DEPTH_BEGIN = 0; + const int MAX_DEPTH_END = ${this.depth}; + + float norm = 0.0; + for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd) { + norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); + } + else { + break; + } + } + + norm = float(${o}) * norm + float(${s}); + + for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){ + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd){ + float dyi = -2.0 * float(${o}) + * float(${r}) + * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) + / norm; + if (k == d) { + dyi += pow(norm, -1.0 * ${r}); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } + else { + break; + } + } + } + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kK={kernelName:Ru,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o,y:r,dy:i}=t,{depthRadius:a,bias:c,alpha:l,beta:u}=s,d=new SK(o.shape,a,c,l,u);return e.runWebGLProgram(d,[o,r,i],o.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TK(n,t,e,s){const o=Z(t),i=Z(n.shape)/o,a=tt({inputs:{x:n},attrs:{shape:[i,o]},backend:s}),c=No(a,n.dtype,"max",s),l=tt({inputs:{x:c},attrs:{shape:e},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(c),l}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hI(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reductionIndices:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a),d=u!=null,h=e.shouldExecuteOnCPU([o]);let p=o;if(d){if(h){const I=e.texData.get(p.dataId).values,y=new Array(a);for(let k=0;k`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))return Je({inputs:{x:o},backend:e});const d=new ca(u,"max",!1);return e.runWebGLProgram(d,[o],o.dtype)}const DK={kernelName:_a,backendName:"webgl",kernelFunc:EK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WK(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dataFormat:c,dimRoundingMode:l}=s,u=[1,1,1],d=ss(o.shape,r,i,u,a,l,c),h=new Dp(d,"max",!1);return e.runWebGLProgram(h,[o],o.dtype)}const MK={kernelName:Ua,backendName:"webgl",kernelFunc:WK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class VK{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const e=t.strideHeight,s=t.strideWidth,o=t.dilationHeight,r=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=r-1-t.padInfo.top,c=i-1-t.padInfo.left,l=r*i-1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${c}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${r}; + wR += ${o}) { + float dyR = float(dyRCorner + wR) / ${e}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${i}; wC++) { + float dyC = float(dyCCorner + wC) / ${s}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = wR * ${i} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + setOutput(dotProd); + } + `}}class FK{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const e=t.strideDepth,s=t.strideHeight,o=t.strideWidth,r=t.dilationDepth,i=t.dilationHeight,a=t.dilationWidth,c=t.effectiveFilterDepth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,d=c-1-t.padInfo.front,h=l-1-t.padInfo.top,p=u-1-t.padInfo.left,f=c*l*u-1;this.userCode=` + const ivec3 pads = ivec3(${d}, ${h}, ${p}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${c}; + wD += ${r}) { + float dyD = float(dyDCorner + wD) / ${e}.0; + + if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${l}; + wR += ${i}) { + float dyR = float(dyRCorner + wR) / ${s}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${u}; + wC += ${a}) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + int maxPosValue = ${f} - + int(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = + wD * ${l} * ${u} + + wR * ${u} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zK(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r,{filterSize:a,strides:c,pad:l,dimRoundingMode:u}=s,d=[1,1,1],h=ss(i.shape,a,c,d,l,u),p=new Dp(h,"max",!0),f=e.runWebGLProgram(p,[i],i.dtype),m=new FK(h),g=e.runWebGLProgram(m,[o,f],i.dtype);return e.disposeIntermediateTensorInfo(f),g}const XK={kernelName:Gu,backendName:"webgl",kernelFunc:zK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AK(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r,output:i}=t,a=r;ra([r,i],"maxPoolGrad");const{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=s,h=pn(a.shape,c,l,1,u,d),p=!0,f=new ca(h,"max",p),m=e.runWebGLProgram(f,[a],a.dtype),g=new VK(h),b=e.runWebGLProgram(g,[o,m],a.dtype);return e.disposeIntermediateTensorInfo(m),b}const PK={kernelName:$u,backendName:"webgl",kernelFunc:AK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OK(n,t,e,s){let o=new ca(e,"max",!1);const r=s.runWebGLProgram(o,[n],"float32");o=new ca(e,"max",!0,!0,t);const i=s.runWebGLProgram(o,[n],"float32");return[r,i]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KK={kernelName:Cf,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:o,strides:r,pad:i,includeBatchInIndex:a}=t,c=e;v(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const l=[1,1];v(Te(r,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${l}'`);const u=pn(s.shape,o,r,l,i),[d,h]=OK(s,a,u,c);return[d,h]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZK(n,t,e,s){const o=Z(t),i=Z(n.shape)/o,a=tt({inputs:{x:n},attrs:{shape:[i,o]},backend:s}),c=No(a,"float32","mean",s),l=tt({inputs:{x:c},attrs:{shape:e},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(c),l}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BK={kernelName:Ya,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{keepDims:o,axis:r}=t,i=e,a=s.shape.length,c=It(r,s.shape);let l=c;const u=Yt(l,a),d=u!=null,h=i.shouldExecuteOnCPU([s]),p=[];let f=s;if(d){if(h){const y=i.texData.get(f.dataId).values,w=new Array(a);for(let S=0;Su[0]+t[d]+u[1]);const o=t.length,r=Wt(o),i=e.map(u=>u[0]).join(","),a=e.map((u,d)=>u[0]+t[d]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o),l=s==="reflect"?0:1;if(o===1){this.userCode=` + int start = ${i}; + int end = ${a}; + + void main() { + int outC = getOutputCoords(); + if (outC < start) { + outC = start * 2 - outC - ${l}; + } else if(outC >= end) { + outC = (end - 1) * 2 - outC + ${l}; + } + setOutput(getX(outC - start)); + } + `;return}this.userCode=` + ${r} start = ${r}(${i}); + ${r} end = ${r}(${a}); + + void main() { + ${r} outC = getOutputCoords(); + for (int i = 0; i < ${o}; i++) { + if (outC[i] < start[i]) { + outC[i] = start[i] * 2 - outC[i] - ${l}; + } else if(outC[i] >= end[i]) { + outC[i] = (end[i] - 1) * 2 - outC[i] + ${l}; + } + } + ${r} coords = outC - start; + setOutput(getX(${c})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qK{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((f,m)=>f[0]+t[m]+f[1]);const o=t.length,r=Wt(o),i=e.map(f=>f[0]).join(","),a=e.map((f,m)=>f[0]+t[m]).join(","),c=We("rc",o),l=We("source",o),u=`${c[o-1]} < ${this.outputShape[o-1]}`,d=o===1?"source":`vec2(${l.slice(-2).join()})`,h=s==="reflect"?0:1;let p="";if(o===1){const f=` + ${r} source = rc; + if (source < start) { + source = start * 2 - source - ${h}; + } else if (source >= end) { + source = (end - 1) * 2 - source + ${h}; + } + source -= start; + `;p=` + ${r} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${l.join()}), ${d}); + ${c[o-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${l.join()}), ${d}); + } + `}else{const f=` + ${r} source = rc; + ${r} lt = ${r}(lessThan(source, start)); + ${r} gte = ${r}(greaterThanEqual(source, end)); + ${r} orig = 1 - (lt + gte); + source = orig * source + + lt * (start * 2 - source - ${h}) + + gte * ((end - 1) * 2 - source + ${h}); + source -= start; + `;p=` + ${r} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${l.join()}), ${d}); + ${c[o-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${l.join()}), ${d}); + } + rc = outputLoc; + ${c[o-2]} += 1; + if(${c[o-2]} < ${this.outputShape[o-2]}) { + ${f} + result[2] = getChannel(getX(${l.join()}), ${d}); + ${c[o-1]} += 1; + if(${u}) { + ${f} + result[3] = getChannel(getX(${l.join()}), ${d}); + } + } + `}this.userCode=` + const ${r} start = ${r}(${i}); + const ${r} end = ${r}(${a}); + + void main() { + ${r} outputLoc = getOutputCoords(); + vec4 result = vec4(0.); + ${p} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tZ={kernelName:Ja,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s}=n,{paddings:o,mode:r}=e,i=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qK(s.shape,o,r):new jK(s.shape,o,r);return t.runWebGLProgram(i,[s],s.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eZ=`if (b == 0.0) return NAN; + return mod(a, b);`,nZ=` + vec4 result = mod(a, b); + bvec4 isNaN = equal(b, vec4(0.0)); + `+To+` + return result; +`,sZ=Ce({opSnippet:eZ,packedOpSnippet:nZ}),oZ={kernelName:Jr,backendName:"webgl",kernelFunc:sZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rZ{constructor(t,e,s){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[t,s],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + + float r = random(seed); + float cdf = 0.0; + + for (int i = 0; i < ${e-1}; i++) { + cdf += getProbs(batch, i); + + if (r < cdf) { + setOutput(float(i)); + return; + } + } + + // If no other event happened, last event happened. + setOutput(float(${e-1})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pI=Ce({opSnippet:` +if (a == b) { + return 1.0; +}; +return a / b;`,packedOpSnippet:` + // vec4 one = vec4(equal(a, b)); + // return one + (vec4(1.0) - one) * a / b; + vec4 result = a / b; + if(a.x == b.x) { + result.x = 1.; + } + if(a.y == b.y) { + result.y = 1.; + } + if(a.z == b.z) { + result.z = 1.; + } + if(a.w == b.w) { + result.w = 1.; + } + + return result; +`,checkOutOfBounds:!0}),iZ={kernelName:Mr,backendName:"webgl",kernelFunc:pI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fI="return a - b;",mI=Ce({opSnippet:fI,packedOpSnippet:fI,supportsComplex:!0,cpuKernelImpl:Wz}),aZ={kernelName:pi,backendName:"webgl",kernelFunc:mI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gI(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{dim:r}=s,i=It([r],o.shape),a=hI({inputs:{x:o},backend:e,attrs:{reductionIndices:i,keepDims:!1}}),c=re(a.shape,i),l=tt({inputs:{x:a},backend:e,attrs:{shape:c}}),u=mI({inputs:{a:o,b:l},backend:e}),d=iI({inputs:{x:u},backend:e}),h=Gl({inputs:{x:d},backend:e,attrs:{axis:i,keepDims:!1}}),p=tt({inputs:{x:h},backend:e,attrs:{shape:c}}),f=pI({inputs:{a:d,b:p},backend:e});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),f}const cZ={kernelName:mc,backendName:"webgl",kernelFunc:gI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lZ(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{numSamples:r,seed:i,normalized:a}=s,c=a?o:gI({inputs:{logits:o},backend:e,attrs:{dim:o.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new rZ(l,u,r),h=[[i]],p=e.runWebGLProgram(d,[c],"int32",h);return a||e.disposeIntermediateTensorInfo(c),p}const uZ={kernelName:vf,backendName:"webgl",kernelFunc:lZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dZ=Cn+` + return -x; +`,hZ=` + vec4 result = -x; + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`;function pZ(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])){const r=e.texData.get(s.dataId),[i,a]=mz(r.values,s.shape,s.dtype);return e.makeTensorInfo(a,s.dtype,i)}let o;return z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fs(s.shape,hZ):o=new jn(s.shape,dZ),e.runWebGLProgram(o,[s],s.dtype)}const fZ={kernelName:ja,backendName:"webgl",kernelFunc:pZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mZ=Hd;function gZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c}=s,l=e.readSync(o.dataId),u=e.readSync(r.dataId),{selectedIndices:d}=mZ(l,u,i,a,c);return e.makeTensorInfo([d.length],"int32",new Int32Array(d))}const bZ={kernelName:Lu,backendName:"webgl",kernelFunc:gZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xZ=_d;function yZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:l}=s,u=e.readSync(o.dataId),d=e.readSync(r.dataId),{selectedIndices:h,validOutputs:p}=xZ(u,d,i,a,c,l);return[e.makeTensorInfo([h.length],"int32",new Int32Array(h)),e.makeTensorInfo([],"int32",new Int32Array([p]))]}const IZ={kernelName:Eu,backendName:"webgl",kernelFunc:yZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wZ=Ud;function CZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,softNmsSigma:l}=s,u=e.readSync(o.dataId),d=e.readSync(r.dataId),h=i,p=a,f=c,m=l,{selectedIndices:g,selectedScores:b}=wZ(u,d,h,p,f,m);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([b.length],"float32",new Float32Array(b))]}const vZ={kernelName:Du,backendName:"webgl",kernelFunc:CZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class SZ{constructor(t,e,s,o){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int index = round(getIndices(coords.x)); + setOutput(mix(float(${o}), float(${s}), + float(index == coords.y))); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kZ={kernelName:ec,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{indices:o}=t,{dtype:r,depth:i,onValue:a,offValue:c}=s,l=Z(o.shape),u=new SZ(l,i,a,c),d=tt({inputs:{x:o},backend:e,attrs:{shape:[l]}}),h=e.runWebGLProgram(u,[d],r);e.disposeIntermediateTensorInfo(d);const p=[...o.shape,i],f=tt({inputs:{x:h},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(h),f}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vl(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="complex64"){const o=la({inputs:{input:s},backend:e}),r=Vl({inputs:{x:o},backend:e}),i=Wl({inputs:{input:s},backend:e}),a=Vl({inputs:{x:i},backend:e}),c=zs({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return ha({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:e})}const TZ={kernelName:xc,backendName:"webgl",kernelFunc:Vl};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bI(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const o=la({inputs:{input:s},backend:e}),r=bI({inputs:{x:o},backend:e}),i=Wl({inputs:{input:s},backend:e}),a=Vl({inputs:{x:i},backend:e}),c=zs({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return ha({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:e})}const NZ={kernelName:tc,backendName:"webgl",kernelFunc:bI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RZ(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s;if(t.length===1)return Vp({inputs:{input:t[0]},backend:e,attrs:{dim:o}});const r=t[0].shape,i=t[0].dtype;t.forEach(u=>{Hl(r,u.shape,"All tensors passed to stack must have matching shapes"),v(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],c=t.map(u=>{const d=Vp({inputs:{input:u},backend:e,attrs:{dim:o}});return a.push(d),d}),l=Y1({inputs:c,backend:e,attrs:{axis:o}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),l}const $Z={kernelName:nc,backendName:"webgl",kernelFunc:RZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class GZ{constructor(t,e,s){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((l,u)=>l[0]+t[u]+l[1]);const o=t.length,r=Wt(o),i=e.map(l=>l[0]).join(","),a=e.map((l,u)=>l[0]+t[u]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=` + int start = ${i}; + int end = ${a}; + + void main() { + int outC = getOutputCoords(); + if (outC < start || outC >= end) { + setOutput(value); + } else { + setOutput(getX(outC - start)); + } + } + `;return}this.userCode=` + ${r} start = ${r}(${i}); + ${r} end = ${r}(${a}); + + void main() { + ${r} outC = getOutputCoords(); + if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { + setOutput(value); + } else { + ${r} coords = outC - start; + setOutput(getX(${c})); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LZ{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((m,g)=>m[0]+t[g]+m[1]);const o=t.length,r=Wt(o),i=e.map(m=>m[0]).join(","),a=e.map((m,g)=>m[0]+t[g]).join(","),c=We("rc",o),l=We("source",o),u=`${c[o-1]} < ${this.outputShape[o-1]}`,d=o===1?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${c[o-1]} += 1; + if(${u}) { + `,o===1?"":`} + rc = outputLoc; + ${c[o-2]} += 1; + if(${c[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":` ${c[o-1]} += 1; + if(${u}) {`],p=o===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let f="";for(let m=0,g=o===1?2:4;m{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{paddings:r,constantValue:i}=s;if(Z(o.shape)===0){const l=r.map((u,d)=>u[0]+o.shape[d]+u[1]);return ha({backend:e,attrs:{shape:l,value:i,dtype:o.dtype}})}const a=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new LZ(o.shape,r,i):new GZ(o.shape,r,i),c=[[i]];return e.runWebGLProgram(a,[o],o.dtype,c)},EZ={kernelName:sc,backendName:"webgl",kernelFunc:xI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DZ=` + if(a < 0.0 && floor(b) < b){ + return NAN; + } + if (b == 0.0) { + return 1.0; + } + return (round(mod(b, 2.0)) != 1) ? + pow(abs(a), b) : sign(a) * pow(abs(a), b); +`,WZ=` + // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. + vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); + vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + vec4 result = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + bvec4 isExpZero = equal(b, vec4(0.0)); + result.r = isExpZero.r ? 1.0 : result.r; + result.g = isExpZero.g ? 1.0 : result.g; + result.b = isExpZero.b ? 1.0 : result.b; + result.a = isExpZero.a ? 1.0 : result.a; + + bvec4 isNaN1 = lessThan(a, vec4(0.0)); + bvec4 isNaN2 = lessThan(floor(b), b); + bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w); + `+To+` + return result; +`,MZ=Ce({opSnippet:DZ,packedOpSnippet:WZ}),VZ={kernelName:qr,backendName:"webgl",kernelFunc:MZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FZ(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=[],l=It(r,o.shape);let u=l;const d=Yt(u,a);let h=o;d!=null&&(h=Me({inputs:{x:o},backend:e,attrs:{perm:d}}),u=ee(u.length,a),c.push(h)),Ie("prod",u,a);let p;if(e.shouldExecuteOnCPU([h])){const f=e.texData.get(h.dataId).values,{outVals:m,outShape:g,outDtype:b}=bz(h.shape,h.dtype,f,u);p=e.makeTensorInfo(g,b,m)}else{const[f,m]=me(h.shape,u),g=Z(m),b=tt({inputs:{x:h},backend:e,attrs:{shape:[-1,g]}}),x=nd(o.dtype),I=No(b,x,"prod",e);p=tt({inputs:{x:I},backend:e,attrs:{shape:f}}),c.push(b),c.push(I)}if(i){c.push(p);const f=re(p.shape,l);p=tt({inputs:{x:p},backend:e,attrs:{shape:f}})}return c.forEach(f=>e.disposeIntermediateTensorInfo(f)),p}const zZ={kernelName:rc,backendName:"webgl",kernelFunc:FZ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XZ(n){const{inputs:t,backend:e,attrs:s}=n,{paramsNestedSplits:o,paramsDenseValues:r,indices:i}=t,{outputRaggedRank:a}=s,c=o.map(b=>e.readSync(b.dataId)),l=o.map(b=>b.shape),u=e.readSync(r.dataId),d=e.readSync(i.dataId),[h,p,f]=xz(c,l,u,r.shape,r.dtype,d,i.shape,a),m=h.map(b=>e.makeTensorInfo([b.length],"int32",b)),g=e.makeTensorInfo(f,r.dtype,p);return m.concat([g])}const AZ={kernelName:Sf,backendName:"webgl",kernelFunc:XZ};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PZ(n){const{inputs:t,backend:e}=n,{starts:s,limits:o,deltas:r}=t,i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=yz(i,s.shape,s.dtype,a,o.shape,c,r.shape),d=e.makeTensorInfo([l.length],"int32",l),h=e.makeTensorInfo([u.length],s.dtype,u);return[d,h]}const OZ={kernelName:kf,backendName:"webgl",kernelFunc:PZ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KZ(n){const{inputs:t,backend:e,attrs:s}=n,{shape:o,values:r,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:c}=s,l=e.readSync(o.dataId),u=e.readSync(r.dataId),d=e.readSync(i.dataId),h=a.map(g=>e.readSync(g.dataId)),p=a.map(g=>g.shape),[f,m]=Iz(l,o.shape,u,r.shape,r.dtype,d,i.shape,h,p,c);return e.makeTensorInfo(f,r.dtype,m)}const ZZ={kernelName:Tf,backendName:"webgl",kernelFunc:KZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yI=n=>{const{backend:t,attrs:e}=n,{start:s,stop:o,step:r,dtype:i}=e,a=wz(s,o,r,i);return t.makeTensorInfo([a.length],i,a)},BZ={kernelName:Wu,backendName:"webgl",kernelFunc:yI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HZ=Tt({opSnippet:"return 1.0 / x;"}),_Z={kernelName:ti,backendName:"webgl",kernelFunc:HZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UZ=Cn+` + return (x < 0.0) ? 0.0 : x; +`,YZ=Tt({opSnippet:UZ,packedOpSnippet:` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`}),QZ={kernelName:ei,backendName:"webgl",kernelFunc:YZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JZ=Cn+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,jZ=Tt({opSnippet:JZ,packedOpSnippet:` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`}),qZ={kernelName:ni,backendName:"webgl",kernelFunc:jZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class tB{constructor(t,e,s,o,r){this.variableNames=["A"],this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s];let h;r?h="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/d[0]}, + ${u[1]/d[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${c}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${h}; + + // Compute the four integer indices. + ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); + ivec2 sourceCeilRC = ivec2( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); + float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); + float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); + float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); + + vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + float top = topLeft + (topRight - topLeft) * fracRC.y; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + float newValue = top + (bottom - top) * fracRC.x; + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eB{constructor(t,e,s,o,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s];let h;r?h="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${u[0]/d[0]}, + ${u[1]/d[1]}, + ${u[1]/d[1]}); + const vec3 inputShapeRC = vec3(${a}.0, ${c}.0, + ${c}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${h}; + + // Compute the four integer indices. + ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); + ivec3 sourceCeilRC = ivec3( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${l-1}; + bool hasNextRow = coords.z < ${s-1}; + + // In parallel, construct four corners for all four components in + // packed 2x2 cell. + vec4 topLeft = vec4( + getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 bottomLeft = vec4( + getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 topRight = vec4( + getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec4 bottomRight = vec4( + getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC); + + vec4 top = mix(topLeft, topRight, fracRC.yyzz); + vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz); + vec4 newValue = mix(top, bottom, fracRC.x); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s,[c,l]=a,u=z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new eB(o.shape,c,l,r,i):new tB(o.shape,c,l,r,i);return e.runWebGLProgram(u,[o],"float32")}const sB={kernelName:cc,backendName:"webgl",kernelFunc:nB};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oB{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,o,r]=e,[,i,a]=t,c=[s&&i>1?o-1:o,s&&a>1?r-1:r],l=[s&&i>1?i-1:i,s&&a>1?a-1:a],u=c[0]/l[0],d=c[1]/l[1],h=1/u,p=1/d,f=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${d}); + + const float invHeightScale = float(${h}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${m}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(startRLerp - float(winHeight / 2)); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(startCLerp - float(winWidth / 2)); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${i}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float dxR = float(dyR) * heightScale; + int topDxRIndex = int(floor(dxR)); + int bottomDxRIndex = int(min(ceil(dxR), ${o-1}.0)); + float dxRLerp = dxR - float(topDxRIndex); + float inverseDxRLerp = 1.0 - dxRLerp; + + float dxC = float(dyC) * widthScale; + int leftDxCIndex = int(floor(dxC)); + int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0)); + float dxCLerp = dxC - float(leftDxCIndex); + float inverseDxCLerp = 1.0 - dxCLerp; + + if (r == topDxRIndex && c == leftDxCIndex) { + // topLeft + accumulator += + getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; + } + + if (r == topDxRIndex && c == rightDxCIndex) { + // topRight + accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; + } + + if (r == bottomDxRIndex && c == leftDxCIndex) { + // bottomLeft + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; + } + + if (r == bottomDxRIndex && c == rightDxCIndex) { + // bottomRight + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s,a=new oB(r.shape,o.shape,i);return e.runWebGLProgram(a,[r],r.dtype)}const iB={kernelName:Fu,backendName:"webgl",kernelFunc:rB};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class aB{constructor(t,e,s,o,r){this.variableNames=["A"],this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s],h=o?"0.5":"0.0";let p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/d[0]}, + ${u[1]/d[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${c}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestRC = ivec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h}))); + float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cB{constructor(t,e,s,o,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s],h=o?"0.5":"0.0";let p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${u[0]/d[0]}, + ${u[1]/d[1]}, + ${u[1]/d[1]}); + const vec3 inputShapeRC = vec3(${a}.0, ${c}.0, + ${c}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec3 sourceNearestRC = ivec3( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h}))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${l-1}; + bool hasNextRow = coords.z < ${s-1}; + + vec4 newValue = vec4( + getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d), + hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s,[c,l]=a,u=z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cB(o.shape,c,l,r,i):new aB(o.shape,c,l,r,i);return e.runWebGLProgram(u,[o],o.dtype)}const uB={kernelName:ac,backendName:"webgl",kernelFunc:lB};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class dB{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,o,r]=e,[,i,a]=t,c=[s&&i>1?o-1:o,s&&a>1?r-1:r],l=[s&&i>1?i-1:i,s&&a>1?a-1:a],u=c[0]/l[0],d=c[1]/l[1],h=1/u,p=1/d,f=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${d}); + + const float invHeightScale = float(${h}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${m}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(floor(startRLerp - float(winHeight / 2))); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(floor(startCLerp - float(winWidth / 2))); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${i}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float sourceFracRow = + float(${c[0]}) * + (float(dyR) / float(${l[0]})); + + float sourceFracCol = + float(${c[1]}) * + (float(dyC) / float(${l[1]})); + + int sourceNearestRow = int(min( + float(int(${o}) - 1), + ${s} ? float(round(sourceFracRow)) : + float(floor(sourceFracRow)))); + + int sourceNearestCol = int(min( + float(int(${r}) - 1), + ${s} ? float(round(sourceFracCol)) : + float(floor(sourceFracCol)))); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s,a=new dB(r.shape,o.shape,i);return e.runWebGLProgram(a,[r],r.dtype)}const pB={kernelName:Vu,backendName:"webgl",kernelFunc:hB};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fB{constructor(t,e){this.variableNames=["x"];const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=t,s===1){this.userCode=` + void main() { + int coord = getOutputCoords(); + setOutput(getX(${t[0]} - coord - 1)); + } + `;return}const o=a=>e.indexOf(a)!==-1&&t[a]!==1?`${t[a]} - coords[${a}] - 1`:`coords[${a}]`,r=t.map((a,c)=>o(c)).join(","),i=Wt(s);this.userCode=` + void main() { + ${i} coords = getOutputCoords(); + setOutput(getX(${r})); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class mB{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=t;const o=We("rc",s),r=`${o[s-1]} + 1 < ${this.outputShape[s-1]}`,i=`${o[s-2]} + 1 < ${this.outputShape[s-2]}`,a=Wt(s);s===1?this.userCode=` + void main(){ + int rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = getChannel(getX(${t[0]} - rc - 1), + ${t[0]} - rc - 1); + if(${r}){ + result.g = getChannel(getX(${t[0]} - (rc + 1) - 1), + ${t[0]} - (rc + 1) - 1); + } + setOutput(result); + } + `:this.userCode=` + void main() { + ${a} rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = ${c(o.slice())}; + if(${r}){ + result.g = ${l(o.slice())}; + } + if(${i}) { + result.b = ${u(o.slice())}; + if(${r}) { + result.a = ${d(o.slice())}; + } + } + setOutput(result); + } + `;function c(f){return h(f)}function l(f){return f[s-1]="("+f[s-1]+" + 1)",h(f)}function u(f){return f[s-2]="("+f[s-2]+" + 1)",h(f)}function d(f){return f[s-1]="("+f[s-1]+" + 1)",f[s-2]="("+f[s-2]+" + 1)",h(f)}function h(f){const m=t.map((x,I)=>p(I,f)),g=m.join(","),b=m.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${b}))`}function p(f,m){return e.indexOf(f)!==-1&&t[f]!==1?`${t[f]} - ${m[f]} - 1`:`${m[f]}`}}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gB(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dims:r}=s,i=o.shape.length,a=It(r,o.shape);if(i===0)return Je({inputs:{x:o},backend:e});const c=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mB(o.shape,a):new fB(o.shape,a);return e.runWebGLProgram(c,[o],o.dtype)}const bB={kernelName:lc,backendName:"webgl",kernelFunc:gB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xB{constructor(t,e){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const s=t[1],o=t[2];this.outputShape=t;let r="";typeof e=="number"?r=`float outputValue = ${e.toFixed(2)};`:r=` + vec3 fill = vec3(${e.join(",")}); + float outputValue = fill[coords[3]];`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + int y = coords[1]; + float coordXFloat = (float(x) - params[0]) * params[3] - + (float(y) - params[1]) * params[2]; + float coordYFloat = (float(x) - params[0]) * params[2] + + (float(y) - params[1]) * params[3]; + int coordX = int(round(coordXFloat + params[0])); + int coordY = int(round(coordYFloat + params[1])); + ${r} + if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${s}) { + outputValue = getImage(coords[0], coordY, coordX, coords[3]); + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yB={kernelName:Bu,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:o,fillValue:r,center:i}=t,a=e,c=new xB(s.shape,r),[l,u]=ih(i,s.shape[1],s.shape[2]),d=[[l,u,Math.sin(o),Math.cos(o)]];return a.runWebGLProgram(c,[s],s.dtype,d)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const IB=Tt({opSnippet:` + // OpenGL ES does not support round function. + // The algorithm is based on banker's rounding. + float base = floor(x); + if ((x - base) < 0.5) { + return floor(x); + } else if ((x - base) > 0.5) { + return ceil(x); + } else { + if (mod(base, 2.0) == 0.0) { + return base; + } else { + return base + 1.0; + } + } +`}),wB={kernelName:si,backendName:"webgl",kernelFunc:IB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CB=Tt({opSnippet:"return inversesqrt(x);",cpuKernelImpl:Cz}),vB={kernelName:oi,backendName:"webgl",kernelFunc:CB};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zp{constructor(t,e,s,o,r,i,a=!0,c=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;const l=Wt(r.length),u=Wt(i.length);let d="";s===1?d="i":s===2&&(d="i, j");const h=`getIndices(${d})`;let p="";o===1?p="i":o===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let m="";c&&(m="coords[0], coords[1]");const g=`getDefaultValue(${m})`,b=e>1?"strides[j]":"strides";this.userCode=` + ${l} strides = ${l}(${r}); + + void main() { + ${u} coords = getOutputCoords(); + float sum = 0.0; + bool found = false; + for (int i = 0; i < ${t}; i++) { + int flattenedIndex = 0; + for (int j = 0; j < ${e}; j++) { + int index = round(${h}); + flattenedIndex += index * ${b}; + } + if (flattenedIndex == coords[0]) { + sum += ${f}; + found = true; + } + } + setOutput(mix(${g}, sum, float(found))); + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class SB{constructor(t,e,s,o,r,i,a=!0,c=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=i;const l=Wt(r.length),u=Wt(i.length);let d="";s===1?d="i":s===2&&(d="i, j");const h=`getIndices(${d})`;let p="";o===1?p="i":o===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let m="";c&&(m="coords[0], coords[1]");const g=`getDefaultValue(${m})`,b=e>1?"strides[j]":"strides",x=e>1?"strides[j + 1]":"strides";this.userCode=` + ${l} strides = ${l}(${r}); + + void main() { + ${u} coords = getOutputCoords(); + vec4 sum = vec4(0.); + vec4 found = vec4(0.); + for (int i = 0; i < ${t}; i+=2) { + ivec2 flattenedIndex = ivec2(0); + for (int j = 0; j < ${e}; j+=2) { + ivec4 index = round(${h}); + flattenedIndex += index.xz * ${b}; + if (j + 1 < ${e}) { + flattenedIndex += index.yw * ${x}; + } + } + if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] || + flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) { + vec4 updVals = ${f}; + if (flattenedIndex[0] == coords[0]) { + sum.xy += updVals.xy; + found.xy = vec2(1.); + } else if (flattenedIndex[0] == coords[0] + 1) { + sum.zw += updVals.xy; + found.zw = vec2(1.); + } + if (flattenedIndex[1] == coords[0]) { + sum.xy += updVals.zw; + found.xy = vec2(1.); + } else if (flattenedIndex[1] == coords[0] + 1) { + sum.zw += updVals.zw; + found.zw = vec2(1.); + } + } + } + setOutput(mix(${g}, sum, found)); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kB(n){const{inputs:t,backend:e,attrs:s}=n,{indices:o,updates:r}=t,{shape:i}=s,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(r,o,i),h=[d/l,l];if(d===0)return e.makeTensorInfo(i,o.dtype);const p=tt({inputs:{x:o},backend:e,attrs:{shape:[c,a]}}),f=tt({inputs:{x:r},backend:e,attrs:{shape:[c,l]}}),m=e.makeTensorInfo([],"float32",new Float32Array([0]));let g;z().getBool("WEBGL_PACK")?g=new SB(c,a,p.shape.length,f.shape.length,u,h):g=new zp(c,a,p.shape.length,f.shape.length,u,h);const b=e.runWebGLProgram(g,[f,p,m],f.dtype),x=tt({inputs:{x:b},backend:e,attrs:{shape:i}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(m),x}const TB={kernelName:Nf,backendName:"webgl",kernelFunc:kB};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class NB{constructor(t,e,s,o){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[t,s];const r="while (left < right) {",i=`for (int i = 0; i < ${Math.ceil(Math.log2(e+1))}; ++i) { if (left >= right) break;`,a=z().getNumber("WEBGL_VERSION")===2?r:i,c=o==="left"?"<":"<=";this.userCode=` + int findBound(int batch, float value) { + int left = 0; + int right = numInputs; + int mid; + ${a} + mid = (left + right) / 2; + if (getSortedSequence(batch, mid) ${c} value) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int valueIndex = coords[1]; + + float value = getValues(batch, valueIndex); + + setOutput(float(findBound(batch, value))); + } + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RB(n){const{inputs:t,backend:e,attrs:s}=n,{sortedSequence:o,values:r}=t,{side:i}=s,a=new NB(o.shape[0],o.shape[1],r.shape[1],i),c=[[o.shape[1]]];return e.runWebGLProgram(a,[o,r],"int32",c)}const $B={kernelName:$f,backendName:"webgl",kernelFunc:RB};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class GB{constructor(t,e,s){this.variableNames=["c","a","b"],this.outputShape=e;let o,r;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)r="resRC",o="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],c=[],l=[];for(let u=0;u= 1.0) { + setOutput(getA(${r})); + } else { + setOutput(getB(${r})); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LB(n){const{inputs:t,backend:e}=n,{condition:s,t:o,e:r}=t,i=new GB(s.shape.length,o.shape,o.shape.length);return e.runWebGLProgram(i,[s,o,r],_e(o.dtype,r.dtype))}const EB={kernelName:uc,backendName:"webgl",kernelFunc:LB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DB=` + // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. + // see: https://arxiv.org/abs/1706.02515 + float scaleAlpha = ${Pc}; + float scale = ${Oc}; + return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); +`,WB=Tt({opSnippet:DB}),MB={kernelName:ri,backendName:"webgl",kernelFunc:WB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VB=br+` + return 1.0 / (1.0 + exp(-1.0 * x)); +`,FB=Tt({opSnippet:VB,packedOpSnippet:` + vec4 result = 1.0 / (1.0 + exp(-1.0 * x)); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,cpuKernelImpl:Sz}),zB={kernelName:li,backendName:"webgl",kernelFunc:FB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XB=Tt({opSnippet:` + if (isnan(x)) { return 0.0; } + return sign(x); +`}),AB={kernelName:ci,backendName:"webgl",kernelFunc:XB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PB=br+` + return sin(x); +`,OB=` + vec4 result = sin(x); + bvec4 isNaN = isnan(x); + ${To} + return result; +`,KB=Tt({opSnippet:PB,packedOpSnippet:OB}),ZB={kernelName:ii,backendName:"webgl",kernelFunc:KB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BB=Tt({opSnippet:` + float e2x = exp(x); + return (e2x - 1.0 / e2x) / 2.0; +`}),HB={kernelName:ai,backendName:"webgl",kernelFunc:BB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _B=Tt({opSnippet:` + float epsilon = 1.1920928955078125e-7; + float threshold = log(epsilon) + 2.0; + + bool too_large = x > -threshold; + bool too_small = x < threshold; + + float result; + float exp_x = exp(x); + + if (too_large){ + result = x; + } + else if (too_small){ + result = exp_x; + } + else{ + result = log(exp_x + 1.0); + } + return result; +`}),UB={kernelName:ui,backendName:"webgl",kernelFunc:_B};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YB={kernelName:pc,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,paddings:i}=s;v(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const a=r.reduce((b,x)=>b*x),c=[[0,0]];c.push(...i);for(let b=1+r.length;be.disposeIntermediateTensorInfo(b)),g}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QB(n){const{inputs:t,backend:e}=n,{indices:s,values:o,denseShape:r,defaultValue:i}=t;if(r.shape.length!==1)throw new Error(`Dense shape must be a vector, saw: + ${r.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw: + ${s.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw: + ${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw: + ${i.shape}`);const a=e.readSync(s.dataId),c=e.readSync(o.dataId),l=e.readSync(r.dataId),u=e.readSync(i.dataId)[0],[d,h,p,f,m]=Tz(a,s.shape,s.dtype,c,o.dtype,l,u);return[e.makeTensorInfo(h,s.dtype,d),e.makeTensorInfo([h[0]],o.dtype,p),e.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),e.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}const JB={kernelName:Gf,backendName:"webgl",kernelFunc:QB};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jB(n){const{inputs:t,backend:e}=n,{inputIndices:s,inputShape:o,newShape:r}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${o.shape}`);if(r.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${r.shape}`);const i=Array.from(e.readSync(o.dataId)),a=e.readSync(s.dataId),c=Array.from(e.readSync(r.dataId)),[l,u,d]=Nz(a,s.shape,s.dtype,i,c);return[e.makeTensorInfo(u,s.dtype,l),e.makeTensorInfo([d.length],r.dtype,new Int32Array(d))]}const qB={kernelName:Lf,backendName:"webgl",kernelFunc:jB};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tH(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${r.shape}`);const i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=S1(i,s.shape,s.dtype,a,c,!0);return e.makeTensorInfo(u,s.dtype,l)}const eH={kernelName:Ef,backendName:"webgl",kernelFunc:tH};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nH(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${r.shape}`);const i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=S1(i,s.shape,s.dtype,a,c);return e.makeTensorInfo(u,s.dtype,l)}const sH={kernelName:Df,backendName:"webgl",kernelFunc:nH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oH(n){const{inputs:t,backend:e,attrs:s}=n,{sparseIndices:o,sparseValues:r,defaultValue:i}=t,{outputShape:a}=s,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=co(r,o,a),p=!1;if(r.dtype==="string"){const b=e.bufferSync(o),x=e.bufferSync(r),I=xs(e.readSync(i.dataId)[0]),y=vz(b,x,a,h,u,l,c,d,I,p);return e.makeTensorInfo(a,y.dtype,y.values)}const f=new zp(l,c,o.shape.length,r.shape.length,d,[h,1],p),m=e.runWebGLProgram(f,[r,o,i],r.dtype),g=tt({inputs:{x:m},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(m),g}const rH={kernelName:Wf,backendName:"webgl",kernelFunc:oH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{numOrSizeSplits:r,axis:i}=s,a=It(i,o.shape)[0],c=Ch(o,r,a),l=o.shape.length,u=new Array(l).fill(0),d=o.shape.slice();return c.map(h=>{const p=[...d];p[a]=h;const f=xr({inputs:{x:o},backend:e,attrs:{begin:u,size:p}});return u[a]+=h,f})}const aH={kernelName:fc,backendName:"webgl",kernelFunc:iH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const II="return sqrt(x);",cH=Tt({opSnippet:II,packedOpSnippet:II,cpuKernelImpl:Rz}),lH={kernelName:di,backendName:"webgl",kernelFunc:cH};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uH=Tt({opSnippet:"return x * x;"}),dH={kernelName:zu,backendName:"webgl",kernelFunc:uH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wI="return (a - b) * (a - b);",hH=Ce({opSnippet:wI,packedOpSnippet:wI}),pH={kernelName:hi,backendName:"webgl",kernelFunc:hH};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;if(o.dtype!=="string")throw new Error("Input must be of datatype string");const r=e.readSync(o.dataId),i=cs(r),a=$z(i,"string",s);return e.makeTensorInfo(o.shape,"string",a)}const mH={kernelName:Xu,backendName:"webgl",kernelFunc:fH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gH({inputs:n,attrs:t,backend:e}){const{x:s}=n,o=Cn+` + return x > 0.0 ? 1.0 : float(${t.alpha}); + `,r=new jn(s.shape,o);return e.runWebGLProgram(r,[s],s.dtype)}const bH={kernelName:bi,backendName:"webgl",kernelFunc:gH};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xH{constructor(t,e,s){this.variableNames=["x"],this.outputShape=s;const o=s.length,r=Wt(s.length),i=Wt(s.length);let a="";if(o===1)a="coords * strides + begin";else{let c=0;a=s.map((l,u)=>(c++,s.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${c-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=` + ${r} begin = ${r}(${t}); + ${r} strides = ${r}(${e}); + + void main() { + ${i} coords = getOutputCoords(); + setOutput(getX(${a})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,end:i,strides:a,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=s,{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:x,end:I,strides:y}=sh(o.shape,r,i,a,c,l,u,d,h);let w;if(m)w=tt({inputs:{x:o},backend:e,attrs:{shape:f}});else if(g||b){v(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);const k=th(x,I,y),S=xr({inputs:{x:o},backend:e,attrs:{begin:x,size:k}});w=tt({inputs:{x:S},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(S)}else if(e.shouldExecuteOnCPU([o])){const S=e.readSync(o.dataId),T=wt(o.shape,o.dtype,S),R=Gz(p,T,y,x);w=e.makeTensorInfo(f,o.dtype,R.values)}else{const S=new xH(x,y,p);w=e.runWebGLProgram(S,[o],o.dtype)}const C=tt({inputs:{x:w},backend:e,attrs:{shape:f}});return e.disposeIntermediateTensorInfo(w),C}const IH={kernelName:Au,backendName:"webgl",kernelFunc:yH};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wH(n){const{inputs:t,backend:e,attrs:s}=n,{separator:o,nGramWidths:r,leftPad:i,rightPad:a,padWidth:c,preserveShortSequences:l}=s,{data:u,dataSplits:d}=t,h=e.readSync(u.dataId),p=e.readSync(d.dataId),[f,m]=Lz(h,p,o,r,i,a,c,l);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(d.shape,"int32",m)]}const CH={kernelName:Mf,backendName:"webgl",kernelFunc:wH};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vH(n){const{inputs:t,backend:e,attrs:s}=n,{skipEmpty:o}=s,{input:r,delimiter:i}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(r.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${r.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const a=e.readSync(r.dataId),c=e.readSync(i.dataId)[0],[l,u,d]=Ez(a,c,o),h=u.length;return[e.makeTensorInfo([h,2],"int32",l),e.makeTensorInfo([h],"string",u),e.makeTensorInfo([2],"int32",new Int32Array(d))]}const SH={kernelName:Vf,backendName:"webgl",kernelFunc:vH};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kH(n){const{inputs:t,backend:e,attrs:s}=n,{numBuckets:o}=s,{input:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");const i=e.readSync(r.dataId),a=Dz(i,o);return e.makeTensorInfo(r.shape,"int32",a)}const TH={kernelName:Ff,backendName:"webgl",kernelFunc:kH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NH=Tt({opSnippet:"return tan(x);"}),RH={kernelName:fi,backendName:"webgl",kernelFunc:NH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $H=Tt({opSnippet:` + float e2x = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e2x) / (1.0 + e2x); +`}),GH={kernelName:mi,backendName:"webgl",kernelFunc:$H};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LH(n){const{inputs:t,backend:e,attrs:s}=n,{tensor:o,indices:r,updates:i}=t,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(i,r,o.shape),h=[d/l,l];if(d===0)return e.makeTensorInfo(o.shape,r.dtype);const p=tt({inputs:{x:r},backend:e,attrs:{shape:[c,a]}}),f=tt({inputs:{x:i},backend:e,attrs:{shape:[c,l]}}),m=tt({inputs:{x:o},backend:e,attrs:{shape:h}}),g=new zp(c,a,p.shape.length,f.shape.length,u,h,!1,!0),b=e.runWebGLProgram(g,[f,p,m],m.dtype),x=tt({inputs:{x:b},backend:e,attrs:{shape:o.shape}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(b),x}const EH={kernelName:Rf,backendName:"webgl",kernelFunc:LH};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class DH{constructor(t,e){this.variableNames=["A"];const s=new Array(t.length);for(let i=0;i5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${n[0]})`;const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let o=0;o5){const c=e.readSync(o.dataId),l=o.dtype==="string"?c.map(h=>xs(h)):c,u=wt(o.shape,o.dtype,l),d=Mz(u,r);return e.makeTensorInfo(d.shape,d.dtype,d.values)}const i=new DH(o.shape,r);return e.runWebGLProgram(i,[o],o.dtype)}const MH={kernelName:gi,backendName:"webgl",kernelFunc:CI};class VH{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=t,this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // We compare elements pair-wise within a group of size 2 * inc. + // The comparing rule for each group alternates between ascending + // and descending. Within each group, we compare each pair at + // positions i and i+inc. To decide whether an element at position i + // is x0 or x1, we mod it by 2 * inc, if the result is smaller than + // inc, it is in the first half of the group, we denote it as x0, + // otherwise we denote it as x1. + // For example, as shown in the Bitonic top K paper referenced above, + // Figure5(a) shows that element[1] is in the + // second half of the group when group size is 2, but it is in the + // first half of the group when group size is 4. + + bool isFirstInPair = imod(elemIdx, 2 * inc) < inc; + int i = isFirstInPair ? elemIdx : elemIdx - inc; + + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc)); + float x0 = i0 < n ? getX(batch, i0) : negativeInf; + float x1 = i1 < n ? getX(batch, i1) : negativeInf; + + // Denotes which direction indices are in (ascending or descending). + bool reverse = imod(elemIdx, 2 * dir) >= dir; + bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0); + if (reverse == isGreater) { // Elements in opposite order of direction + int iTemp = i0; + i0 = i1; + i1 = iTemp; + } + if (isFirstInPair) { + setOutput(float(i0)); + } else { + setOutput(float(i1)); + } + } + `}}class FH{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=t,this.userCode=` + void main() { + // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ... + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // The output size is half of the previous size. + // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4), + // we only need to output the indices at positions |, the indices at + // positions _ can be thrown away, see Figure5(b) After Phase 2 + // (Merge phase) in the Bitonic Top K paper referenced above. + // For example, the paper shows we only need to output the orange bars. + // The output sequence should look like this | | | | | | | |. + // Because the sequence is halved, to map the output index back + // to the previous sequence to find the corresponding value, + // we need to double the index. When we double the index, + // we basically interpolate a position, so 2i looks like + // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position + // of each 2k positions by - elemIdx % k. E.g. for output at + // index 4,5,6,7, we want to get the corresponding element at + // original index 8,9,10,11, for output at index 8,9,10,11, + // we want to get the corresponding element at original index + // 16,17,18,19, so on and so forth. + + int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k)); + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k)); + + float x0 = getX(batch, i0); + float x1 = i1 < n ? getX(batch, i1) : x0; + + setOutput(x0 >= x1 ? float(i0) : float(i1)); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ro(n,t){t!==null&&n.disposeIntermediateTensorInfo(t)}function vI(n){let t=1;for(;tc){const R=e.readSync(o.dataId),[L,V]=Vz(R,l,o.dtype,r,i);return[e.makeTensorInfo(L.shape,L.dtype,L.values),e.makeTensorInfo(V.shape,V.dtype,V.values)]}if(r===0)return l[l.length-1]=0,[e.makeTensorInfo(l,o.dtype,[]),e.makeTensorInfo(l,"int32",[])];if(u===1)return[o,ha({attrs:{shape:l,dtype:"int32",value:0},backend:e})];const d=e.texData.get(o.dataId),h=d!==null&&d.isPacked,p=h?e.unpackTensor(o):o,m=Z(l)/u,g=tt({inputs:{x:p},attrs:{shape:[m,u]},backend:e});h&&Ro(e,p);const b=vI(r),x=vI(u);let I=null;const y=()=>I===null?[g,g]:[g,I],w=(R,L,V)=>{const F=y(),X=new VH(V),P=[[u],[I===null?1:0],[Number.NEGATIVE_INFINITY],[R],[L]],B=I;I=e.runWebGLProgram(X,F,"int32",P),Ro(e,B)};for(let R=1;R=1;V/=2)w(L,V,[m,x])}for(let R=x;R>b;R/=2){const L=y(),V=new FH([m,R/2]),X=[[u],[I===null?1:0],[b]],A=I;I=e.runWebGLProgram(V,L,"int32",X),Ro(e,A);const P=b/2,B=P*2;for(let K=P;K>=1;K/=2)w(B,K,I.shape)}let C=I;I=xr({inputs:{x:I},backend:e,attrs:{begin:0,size:[m,r]}}),Ro(e,C);let k=dI({inputs:{x:g,indices:I},backend:e,attrs:{axis:1,batchDims:1}});Ro(e,g);const S=l.slice(0,-1);S.push(r),C=I,I=tt({inputs:{x:I},attrs:{shape:S},backend:e}),Ro(e,C);const T=k;return k=tt({inputs:{x:k},attrs:{shape:S},backend:e}),Ro(e,T),[k,I]}const XH={kernelName:Pu,backendName:"webgl",kernelFunc:zH};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class AH{constructor(t,e,s,o,r,i){this.variableNames=["Image","Transforms"],this.outputShape=i;const a=s==="nearest"?1:2;let c;switch(o){case"constant":c=1;break;case"reflect":c=2;break;case"wrap":c=3;break;case"nearest":c=4;break;default:c=1;break}this.userCode=` + float mapCoord(float outCoord, float len) { + float inCoord = outCoord; + if(${c} == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * float(int(float(-inCoord / sz2))) + + inCoord; + } + inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + inCoord -= sz2 * float(int(float(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${c} == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord -= len * float(int(float(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${c} == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } else { + return outCoord; + } + } + + float readWithFillValue(int batch, int coordY, int coordX, + int channel) { + float outputValue; + if (0 <= coordY && coordY < ${t} && 0 <= coordX && coordX < ${e}) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = float(${r}); + } + return outputValue; + } + + void main() { + ivec4 coords = getOutputCoords(); + float outputValue; + int batch = coords[0]; + int x = coords[2]; + int y = coords[1]; + int channel = coords[3]; + float xf = float(x); + float yf = float(y); + float a1 = getTransforms(batch, 0); + float a2 = getTransforms(batch, 1); + float a3 = getTransforms(batch, 2); + float b1 = getTransforms(batch, 3); + float b2 = getTransforms(batch, 4); + float b3 = getTransforms(batch, 5); + float c1 = getTransforms(batch, 6); + float c2 = getTransforms(batch, 7); + float projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = float(${r}); + } else { + float inX = (a1 * xf + a2 * yf + a3) / projection; + float inY = (b1 * xf + b2 * yf + b3) / projection; + float mapX = mapCoord(inX, float(${e})); + float mapY = mapCoord(inY, float(${t})); + + if (${a} == 1) { + int coordY = int(round(mapY)); + int coordX = int(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + float yFloor = floor(mapY); + float xFloor = floor(mapX); + float yCeil = yFloor + 1.0; + float xCeil = xFloor + 1.0; + float valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, int(yFloor), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yFloor), int(xCeil), channel); + float valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, int(yCeil), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yCeil), int(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PH(n){const{inputs:t,backend:e,attrs:s}=n,{image:o,transforms:r}=t,{interpolation:i,fillMode:a,fillValue:c,outputShape:l}=s,[u,d,h,p]=o.shape,[f,m]=l??[d,h],g=[u,f,m,p],b=new AH(d,h,i,a,c,g);return e.runWebGLProgram(b,[o,r],"float32")}const OH={kernelName:Ou,backendName:"webgl",kernelFunc:PH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KH(n){const{inputs:t,attrs:e,backend:s}=n,{axis:o}=e,{x:r}=t;ra(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(r.dataId),{outputValues:a,outputShape:c,indices:l}=Fz(i,o,r.shape,r.dtype);return[s.makeTensorInfo(c,r.dtype,a),s.makeTensorInfo([l.length],"int32",l)]}const ZH={kernelName:Ku,backendName:"webgl",kernelFunc:KH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BH(n){const{inputs:t,backend:e,attrs:s}=n,{value:o}=t;let{axis:r}=s;r<0&&(r+=o.shape.length);const i=o,a=i.shape.length,c=o.shape[r],l=new Array(a-1);let u=0;for(let m=0;me.disposeIntermediateTensorInfo(m)),f}const HH={kernelName:gc,backendName:"webgl",kernelFunc:BH};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _H{constructor(t,e){this.variableNames=["x","segmentIds"];const s=t.windowSize,o=t.batchSize,r=t.inSize,i=t.numSegments,a=i*Math.ceil(r/s);this.outputShape=[o,a];const c="0.0",l="sumValue",u=Math.floor(s/4)*4,d=s%4,h=` + sumValue += dot(values, segFilter); + `;let p="";r%s>0&&(p=` + if (inIdx < 0 || inIdx >= ${r}) { + return initializationValue; + } + `);let f="";r%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${r}) { + return -1.0; + } + `),this.userCode=` + const float initializationValue = ${c}; + + float getValue(int batch, int inIdx) { + ${p} + return getX(batch, inIdx); + } + + float getSegmentIdAtIndex(int inIdx) { + ${f} + return getSegmentIds(inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = int(floor(float(outIdx) / float( + ${i})) * float(${s})); + int currentSeg = int(mod(float(outIdx), float(${i}))); + + float sumValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 + ); + + ${h} + } + + int inIdx = inOffset + ${u}; + if (${d===1}) { + vec4 values = vec4( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + 0, + 0, + 0 + ); + + ${h} + } else if (${d===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + 0, + 0 + ); + + ${h} + } else if (${d===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + 0 + ); + + ${h} + } + setOutput(${l}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,segmentIds:r}=t,{numSegments:i}=s,a=o.shape.length,c=[];let l=0;const u=Yt([l],a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),c.push(d),l=ee(1,a)[0]);const h=Qg(d.shape,l,i),p=Z([d.shape[l]]),f=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,p]}});c.push(f);const m=nd(o.dtype),g=(y,w,C,k,S)=>{const T=y.shape[0],R=y.shape[1],L=Yg(R,S),V={windowSize:L,inSize:R,batchSize:T,numSegments:S},F=new _H(V,w),X=e.compileAndRun(F,[y,C],k);if(c.push(X),X.shape[1]===S)return X;const A=yI({backend:e,attrs:{start:0,stop:S,step:1,dtype:"float32"}}),P=CI({inputs:{x:A},backend:e,attrs:{reps:[R/L]}});return c.push(A),c.push(P),g(X,w,P,k,S)},b=g(f,"unsortedSegmentSum",r,m,i),x=tt({inputs:{x:b},backend:e,attrs:{shape:h}});let I=x;if(u!=null){c.push(x);const y=Cs(u);I=Me({inputs:{x:I},backend:e,attrs:{perm:y}})}return c.forEach(y=>e.disposeIntermediateTensorInfo(y)),I}const YH={kernelName:bc,backendName:"webgl",kernelFunc:UH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QH=[RX,GX,DX,VX,zX,PX,KX,BX,YX,JX,tA,sA,iA,uA,pA,mA,bA,wA,vA,kA,RA,WA,VA,AA,OA,_A,YA,qA,dX,nP,aP,dP,bP,IP,CP,SP,TP,GP,EP,WP,VP,zP,AP,KP,BP,YP,JP,tO,sO,rO,aO,uO,hO,mO,bO,xO,IO,CO,SO,TO,RO,GO,DO,VO,zO,PO,ZO,HO,UO,uX,QO,rP,jO,tK,nK,pX,oK,iK,cK,dK,fK,gK,xK,IK,vK,kK,NK,LK,DK,MK,XK,PK,KK,BK,_K,JK,tZ,oZ,uZ,gX,fZ,bZ,IZ,vZ,KA,kZ,NZ,$Z,EZ,VZ,mX,zZ,AZ,OZ,ZZ,BZ,ZA,iZ,_Z,QZ,qZ,xX,sB,iB,uB,pB,bB,yB,wB,vB,TB,$B,EB,MB,zB,AB,ZB,HB,DA,cZ,UB,YB,JB,qB,eH,sH,rH,aH,lH,dH,pH,mH,bH,IH,CH,SH,TH,aZ,kX,RH,GH,EH,MH,XH,OH,TX,ZH,HH,YH,TZ];for(const n of QH)qe(n);const SI="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NsYXNzIFd0e2NvbnN0cnVjdG9yKG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mV3IGhuKG4ucHJvamVjdGlvblRyYW5zZm9ybSk7YnJlYWs7Y2FzZSJtYXRjaCI6Y29uc3QgZT1uLnRhcmdldEluZGV4ZXM7bGV0IHQ9LTEscz1udWxsLHI9bnVsbDtmb3IobGV0IGY9MDtmPGUubGVuZ3RoO2YrKyl7Y29uc3QgZz1lW2ZdLHtrZXlmcmFtZUluZGV4OmEsc2NyZWVuQ29vcmRzOmosd29ybGRDb29yZHM6dyxkZWJ1Z0V4dHJhOnl9PUd0Lm1hdGNoRGV0ZWN0aW9uKEt0W2ddLG4uZmVhdHVyZVBvaW50cyk7aWYocj15LGEhPT0tMSl7Y29uc3QgbT1TdC5lc3RpbWF0ZSh7c2NyZWVuQ29vcmRzOmosd29ybGRDb29yZHM6d30pO20mJih0PWcscz1tKTticmVha319cG9zdE1lc3NhZ2Uoe3R5cGU6Im1hdGNoRG9uZSIsdGFyZ2V0SW5kZXg6dCxtb2RlbFZpZXdUcmFuc2Zvcm06cyxkZWJ1Z0V4dHJhOnJ9KTticmVhaztjYXNlInRyYWNrVXBkYXRlIjpjb25zdHttb2RlbFZpZXdUcmFuc2Zvcm06aSx3b3JsZENvb3JkczpoLHNjcmVlbkNvb3JkczpsfT1uLHU9U3QucmVmaW5lRXN0aW1hdGUoe2luaXRpYWxNb2RlbFZpZXdUcmFuc2Zvcm06aSx3b3JsZENvb3JkczpoLHNjcmVlbkNvb3JkczpsfSk7cG9zdE1lc3NhZ2Uoe3R5cGU6InRyYWNrVXBkYXRlRG9uZSIsbW9kZWxWaWV3VHJhbnNmb3JtOnV9KTticmVhaztjYXNlImRpc3Bvc2UiOmNsb3NlKCk7YnJlYWs7ZGVmYXVsdDp0aHJvdyBuZXcgRXJyb3IoYEludmFsaWQgbWVzc2FnZSB0eXBlICcke24udHlwZX0nYCl9fX0pKCk7Cg==",kI=typeof window<"u"&&window.Blob&&new Blob([atob(SI)],{type:"text/javascript;charset=utf-8"});function JH(n){let t;try{if(t=kI&&(window.URL||window.webkitURL).createObjectURL(kI),!t)throw"";const e=new Worker(t,{name:n==null?void 0:n.name});return e.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:application/javascript;base64,"+SI,{name:n==null?void 0:n.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}const jH=(n,t)=>[[n[0][0]*t[0][0]+n[0][2]*t[2][0],n[0][0]*t[0][1]+n[0][2]*t[2][1],n[0][0]*t[0][2]+n[0][2]*t[2][2],n[0][0]*t[0][3]+n[0][2]*t[2][3]],[n[1][1]*t[1][0]+n[1][2]*t[2][0],n[1][1]*t[1][1]+n[1][2]*t[2][1],n[1][1]*t[1][2]+n[1][2]*t[2][2],n[1][1]*t[1][3]+n[1][2]*t[2][3]],[t[2][0],t[2][1],t[2][2],t[2][3]]],qH=(n,t,e,s)=>{const o=n[0][0]*t+n[0][1]*e+n[0][3],r=n[1][0]*t+n[1][1]*e+n[1][3],i=n[2][0]*t+n[2][1]*e+n[2][3];return{x:o,y:r,z:i}},t9=(n,t,e,s)=>{const{x:o,y:r,z:i}=qH(n,t,e);return{x:o/i,y:r/i}},e9=6,n9=1,s9=10,o9=1,r9=.8,i9=1,qn=1e3;class a9{constructor(t,e,s,o,r,i=!1){this.markerDimensions=t,this.trackingDataList=e,this.projectionTransform=s,this.debugMode=i,this.trackingKeyframeList=[];for(let c=0;cr9&&I= (${h} - ${r}) || sy < ${r} || sy >= (${d} - ${r})) { + setOutput(-2.); + } + else { + float sumPoint = 0.; + float sumPointSquare = 0.; + float sumTemplate = 0.; + float sumTemplateSquare = 0.; + float sumPointTemplate = 0.; + + for (int templateOffsetY = 0; templateOffsetY < ${i}; templateOffsetY++) { + for (int templateOffsetX = 0; templateOffsetX < ${i}; templateOffsetX++) { + int fx2 = sCenterX + templateOffsetX - ${r}; + int fy2 = sCenterY + templateOffsetY - ${r}; + + int sx2 = sx + templateOffsetX - ${r}; + int sy2 = sy + templateOffsetY - ${r}; + + int markerPixelIndex = fy2 * markerWidth + fx2; + float markerPixel = getMarkerPixels(markerPixelIndex); + float targetPixel = getTargetPixels(sy2, sx2); + + sumTemplate += markerPixel; + sumTemplateSquare += markerPixel * markerPixel; + sumPoint += targetPixel; + sumPointSquare += targetPixel * targetPixel; + sumPointTemplate += targetPixel * markerPixel; + } + } + + // Normalized cross-correlation + // !important divide first avoid overflow (e.g. sumPoint / count * sumPoint) + float count = float(${i} * ${i}); + float pointVariance = sqrt(sumPointSquare - sumPoint / count * sumPoint); + float templateVariance = sqrt(sumTemplateSquare - sumTemplate / count * sumTemplate); + + if (pointVariance < 0.0000001) { + setOutput(-3.); + } else if (templateVariance < 0.0000001) { + //setOutput(sumTemplate); + setOutput(-4.); + } else { + sumPointTemplate -= sumPoint / count * sumTemplate; + float sim = sumPointTemplate / pointVariance / templateVariance; + setOutput(sim); + } + } + } + `},m={variableNames:["featurePoints","markerProperties","maxIndex"],outputShape:[p,2],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + + float markerScale = getMarkerProperties(2); + + int featureIndex = coords[0]; + + int maxIndex = int(getMaxIndex(featureIndex)); + int searchLocationIndex = maxIndex / ${u*u}; + int searchOffsetIndex = imod(maxIndex, ${u*u}); + + if (coords[1] == 0) { + int searchOffsetX = imod(searchOffsetIndex, ${u}) * ${l}; + setOutput(getFeaturePoints(featureIndex, 0) + float(searchOffsetX - ${c}) / markerScale); + } + else if (coords[1] == 1) { + int searchOffsetY = searchOffsetIndex / ${u} * ${l}; + setOutput(getFeaturePoints(featureIndex, 1) + float(searchOffsetY - ${c}) / markerScale); + } + } + `},g={variableNames:["sims","maxIndex"],outputShape:[p],userCode:` + void main() { + int featureIndex = getOutputCoords(); + int maxIndex = int(getMaxIndex(featureIndex)); + setOutput(getSims(featureIndex, maxIndex)); + } + `};this.kernelCaches.computeMatching=[f,m,g]}return M(()=>{const f=this.kernelCaches.computeMatching,m=this._compileAndRun(f[0],[t,e,s,o]),g=m.argMax(1),b=this._compileAndRun(f[1],[t,s,g]),x=this._compileAndRun(f[2],[m,g]);return{matchingPointsT:b,simT:x}})}_computeProjection(t,e,s){const o=this.trackingKeyframeList[s].width,r=this.trackingKeyframeList[s].height,i=this.trackingKeyframeList[s].scale,a=o+"-"+r+"-"+i;if(this.kernelCaches.computeProjection||(this.kernelCaches.computeProjection={}),!this.kernelCaches.computeProjection[a]){const c={variableNames:["M","pixel"],outputShape:[r,o],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + + float m00 = getM(0, 0) * ${qn}.; + float m01 = getM(0, 1) * ${qn}.; + float m03 = getM(0, 3) * ${qn}.; + float m10 = getM(1, 0) * ${qn}.; + float m11 = getM(1, 1) * ${qn}.; + float m13 = getM(1, 3) * ${qn}.; + float m20 = getM(2, 0) * ${qn}.; + float m21 = getM(2, 1) * ${qn}.; + float m23 = getM(2, 3) * ${qn}.; + + float y = float(coords[0]) / float(${i}); + float x = float(coords[1]) / float(${i}); + float uz = (x * m20) + (y * m21) + m23; + float oneOverUz = 1. / uz; + + float ux = (x * m00) + (y * m01) + m03; + float uy = (x * m10) + (y * m11) + m13; + + ux = floor(ux * oneOverUz + 0.5); + uy = floor(uy * oneOverUz + 0.5); + setOutput(getPixel(int(uy), int(ux))); + } + `};this.kernelCaches.computeProjection[a]=c}return M(()=>{const c=this.kernelCaches.computeProjection[a];return this._compileAndRun(c,[t,e])})}_buildAdjustedModelViewTransform(t){return M(()=>{let e=[];for(let o=0;o{const s=t.scale,o=[];for(let c=0;c{const t=n.inputs.image,e=n.backend,[s,o]=c9(t),r=e.runWebGLProgram(s,[t],t.dtype),i=e.runWebGLProgram(o,[r],t.dtype);return e.disposeIntermediateTensorInfo(r),i}},zl=7,TI=3,u9=TI*TI,Ap=4,d9=(Ap+1)*(Ap+1)/Ap,Pp={};function h9(n){const t=n.shape[1],e=n.shape[0],s="w"+t+"h"+e;if(!Pp.hasOwnProperty(s)){const o={variableNames:["image0","image1","image2"],outputShape:[e,t],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + + int y = coords[0]; + int x = coords[1]; + + float value = getImage1(y, x); + + // Step 1: find local maxima/minima + if (value * value < ${u9}.) { + setOutput(0.); + return; + } + if (y < ${zl} || y > ${e-1-zl}) { + setOutput(0.); + return; + } + if (x < ${zl} || x > ${t-1-zl}) { + setOutput(0.); + return; + } + + bool isMax = true; + bool isMin = true; + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) { + float value0 = getImage0(y+dy, x+dx); + float value1 = getImage1(y+dy, x+dx); + float value2 = getImage2(y+dy, x+dx); + + if (value < value0 || value < value1 || value < value2) { + isMax = false; + } + if (value > value0 || value > value1 || value > value2) { + isMin = false; + } + } + } + + if (!isMax && !isMin) { + setOutput(0.); + return; + } + + // compute edge score and reject based on threshold + float dxx = getImage1(y, x+1) + getImage1(y, x-1) - 2. * getImage1(y, x); + float dyy = getImage1(y+1, x) + getImage1(y-1, x) - 2. * getImage1(y, x); + float dxy = 0.25 * (getImage1(y-1,x-1) + getImage1(y+1,x+1) - getImage1(y-1,x+1) - getImage1(y+1,x-1)); + + float det = (dxx * dyy) - (dxy * dxy); + + if (abs(det) < 0.0001) { // determinant undefined. no solution + setOutput(0.); + return; + } + + float edgeScore = (dxx + dyy) * (dxx + dyy) / det; + + if (abs(edgeScore) >= ${d9} ) { + setOutput(0.); + return; + } + setOutput(getImage1(y,x)); + } + `};Pp[s]=o}return Pp[s]}const p9={kernelName:"BuildExtremas",backendName:"webgl",kernelFunc:n=>{let{image0:t,image1:e,image2:s}=n.inputs;const o=n.backend,r=h9(e);return t=zt().runKernel("DownsampleBilinear",{image:t}),s=zt().runKernel("UpsampleBilinear",{image:s,targetImage:e}),o.runWebGLProgram(r,[t,e,s],e.dtype)}},pa=36,Op={};function f9(n){const t=n.shape[0];if(!Op.hasOwnProperty(t)){const e={variableNames:["histogram"],outputShape:[n.shape[0]],userCode:` + void main() { + int featureIndex = getOutputCoords(); + + int maxIndex = 0; + for (int i = 1; i < ${pa}; i++) { + if (getHistogram(featureIndex, i) > getHistogram(featureIndex, maxIndex)) { + maxIndex = i; + } + } + + int prev = imod(maxIndex - 1 + ${pa}, ${pa}); + int next = imod(maxIndex + 1, ${pa}); + + /** + * Fit a quatratic to 3 points. The system of equations is: + * + * y0 = A*x0^2 + B*x0 + C + * y1 = A*x1^2 + B*x1 + C + * y2 = A*x2^2 + B*x2 + C + * + * This system of equations is solved for A,B,C. + */ + float p10 = float(maxIndex - 1); + float p11 = getHistogram(featureIndex, prev); + float p20 = float(maxIndex); + float p21 = getHistogram(featureIndex, maxIndex); + float p30 = float(maxIndex + 1); + float p31 = getHistogram(featureIndex, next); + + float d1 = (p30-p20)*(p30-p10); + float d2 = (p10-p20)*(p30-p10); + float d3 = p10-p20; + + // If any of the denominators are zero then, just use maxIndex. + float fbin = float(maxIndex); + if ( abs(d1) > 0.00001 && abs(d2) > 0.00001 && abs(d3) > 0.00001) { + float a = p10*p10; + float b = p20*p20; + + // Solve for the coefficients A,B,C + float A = ((p31-p21)/d1)-((p11-p21)/d2); + float B = ((p11-p21)+(A*(b-a)))/d3; + float C = p11-(A*a)-(B*p10); + fbin = -B / (2. * A); + } + + float an = 2.0 *${Math.PI} * (fbin + 0.5) / ${pa}. - ${Math.PI}; + setOutput(an); + } + `};Op[t]=e}return Op[t]}const m9={kernelName:"ComputeExtremaAngles",backendName:"webgl",kernelFunc:n=>{const{histograms:t}=n.inputs,e=n.backend,s=f9(t);return e.runWebGLProgram(s,[t],t.dtype)}},NI=7,Kp={};function g9(n,t){const e=`${n}|${t.shape[0]}`;if(!Kp.hasOwnProperty(e)){const s=[];for(let i=1;i{const{gaussianImagesT:t,prunedExtremas:e,prunedExtremasAngles:s,freakPointsT:o,pyramidImagesLength:r}=n.inputs,i=n.backend,a=g9(r,e);return i.runWebGLProgram(a,[...t,e,s,o],"float32")}},RI=($o.length-1)*$o.length/2,x9=Math.ceil(RI/8),Zp={};function y9(n){const t=`${n.shape[0]}`;if(!Zp.hasOwnProperty(t)){const e={variableNames:["freak","p"],outputShape:[n.shape[0],x9],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int featureIndex = coords[0]; + int descIndex = coords[1] * 8; + + int sum = 0; + for (int i = 0; i < 8; i++) { + if (descIndex + i >= ${RI}) { + continue; + } + + int p1 = int(getP(descIndex + i, 0)); + int p2 = int(getP(descIndex + i, 1)); + + float v1 = getFreak(featureIndex, p1); + float v2 = getFreak(featureIndex, p2); + + if (v1 < v2 + 0.01) { + sum += int(pow(2.0, float(7 - i))); + } + } + setOutput(float(sum)); + } +`};Zp[t]=e}return Zp[t]}const I9={kernelName:"ComputeFreakDescriptors",backendName:"webgl",kernelFunc:n=>{const{extremaFreaks:t,positionT:e}=n.inputs,{backend:s}=n,o=y9(t);return s.runWebGLProgram(o,[t,e],"int32")}},Bp={};function w9(n,t){const e=`${n}|${t}`;if(!Bp.hasOwnProperty(e)){const s=[];let o="float getPixel(int octave, int y, int x) {";for(let r=1;r{const{prunedExtremasList:t,dogPyramidImagesT:e}=n.inputs,s=n.backend,o=w9(e.length,t.length),r=tn(t,[t.length,t[0].length],"int32");return s.runWebGLProgram(o,[...e.slice(1),r],e[0].dtype)}},v9=.159154943091895,Ir=36,Hp={};function S9(n,t,e){const s=`${e}|${n.shape[0]}|${t.shape[0]}`;if(!Hp.hasOwnProperty(s)){const o=[];for(let c=1;c{const{gaussianImagesT:t,prunedExtremasT:e,radialPropertiesT:s,pyramidImagesLength:o}=n.inputs,r=n.backend,[i,a]=S9(e,s,o),c=r.runWebGLProgram(i,[...t,e,s],s.dtype),l=r.runWebGLProgram(a,[c],s.dtype);return r.disposeIntermediateTensorInfo(c),l}},_p={};function T9(n){const t=n.shape[1],e=n.shape[0],s="w"+t+"h"+e;if(!_p.hasOwnProperty(s)){const o={variableNames:["p"],outputShape:[Math.floor(e/2),Math.floor(t/2)],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int y = coords[0] * 2; + int x = coords[1] * 2; + + float sum = getP(y, x) * 0.25; + sum += getP(y+1,x) * 0.25; + sum += getP(y, x+1) * 0.25; + sum += getP(y+1,x+1) * 0.25; + setOutput(sum); + } + `};_p[s]=o}return _p[s]}const N9={kernelName:"DownsampleBilinear",backendName:"webgl",kernelFunc:n=>{const t=n.inputs.image,e=n.backend,s=T9(t);return e.runWebGLProgram(s,[t],t.dtype)}},R9={kernelName:"ExtremaReduction",backendName:"webgl",kernelFunc:n=>{const{extremasResultT:t}=n.inputs,e=n.backend,s=t.shape[0],o=t.shape[1],r={variableNames:["extrema"],outputShape:[Math.floor(s/2),Math.floor(o/2)],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int y = coords[0] * 2; + int x = coords[1] * 2; + + float location = 0.0; + float values = getExtrema(y, x); + + if (getExtrema(y+1, x) != 0.0) { + location = 1.0; + values = getExtrema(y+1, x); + } + else if (getExtrema(y, x+1) != 0.0) { + location = 2.0; + values = getExtrema(y, x+1); + } + else if (getExtrema(y+1, x+1) != 0.0) { + location = 3.0; + values = getExtrema(y+1, x+1); + } + + if (values < 0.0) { + setOutput(location * -1000.0 + values); + } else { + setOutput(location * 1000.0 + values); + } + } + `};return e.runWebGLProgram(r,[t],t.dtype)}},Xl=36,$9=5,Up={};function G9(n){const t=`h${n.shape[0]}`;if(!Up.hasOwnProperty(t)){const e={variableNames:["histogram"],outputShape:[n.shape[0],Xl],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + + int featureIndex = coords[0]; + int binIndex = coords[1]; + + int prevBin = imod(binIndex - 1 + ${Xl}, ${Xl}); + int nextBin = imod(binIndex + 1, ${Xl}); + float result = 0.274068619061197 * getHistogram(featureIndex, prevBin) + 0.451862761877606 * getHistogram(featureIndex, binIndex) + 0.274068619061197 * getHistogram(featureIndex, nextBin); + + setOutput(result); + } + `};Up[t]=e}return Up[t]}const L9={kernelName:"SmoothHistograms",backendName:"webgl",kernelFunc:n=>{let{histograms:t}=n.inputs;const e=n.backend,s=G9(t);for(let o=0;o<$9;o++){const r=t;t=e.runWebGLProgram(s,[t],t.dtype),o>0&&e.disposeIntermediateTensorInfo(r)}return t}},Yp={};function E9(n,t){const e=t.shape[1],s=t.shape[0],o="w"+e+"h"+s;if(!Yp.hasOwnProperty(o)){const r={variableNames:["p"],outputShape:[s,e],userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int j = coords[0]; + int i = coords[1]; + + float sj = 0.5 * float(j) - 0.25; + float si = 0.5 * float(i) - 0.25; + + float sj0 = floor(sj); + float sj1 = ceil(sj); + float si0 = floor(si); + float si1 = ceil(si); + + int sj0I = int(sj0); + int sj1I = int(sj1); + int si0I = int(si0); + int si1I = int(si1); + + float sum = 0.0; + sum += getP(sj0I, si0I) * (si1 - si) * (sj1 - sj); + sum += getP(sj1I, si0I) * (si1 - si) * (sj - sj0); + sum += getP(sj0I, si1I) * (si - si0) * (sj1 - sj); + sum += getP(sj1I, si1I) * (si - si0) * (sj - sj0); + setOutput(sum); + } + `};Yp[o]=r}return Yp[o]}const D9={kernelName:"UpsampleBilinear",backendName:"webgl",kernelFunc:n=>{const{image:t,targetImage:e}=n.inputs,s=n.backend,o=E9(t,e);return s.runWebGLProgram(o,[t],t.dtype)}};qe(l9),qe(p9),qe(m9),qe(b9),qe(I9),qe(C9),qe(k9),qe(N9),qe(R9),qe(L9),qe(D9);const $I=8,W9=5,fa=10,M9=5,Qp=3,V9=1.5;($o.length-1)*$o.length/2;class GI{constructor(t,e,s=!1){this.debugMode=s,this.width=t,this.height=e;let o=0;for(;t>=$I&&e>=$I&&(t/=2,e/=2,o++,o!==W9););this.numOctaves=o,this.tensorCaches={},this.kernelCaches={}}detectImageData(t){const e=new Uint8ClampedArray(4*t.length);for(let o=0;ob.map(x=>x.arraySync())),dogPyramidImages:o.map(b=>b?b.arraySync():null),extremasResults:r.map(b=>b.arraySync()),extremaAngles:u.arraySync(),prunedExtremas:i,localizedExtremas:a.arraySync()}),s.forEach(b=>b.forEach(x=>x.dispose())),o.forEach(b=>b&&b.dispose()),r.forEach(b=>b.dispose()),a.dispose(),c.dispose(),l.dispose(),u.dispose(),d.dispose(),h.dispose();const g=[];for(let b=0;b0,x:C,y:k,scale:S,angle:f[b],descriptors:x})}return{featurePoints:g,debugExtra:e}}_computeFreakDescriptors(t){if(!this.tensorCaches.computeFreakDescriptors){const s=[],o=[];for(let a=0;azt().runKernel("ComputeFreakDescriptors",{extremaFreaks:t,positionT:e}))}_computeExtremaFreak(t,e,s){this.tensorCaches._computeExtremaFreak||M(()=>{const i=tn($o);this.tensorCaches._computeExtremaFreak={freakPointsT:en(i)}});const{freakPointsT:o}=this.tensorCaches._computeExtremaFreak,r=[];for(let i=1;izt().runKernel("ComputeExtremaFreak",{gaussianImagesT:r,prunedExtremas:e,prunedExtremasAngles:s,freakPointsT:o,pyramidImagesLength:t.length}))}_computeExtremaAngles(t){return M(()=>zt().runKernel("ComputeExtremaAngles",{histograms:t}))}_computeOrientationHistograms(t,e){const s=[];for(let r=1;r{const r=-1/(2*Qp*Qp),i=Qp*V9,a=Math.ceil(i),c=[];for(let l=-a;l<=a;l++)for(let u=-a;u<=a;u++){const d=u*u+l*l;if(d<=i*i){const h=d*r;let p=(720+h*(720+h*(360+h*(120+h*(30+h*(6+h))))))*.0013888888;c.push([l,u,p])}}this.tensorCaches.orientationHistograms={radialPropertiesT:en(tn(c,[c.length,3]))}});const{radialPropertiesT:o}=this.tensorCaches.orientationHistograms;return M(()=>zt().runKernel("ComputeOrientationHistograms",{gaussianImagesT:s,prunedExtremasT:t,radialPropertiesT:o,pyramidImagesLength:e.length}))}_smoothHistograms(t){return M(()=>zt().runKernel("SmoothHistograms",{histograms:t}))}_computeLocalization(t,e){return M(()=>{const o=zt().runKernel("ComputeLocalization",{prunedExtremasList:t,dogPyramidImagesT:e}).arraySync(),r=[];for(let a=0;a{for(let a=0;a=1&&T>o[S][R-1];)R-=1;if(R=R+1;L--)o[S][L]=o[S][L-1],r[S][L][0]=r[S][L-1][0],r[S][L][1]=r[S][L-1][1],r[S][L][2]=r[S][L-1][2],r[S][L][3]=r[S][L-1][3];o[S][R]=T,r[S][R][0]=x,r[S][R][1]=l,r[S][R][2]=w,r[S][R][3]=y}}}});const i=[];for(let a=0;azt().runKernel("BuildExtremas",{image0:t,image1:e,image2:s}))}_differenceImageBinomial(t,e){return M(()=>t.sub(e))}_applyFilter(t){return M(()=>zt().runKernel("BinomialFilter",{image:t}))}_downsampleBilinear(t){return M(()=>zt().runKernel("DownsampleBilinear",{image:t}))}_compileAndRun(t,e){const s=ys().compileAndRun(t,e);return zt().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}_runWebGLProgram(t,e,s){const o=ys().runWebGLProgram(t,e,s);return zt().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}}class F9{constructor(t,e,s=!1){this.debugMode=s,this.width=t,this.height=e;let o=Math.min(t,e)/2,r=Math.pow(2,Math.round(Math.log(o)/Math.log(2)));this.cropSize=r,this.detector=new GI(r,r,s),this.kernelCaches={},this.lastRandomIndex=4}detect(t){const e=Math.floor(this.height/2-this.cropSize/2),s=Math.floor(this.width/2-this.cropSize/2),o=this._detect(t,s,e);return this.debugMode&&(o.debugExtra.crop={startX:s,startY:e,cropSize:this.cropSize}),o}detectMoving(t){const e=this.lastRandomIndex%3,s=Math.floor(this.lastRandomIndex/3);let o=Math.floor(this.height/2-this.cropSize+s*this.cropSize/2),r=Math.floor(this.width/2-this.cropSize+e*this.cropSize/2);return r<0&&(r=0),o<0&&(o=0),r>=this.width-this.cropSize&&(r=this.width-this.cropSize-1),o>=this.height-this.cropSize&&(o=this.height-this.cropSize-1),this.lastRandomIndex=(this.lastRandomIndex+1)%9,this._detect(t,r,o)}_detect(t,e,s){const o=t.slice([s,e],[this.cropSize,this.cropSize]),{featurePoints:r,debugExtra:i}=this.detector.detect(o);return r.forEach(a=>{a.x+=e,a.y+=s}),this.debugMode&&(i.projectedImage=o.arraySync()),o.dispose(),{featurePoints:r,debugExtra:i}}}const LI=({image:n,ratio:t})=>{const e=Math.round(n.width*t),s=Math.round(n.height*t),o=new Uint8Array(e*s);for(let r=0;r=n.width&&(a=n.width-1);for(let c=0;c=n.height&&(u=n.height-1);let d=0,h=0;for(let p=i;p<=a;p++)for(let f=l;f<=u;f++)d+=1*n.data[f*n.width+p],h+=1;o[c*e+r]=Math.floor(d/h)}}return{data:o,width:e,height:s}},z9=100,X9=n=>{const t=z9/Math.min(n.width,n.height),e=[];let s=t;for(;;)if(e.push(s),s*=Math.pow(2,1/3),s>=.95){s=1;break}e.push(s),e.reverse();const o=[];for(let r=0;r{const t=Math.min(n.width,n.height),e=[],s=[];e.push(256/t),e.push(128/t);for(let o=0;o{const{v1:t,v2:e}=n;let s=0;for(let o=0;o>>0;s+=O9(r)}return s},O9=n=>{var t=n-(n>>1&1431655765);return t=(t>>2&858993459)+(t&858993459),t=(t>>4)+t&252645135,t=(t>>8)+t&16711935,t=(t>>16)+t&65535,t},K9=1234,Z9=()=>({seed:K9,arrayShuffle(t){const{arr:e,sampleSize:s}=t;for(let o=0;o>16&32767;r=r%e.length;let i=e[o];e[o]=e[r],e[r]=i}},nextInt(t){this.seed=(214013*this.seed+2531011)%-2147483648;let e=this.seed>>16&32767;return e=e%t,e}}),B9=16,H9=128,Jp=8,_9=n=>{const{points:t,pointIndexes:e,randomizer:s}=n,o=[];for(let c=0;c{const t=[];for(let o=0;o{const{points:t,pointIndexes:e,centerPointIndex:s,randomizer:o}=n;let r=!1;(e.length<=Jp||e.length<=B9)&&(r=!0);const i={};if(!r){const c=_9({points:t,pointIndexes:e,randomizer:o});for(let l=0;l{a.children.push(DI({points:t,pointIndexes:i[c],centerPointIndex:c,randomizer:o}))}),a};var Go=4294967295;function U9(n,t,e){var s=e/4294967296,o=e;n.setUint32(t,s),n.setUint32(t+4,o)}function WI(n,t,e){var s=Math.floor(e/4294967296),o=e;n.setUint32(t,s),n.setUint32(t+4,o)}function MI(n,t){var e=n.getInt32(t),s=n.getUint32(t+4);return e*4294967296+s}function Y9(n,t){var e=n.getUint32(t),s=n.getUint32(t+4);return e*4294967296+s}var jp,qp,tf,Al=(typeof process>"u"||((jp=process==null?void 0:process.env)===null||jp===void 0?void 0:jp.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function VI(n){for(var t=n.length,e=0,s=0;s=55296&&o<=56319&&s>6&31|192;else{if(i>=55296&&i<=56319&&r>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128):(t[o++]=i>>12&15|224,t[o++]=i>>6&63|128)}else{t[o++]=i;continue}t[o++]=i&63|128}}var ma=Al?new TextEncoder:void 0,J9=Al?typeof process<"u"&&((qp=process==null?void 0:process.env)===null||qp===void 0?void 0:qp.TEXT_ENCODING)!=="force"?200:0:Go;function j9(n,t,e){t.set(ma.encode(n),e)}function q9(n,t,e){ma.encodeInto(n,t.subarray(e))}var t_=ma!=null&&ma.encodeInto?q9:j9,e_=4096;function FI(n,t,e){for(var s=t,o=s+e,r=[],i="";s65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|d&1023),r.push(d)}else r.push(a);r.length>=e_&&(i+=String.fromCharCode.apply(String,r),r.length=0)}return r.length>0&&(i+=String.fromCharCode.apply(String,r)),i}var n_=Al?new TextDecoder:null,s_=Al?typeof process<"u"&&((tf=process==null?void 0:process.env)===null||tf===void 0?void 0:tf.TEXT_DECODER)!=="force"?200:0:Go;function o_(n,t,e){var s=n.subarray(t,t+e);return n_.decode(s)}var Pl=function(){function n(t,e){this.type=t,this.data=e}return n}(),r_=function(){var n=function(t,e){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(s[r]=o[r])},n(t,e)};return function(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");n(t,e);function s(){this.constructor=t}t.prototype=e===null?Object.create(e):(s.prototype=e.prototype,new s)}}(),ts=function(n){r_(t,n);function t(e){var s=n.call(this,e)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(s,o),Object.defineProperty(s,"name",{configurable:!0,enumerable:!1,value:t.name}),s}return t}(Error),i_=-1,a_=4294967296-1,c_=17179869184-1;function l_(n){var t=n.sec,e=n.nsec;if(t>=0&&e>=0&&t<=c_)if(e===0&&t<=a_){var s=new Uint8Array(4),o=new DataView(s.buffer);return o.setUint32(0,t),s}else{var r=t/4294967296,i=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|r&3),o.setUint32(4,i),s}else{var s=new Uint8Array(12),o=new DataView(s.buffer);return o.setUint32(0,e),WI(o,4,t),s}}function u_(n){var t=n.getTime(),e=Math.floor(t/1e3),s=(t-e*1e3)*1e6,o=Math.floor(s/1e9);return{sec:e+o,nsec:s-o*1e9}}function d_(n){if(n instanceof Date){var t=u_(n);return l_(t)}else return null}function h_(n){var t=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:{var e=t.getUint32(0),s=0;return{sec:e,nsec:s}}case 8:{var o=t.getUint32(0),r=t.getUint32(4),e=(o&3)*4294967296+r,s=o>>>2;return{sec:e,nsec:s}}case 12:{var e=MI(t,4),s=t.getUint32(0);return{sec:e,nsec:s}}default:throw new ts("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(n.length))}}function p_(n){var t=h_(n);return new Date(t.sec*1e3+t.nsec/1e6)}var f_={type:i_,encode:d_,decode:p_},zI=function(){function n(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(f_)}return n.prototype.register=function(t){var e=t.type,s=t.encode,o=t.decode;if(e>=0)this.encoders[e]=s,this.decoders[e]=o;else{var r=1+e;this.builtInEncoders[r]=s,this.builtInDecoders[r]=o}},n.prototype.tryToEncode=function(t,e){for(var s=0;sthis.maxDepth)throw new Error("Too deep objects in depth ".concat(e));t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.encodeObject(t,e)},n.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},n.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error("Too long string: ".concat(t," bytes in UTF-8"))},n.prototype.encodeString=function(t){var e=5,s=t.length;if(s>J9){var o=VI(t);this.ensureBufferSizeToWrite(e+o),this.writeStringHeader(o),t_(t,this.bytes,this.pos),this.pos+=o}else{var o=VI(t);this.ensureBufferSizeToWrite(e+o),this.writeStringHeader(o),Q9(t,this.bytes,this.pos),this.pos+=o}},n.prototype.encodeObject=function(t,e){var s=this.extensionCodec.tryToEncode(t,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,e);else throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(t)))},n.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else if(e<4294967296)this.writeU8(198),this.writeU32(e);else throw new Error("Too large binary: ".concat(e));var s=Ol(t);this.writeU8a(s)},n.prototype.encodeArray=function(t,e){var s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error("Too large array: ".concat(s));for(var o=0,r=t;o0&&t<=this.maxKeyLength},n.prototype.find=function(t,e,s){var o=this.caches[s-1];t:for(var r=0,i=o;r=this.maxLengthPerKey?s[Math.random()*s.length|0]=o:s.push(o)},n.prototype.decode=function(t,e,s){var o=this.find(t,e,s);if(o!=null)return this.hit++,o;this.miss++;var r=FI(t,e,s),i=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(i,r),r},n}(),S_=function(n,t,e,s){function o(r){return r instanceof e?r:new e(function(i){i(r)})}return new(e||(e=Promise))(function(r,i){function a(u){try{l(s.next(u))}catch(d){i(d)}}function c(u){try{l(s.throw(u))}catch(d){i(d)}}function l(u){u.done?r(u.value):o(u.value).then(a,c)}l((s=s.apply(n,t||[])).next())})},nf=function(n,t){var e={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},s,o,r,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(l){return function(u){return c([l,u])}}function c(l){if(s)throw new TypeError("Generator is already executing.");for(;e;)try{if(s=1,o&&(r=l[0]&2?o.return:l[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,l[1])).done)return r;switch(o=0,r&&(l=[l[0]&2,r.value]),l[0]){case 0:case 1:r=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,o=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(r=e.trys,!(r=r.length>0&&r[r.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!r||l[1]>r[0]&&l[1]1||a(h,p)})})}function a(h,p){try{c(s[h](p))}catch(f){d(r[0][3],f)}}function c(h){h.value instanceof wr?Promise.resolve(h.value.v).then(l,u):d(r[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,p){h(p),r.shift(),r.length&&a(r[0][0],r[0][1])}},T_=function(n){var t=typeof n;return t==="string"||t==="number"},ga=-1,sf=new DataView(new ArrayBuffer(0)),N_=new Uint8Array(sf.buffer),of=function(){try{sf.getInt8(0)}catch(n){return n.constructor}throw new Error("never reached")}(),AI=new of("Insufficient data"),R_=new v_,$_=function(){function n(t,e,s,o,r,i,a,c){t===void 0&&(t=zI.defaultCodec),e===void 0&&(e=void 0),s===void 0&&(s=Go),o===void 0&&(o=Go),r===void 0&&(r=Go),i===void 0&&(i=Go),a===void 0&&(a=Go),c===void 0&&(c=R_),this.extensionCodec=t,this.context=e,this.maxStrLength=s,this.maxBinLength=o,this.maxArrayLength=r,this.maxMapLength=i,this.maxExtLength=a,this.keyDecoder=c,this.totalPos=0,this.pos=0,this.view=sf,this.bytes=N_,this.headByte=ga,this.stack=[]}return n.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=ga,this.stack.length=0},n.prototype.setBuffer=function(t){this.bytes=Ol(t),this.view=m_(this.bytes),this.pos=0},n.prototype.appendBuffer=function(t){if(this.headByte===ga&&!this.hasRemaining(1))this.setBuffer(t);else{var e=this.bytes.subarray(this.pos),s=Ol(t),o=new Uint8Array(e.length+s.length);o.set(e),o.set(s,e.length),this.setBuffer(o)}},n.prototype.hasRemaining=function(t){return this.view.byteLength-this.pos>=t},n.prototype.createExtraByteError=function(t){var e=this,s=e.view,o=e.pos;return new RangeError("Extra ".concat(s.byteLength-o," of ").concat(s.byteLength," byte(s) found at buffer[").concat(t,"]"))},n.prototype.decode=function(t){this.reinitializeState(),this.setBuffer(t);var e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e},n.prototype.decodeMulti=function(t){return nf(this,function(e){switch(e.label){case 0:this.reinitializeState(),this.setBuffer(t),e.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return e.sent(),[3,1];case 3:return[2]}})},n.prototype.decodeAsync=function(t){var e,s,o,r;return S_(this,void 0,void 0,function(){var i,a,c,l,u,d,h,p;return nf(this,function(f){switch(f.label){case 0:i=!1,f.label=1;case 1:f.trys.push([1,6,7,12]),e=XI(t),f.label=2;case 2:return[4,e.next()];case 3:if(s=f.sent(),!!s.done)return[3,5];if(c=s.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),i=!0}catch(m){if(!(m instanceof of))throw m}this.totalPos+=this.pos,f.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=f.sent(),o={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),s&&!s.done&&(r=e.return)?[4,r.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw u=this,d=u.headByte,h=u.pos,p=u.totalPos,new RangeError("Insufficient data in parsing ".concat(ef(d)," at ").concat(p," (").concat(h," in the current buffer)"))}})})},n.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},n.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},n.prototype.decodeMultiAsync=function(t,e){return k_(this,arguments,function(){var o,r,i,a,c,l,u,d,h;return nf(this,function(p){switch(p.label){case 0:o=e,r=-1,p.label=1;case 1:p.trys.push([1,13,14,19]),i=XI(t),p.label=2;case 2:return[4,wr(i.next())];case 3:if(a=p.sent(),!!a.done)return[3,12];if(c=a.value,e&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),o&&(r=this.readArraySize(),o=!1,this.complete()),p.label=4;case 4:p.trys.push([4,9,,10]),p.label=5;case 5:return[4,wr(this.doDecodeSync())];case 6:return[4,p.sent()];case 7:return p.sent(),--r===0?[3,8]:[3,5];case 8:return[3,10];case 9:if(l=p.sent(),!(l instanceof of))throw l;return[3,10];case 10:this.totalPos+=this.pos,p.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return u=p.sent(),d={error:u},[3,19];case 14:return p.trys.push([14,,17,18]),a&&!a.done&&(h=i.return)?[4,wr(h.call(i))]:[3,16];case 15:p.sent(),p.label=16;case 16:return[3,18];case 17:if(d)throw d.error;return[7];case 18:return[7];case 19:return[2]}})})},n.prototype.doDecodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){var s=t-128;if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t<160){var s=t-144;if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else{var o=t-160;e=this.decodeUtf8String(o,0)}else if(t===192)e=null;else if(t===194)e=!1;else if(t===195)e=!0;else if(t===202)e=this.readF32();else if(t===203)e=this.readF64();else if(t===204)e=this.readU8();else if(t===205)e=this.readU16();else if(t===206)e=this.readU32();else if(t===207)e=this.readU64();else if(t===208)e=this.readI8();else if(t===209)e=this.readI16();else if(t===210)e=this.readI32();else if(t===211)e=this.readI64();else if(t===217){var o=this.lookU8();e=this.decodeUtf8String(o,1)}else if(t===218){var o=this.lookU16();e=this.decodeUtf8String(o,2)}else if(t===219){var o=this.lookU32();e=this.decodeUtf8String(o,4)}else if(t===220){var s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else if(t===221){var s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else if(t===222){var s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t===223){var s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t===196){var s=this.lookU8();e=this.decodeBinary(s,1)}else if(t===197){var s=this.lookU16();e=this.decodeBinary(s,2)}else if(t===198){var s=this.lookU32();e=this.decodeBinary(s,4)}else if(t===212)e=this.decodeExtension(1,0);else if(t===213)e=this.decodeExtension(2,0);else if(t===214)e=this.decodeExtension(4,0);else if(t===215)e=this.decodeExtension(8,0);else if(t===216)e=this.decodeExtension(16,0);else if(t===199){var s=this.lookU8();e=this.decodeExtension(s,1)}else if(t===200){var s=this.lookU16();e=this.decodeExtension(s,2)}else if(t===201){var s=this.lookU32();e=this.decodeExtension(s,4)}else throw new ts("Unrecognized type byte: ".concat(ef(t)));this.complete();for(var r=this.stack;r.length>0;){var i=r[r.length-1];if(i.type===0)if(i.array[i.position]=e,i.position++,i.position===i.size)r.pop(),e=i.array;else continue t;else if(i.type===1){if(!T_(e))throw new ts("The type of key must be string or number but "+typeof e);if(e==="__proto__")throw new ts("The key __proto__ is not allowed");i.key=e,i.type=2;continue t}else if(i.map[i.key]=e,i.readCount++,i.readCount===i.size)r.pop(),e=i.map;else{i.key=null,i.type=1;continue t}}return e}},n.prototype.readHeadByte=function(){return this.headByte===ga&&(this.headByte=this.readU8()),this.headByte},n.prototype.complete=function(){this.headByte=ga},n.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new ts("Unrecognized array type byte: ".concat(ef(t)))}}},n.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new ts("Max length exceeded: map length (".concat(t,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},n.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new ts("Max length exceeded: array length (".concat(t,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:t,array:new Array(t),position:0})},n.prototype.decodeUtf8String=function(t,e){var s;if(t>this.maxStrLength)throw new ts("Max length exceeded: UTF-8 byte length (".concat(t,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengths_?r=o_(this.bytes,o,t):r=FI(this.bytes,o,t),this.pos+=e+t,r},n.prototype.stateIsMapKey=function(){if(this.stack.length>0){var t=this.stack[this.stack.length-1];return t.type===1}return!1},n.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new ts("Max length exceeded: bin length (".concat(t,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(t+e))throw AI;var s=this.pos+e,o=this.bytes.subarray(s,s+t);return this.pos+=e+t,o},n.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new ts("Max length exceeded: ext length (".concat(t,") > maxExtLength (").concat(this.maxExtLength,")"));var s=this.view.getInt8(this.pos+e),o=this.decodeBinary(t,e+1);return this.extensionCodec.decode(o,s,this.context)},n.prototype.lookU8=function(){return this.view.getUint8(this.pos)},n.prototype.lookU16=function(){return this.view.getUint16(this.pos)},n.prototype.lookU32=function(){return this.view.getUint32(this.pos)},n.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},n.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},n.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},n.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},n.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},n.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},n.prototype.readU64=function(){var t=Y9(this.view,this.pos);return this.pos+=8,t},n.prototype.readI64=function(){var t=MI(this.view,this.pos);return this.pos+=8,t},n.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},n.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},n}(),G_={};function L_(n,t){t===void 0&&(t=G_);var e=new $_(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength);return e.decode(n)}const PI=2;class E_{constructor(){this.data=null}compileImageTargets(t,e){return new Promise(async(s,o)=>{const r=[];for(let l=0;l{a+=h,e(a)});this.data.push({targetImage:u,imageList:d,matchingData:p})}for(let l=0;l{const e=[];for(let s=0;s{const i=tn(o.data,[o.data.length],"float32").reshape([o.height,o.width]),{featurePoints:a}=r.detect(i),c=a.filter(h=>h.maxima),l=a.filter(h=>!h.maxima),u=EI({points:c}),d=EI({points:l});e.push({maximaPoints:c,minimaPoints:l,maximaPointsCluster:u,minimaPointsCluster:d,width:o.width,height:o.height,scale:o.scale}),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RJbWFnZXM6dH09cyxvPTEwMC90Lmxlbmd0aDtsZXQgZT0wO2NvbnN0IG49W107Zm9yKGxldCBhPTA7YTx0Lmxlbmd0aDthKyspe2NvbnN0IGc9dFthXSxkPVkoZyksdz1vL2QubGVuZ3RoLGo9VyhkLEU9PntlKz13LHBvc3RNZXNzYWdlKHt0eXBlOiJwcm9ncmVzcyIscGVyY2VudDplfSl9KTtuLnB1c2goail9cG9zdE1lc3NhZ2Uoe3R5cGU6ImNvbXBpbGVEb25lIixsaXN0Om59KX19fSkoKTsK",KI=typeof window<"u"&&window.Blob&&new Blob([atob(OI)],{type:"text/javascript;charset=utf-8"});function W_(n){let t;try{if(t=KI&&(window.URL||window.webkitURL).createObjectURL(KI),!t)throw"";const e=new Worker(t,{name:n==null?void 0:n.name});return e.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:application/javascript;base64,"+OI,{name:n==null?void 0:n.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}class ZI extends E_{createProcessCanvas(t){const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e}compileTrack({progressCallback:t,targetImages:e,basePercent:s}){return new Promise((o,r)=>{const i=new W_;i.onmessage=a=>{a.data.type==="progress"?t(s+a.data.percent*s/100):a.data.type==="compileDone"&&o(a.data.list)},i.postMessage({type:"compile",targetImages:e})})}}class M_{constructor(t,e){this.width=t,this.height=e,this.texShape=[e,t];const s=document.createElement("canvas").getContext("2d");s.canvas.width=t,s.canvas.height=e,this.context=s,this.program=this.buildProgram(t,e);const o=ys();this.tempPixelHandle=o.makeTensorInfo(this.texShape,"float32"),o.texData.get(this.tempPixelHandle.dataId).usage=2}_loadInput(t){return M(()=>{let e=CT(t);return e=e.mean(2),e})}loadInput(t){const e=this.context;if(e.clearRect(0,0,this.context.canvas.width,this.context.canvas.height),t.width===this.height&&t.height===this.width){let i=this.context.canvas.width/2,a=this.context.canvas.height/2,c=90;e.save(),e.translate(i,a),e.rotate(c*Math.PI/180),e.drawImage(t,-t.width/2,-t.height/2),e.restore()}else this.context.drawImage(t,0,0,t.width,t.height);const o=ys();return o.gpgpu.uploadPixelDataToTexture(o.getTexture(this.tempPixelHandle.dataId),this.context.canvas),this._compileAndRun(this.program,[this.tempPixelHandle])}buildProgram(t,e){const s=z().getNumber("WEBGL_VERSION")===2?"texture":"texture2D";return{variableNames:["A"],outputShape:this.texShape,userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${t}.0, ${e}.0); + + vec4 values = ${s}(A, uv); + setOutput((0.299 * values.r + 0.587 * values.g + 0.114 * values.b) * 255.0); + } + `}}_compileAndRun(t,e){const s=ys().compileAndRun(t,e);return zt().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}_runWebGLProgram(t,e,s){const o=ys().runWebGLProgram(t,e,s);return zt().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}}const BI=(n,t)=>{const e=2*Math.PI*t*n;return e/(e+1)},HI=(n,t,e)=>n*t+(1-n)*e;class V_{constructor({minCutOff:t,beta:e}){this.minCutOff=t,this.beta=e,this.dCutOff=.001,this.xPrev=null,this.dxPrev=null,this.tPrev=null,this.initialized=!1}reset(){this.initialized=!1}filter(t,e){if(!this.initialized)return this.initialized=!0,this.xPrev=e,this.dxPrev=e.map(()=>0),this.tPrev=t,e;const{xPrev:s,tPrev:o,dxPrev:r}=this,i=t-o,a=BI(i,this.dCutOff),c=[],l=[],u=[];for(let d=0;d{f.data.type==="matchDone"&&this.workerMatchDone!==null&&this.workerMatchDone(f.data),f.data.type==="trackUpdateDone"&&this.workerTrackDone!==null&&this.workerTrackDone(f.data)}}showTFStats(){console.log(rf.memory().numTensors),console.table(rf.memory())}addImageTargets(t){return new Promise(async(e,s)=>{const r=await(await fetch(t)).arrayBuffer(),i=this.addImageTargetsFromBuffer(r);e(i)})}addImageTargetsFromBuffer(t){const s=new ZI().importData(t),o=[],r=[],i=[];for(let a=0;a{for(;this.processingVideo;){const s=this.inputLoader.loadInput(t);if(this.trackingStates.reduce((r,i)=>r+(i.isTracking?1:0),0)this.warmupTolerance&&(i.showing=!0,i.trackingMatrix=null,i.filter.reset())),i.showing&&(i.isTracking?i.trackMiss=0:(i.trackCount=0,i.trackMiss+=1,i.trackMiss>this.missTolerance&&(i.showing=!1,i.trackingMatrix=null,this.onUpdate&&this.onUpdate({type:"updateMatrix",targetIndex:r,worldMatrix:null})))),i.showing){const a=this._glModelViewMatrix(i.currentModelViewTransform,r);i.trackingMatrix=i.filter.filter(Date.now(),a);let c=[];for(let u=0;u{this.workerMatchDone=r=>{s({targetIndex:r.targetIndex,modelViewTransform:r.modelViewTransform,debugExtra:r.debugExtra})},this.worker.postMessage({type:"match",featurePoints:t,targetIndexes:e})})}_workerTrackUpdate(t,e){return new Promise(async(s,o)=>{this.workerTrackDone=a=>{s(a.modelViewTransform)};const{worldCoords:r,screenCoords:i}=e;this.worker.postMessage({type:"trackUpdate",modelViewTransform:t,worldCoords:r,screenCoords:i})})}_glModelViewMatrix(t,e){const s=this.markerDimensions[e][1];return[t[0][0],-t[1][0],-t[2][0],0,-t[0][1],t[1][1],t[2][1],0,-t[0][2],t[1][2],t[2][2],0,t[0][1]*s+t[0][3],-(t[1][1]*s+t[1][3]),-(t[2][1]*s+t[2][3]),1]}_glProjectionMatrix({projectionTransform:t,width:e,height:s,near:o,far:r}){const i=[[2*t[0][0]/e,0,-(2*t[0][2]/e-1),0],[0,2*t[1][1]/s,-(2*t[1][2]/s-1),0],[0,0,-(r+o)/(r-o),-2*r*o/(r-o)],[0,0,-1,0]],a=[];for(let c=0;c<4;c++)for(let l=0;l<4;l++)a.push(i[l][c]);return a}}const P_=`
+
+
+`,O_=`
+
+

Failed to launch :(

+

+ Looks like your device/browser is not compatible. +

+ +
+
+

+ Please try the following recommended browsers: +

+

+ For Android device - Chrome +

+

+ For iOS device - Safari +

+
+
+`,K_=`
+
+
+
+
+
+
+`,Z_=".mindar-ui-overlay{display:flex;align-items:center;justify-content:center;position:absolute;left:0;right:0;top:0;bottom:0;background:transparent;z-index:2}.mindar-ui-overlay.hidden{display:none}.mindar-ui-loading .loader{border:16px solid #222;border-top:16px solid white;opacity:.8;border-radius:50%;width:120px;height:120px;animation:spin 2s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.mindar-ui-compatibility .content{background:black;color:#fff;opacity:.8;text-align:center;margin:20px;padding:20px;min-height:50vh}@media (min-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:50vh;height:50vh}}@media (max-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:80vw;height:80vw}}.mindar-ui-scanning .scanning .inner{position:relative;width:100%;height:100%;opacity:.8;background:linear-gradient(to right,white 10px,transparent 10px) 0 0,linear-gradient(to right,white 10px,transparent 10px) 0 100%,linear-gradient(to left,white 10px,transparent 10px) 100% 0,linear-gradient(to left,white 10px,transparent 10px) 100% 100%,linear-gradient(to bottom,white 10px,transparent 10px) 0 0,linear-gradient(to bottom,white 10px,transparent 10px) 100% 0,linear-gradient(to top,white 10px,transparent 10px) 0 100%,linear-gradient(to top,white 10px,transparent 10px) 100% 100%;background-repeat:no-repeat;background-size:40px 40px}.mindar-ui-scanning .scanning .inner .scanline{position:absolute;width:100%;height:10px;background:white;animation:move 2s linear infinite}@keyframes move{0%,to{top:0%}50%{top:calc(100% - 10px)}}";class UI{constructor({uiLoading:t,uiScanning:e,uiError:s}){const o=document.createElement("style");o.innerText=Z_,document.head.appendChild(o),t==="yes"?this.loadingModal=this._loadHTML(P_):t!=="no"&&(this.loadingModal=document.querySelector(t)),s==="yes"?this.compatibilityModal=this._loadHTML(O_):s!=="no"&&(this.compatibilityModal=document.querySelector(s)),e==="yes"?this.scanningMask=this._loadHTML(K_):e!=="no"&&(this.scanningMask=document.querySelector(e)),this.hideLoading(),this.hideCompatibility(),this.hideScanning()}showLoading(){this.loadingModal&&this.loadingModal.classList.remove("hidden")}hideLoading(){this.loadingModal&&this.loadingModal.classList.add("hidden")}showCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.remove("hidden")}hideCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.add("hidden")}showScanning(){this.scanningMask&&this.scanningMask.classList.remove("hidden")}hideScanning(){this.scanningMask&&this.scanningMask.classList.add("hidden")}_loadHTML(t){const e=document.createElement("template");e.innerHTML=t.trim();const s=e.content.firstChild;return document.getElementsByTagName("body")[0].appendChild(s),s}}window.MINDAR||(window.MINDAR={}),window.MINDAR.IMAGE={Controller:_I,Compiler:ZI,UI},AFRAME.registerSystem("mindar-image-system",{container:null,video:null,processingImage:!1,init:function(){this.anchorEntities=[]},tick:function(){},setup:function({imageTargetSrc:n,maxTrack:t,showStats:e,uiLoading:s,uiScanning:o,uiError:r,missTolerance:i,warmupTolerance:a,filterMinCF:c,filterBeta:l}){this.imageTargetSrc=n,this.maxTrack=t,this.filterMinCF=c,this.filterBeta=l,this.missTolerance=i,this.warmupTolerance=a,this.showStats=e,this.ui=new UI({uiLoading:s,uiScanning:o,uiError:r})},registerAnchor:function(n,t){this.anchorEntities.push({el:n,targetIndex:t})},start:function(){this.container=this.el.sceneEl.parentNode,this.showStats&&(this.mainStats=new Stats,this.mainStats.showPanel(0),this.mainStats.domElement.style.cssText="position:absolute;top:0px;left:0px;z-index:999",this.container.appendChild(this.mainStats.domElement)),this.ui.showLoading(),this._startVideo()},switchTarget:function(n){this.controller.interestedTargetIndex=n},stop:function(){this.pause(),this.video.srcObject.getTracks().forEach(function(t){t.stop()}),this.video.remove(),this.controller.dispose()},pause:function(n=!1){n||this.video.pause(),this.controller.stopProcessVideo()},unpause:function(){this.video.play(),this.controller.processVideo(this.video)},_startVideo:function(){if(this.video=document.createElement("video"),this.video.setAttribute("autoplay",""),this.video.setAttribute("muted",""),this.video.setAttribute("playsinline",""),this.video.style.position="absolute",this.video.style.top="0px",this.video.style.left="0px",this.video.style.zIndex="-2",this.container.appendChild(this.video),!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){this.el.emit("arError",{error:"VIDEO_FAIL"}),this.ui.showCompatibility();return}navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"environment",width:{ideal:1920,max:2560,min:1280},height:{ideal:1080,max:1920,min:720}}}).then(n=>{this.video.addEventListener("loadedmetadata",()=>{this.video.setAttribute("width",this.video.videoWidth),this.video.setAttribute("height",this.video.videoHeight),this._startAR()}),this.video.srcObject=n}).catch(n=>{console.log("getUserMedia error",n),this.el.emit("arError",{error:"VIDEO_FAIL"})})},_startAR:async function(){const n=this.video;this.container,this.controller=new _I({inputWidth:n.videoWidth,inputHeight:n.videoHeight,maxTrack:this.maxTrack,filterMinCF:this.filterMinCF,filterBeta:this.filterBeta,missTolerance:this.missTolerance,warmupTolerance:this.warmupTolerance,onUpdate:e=>{if(e.type==="processDone")this.mainStats&&this.mainStats.update();else if(e.type==="updateMatrix"){const{targetIndex:s,worldMatrix:o}=e;for(let i=0;ii||a.el.el.object3D.visible,!1)?this.ui.hideScanning():this.ui.showScanning()}}}),this._resize(),window.addEventListener("resize",this._resize.bind(this));const{dimensions:t}=await this.controller.addImageTargets(this.imageTargetSrc);for(let e=0;er?(s=t.clientHeight,e=s*o):(e=t.clientWidth,s=e/o);const i=this.controller.getProjectionMatrix(),a=2*Math.atan(1/i[5]/s*t.clientHeight)*180/Math.PI,c=i[14]/(i[10]-1),l=i[14]/(i[10]+1);i[5]/i[0];const u=t.clientWidth/t.clientHeight,h=t.getElementsByTagName("a-camera")[0].getObject3D("camera");h.fov=a,h.aspect=u,h.near=c,h.far=l,h.updateProjectionMatrix(),this.video.style.top=-(s-t.clientHeight)/2+"px",this.video.style.left=-(e-t.clientWidth)/2+"px",this.video.style.width=e+"px",this.video.style.height=s+"px"}}),AFRAME.registerComponent("mindar-image",{dependencies:["mindar-image-system"],schema:{imageTargetSrc:{type:"string"},maxTrack:{type:"int",default:1},filterMinCF:{type:"number",default:-1},filterBeta:{type:"number",default:-1},missTolerance:{type:"int",default:-1},warmupTolerance:{type:"int",default:-1},showStats:{type:"boolean",default:!1},autoStart:{type:"boolean",default:!0},uiLoading:{type:"string",default:"yes"},uiScanning:{type:"string",default:"yes"},uiError:{type:"string",default:"yes"}},init:function(){const n=this.el.sceneEl.systems["mindar-image-system"];n.setup({imageTargetSrc:this.data.imageTargetSrc,maxTrack:this.data.maxTrack,filterMinCF:this.data.filterMinCF===-1?null:this.data.filterMinCF,filterBeta:this.data.filterBeta===-1?null:this.data.filterBeta,missTolerance:this.data.missTolerance===-1?null:this.data.missTolerance,warmupTolerance:this.data.warmupTolerance===-1?null:this.data.warmupTolerance,showStats:this.data.showStats,uiLoading:this.data.uiLoading,uiScanning:this.data.uiScanning,uiError:this.data.uiError}),this.data.autoStart&&this.el.sceneEl.addEventListener("renderstart",()=>{n.start()})},remove:function(){this.el.sceneEl.systems["mindar-image-system"].stop()}}),AFRAME.registerComponent("mindar-image-target",{dependencies:["mindar-image-system"],schema:{targetIndex:{type:"number"}},postMatrix:null,init:function(){this.el.sceneEl.systems["mindar-image-system"].registerAnchor(this,this.data.targetIndex),this.invisibleMatrix=new AFRAME.THREE.Matrix4().set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const t=this.el.object3D;t.visible=!1,t.matrixAutoUpdate=!1,t.matrix=this.invisibleMatrix},setupMarker([n,t]){const e=new AFRAME.THREE.Vector3,s=new AFRAME.THREE.Quaternion,o=new AFRAME.THREE.Vector3;e.x=n/2,e.y=n/2+(t-n)/2,o.x=n,o.y=n,o.z=n,this.postMatrix=new AFRAME.THREE.Matrix4,this.postMatrix.compose(e,s,o)},updateWorldMatrix(n){if(this.el.emit("targetUpdate"),!this.el.object3D.visible&&n!==null?this.el.emit("targetFound"):this.el.object3D.visible&&n===null&&this.el.emit("targetLost"),this.el.object3D.visible=n!==null,n===null){this.el.object3D.matrix=this.invisibleMatrix;return}var t=new AFRAME.THREE.Matrix4;t.elements=n,t.multiply(this.postMatrix),this.el.object3D.matrix=t}})})(); diff --git a/static/js/screenshot.js b/static/js/screenshot.js new file mode 100644 index 0000000..1b4b013 --- /dev/null +++ b/static/js/screenshot.js @@ -0,0 +1,51 @@ +const RESOLUTION_SCALE = 2; + +function takeScreenshot() { + const video = document.querySelector("video"); + const canvas = document.createElement("canvas"); + + let vWidth = video.clientWidth * RESOLUTION_SCALE; + let vHeight = video.clientHeight * RESOLUTION_SCALE; + + canvas.width = vWidth; + canvas.height = vHeight; + + const element = document.querySelector("video"); + const style = window.getComputedStyle(element); + const top = style.getPropertyValue("top"); + + canvas.getContext("2d").drawImage(video, 0, parseFloat(top), vWidth, vHeight); + + const imgData = document.querySelector("a-scene").components.screenshot.getCanvas("perspective"); + + canvas.getContext("2d").drawImage(imgData, 0, 0, vWidth, vHeight); + + downloadScreenshot(canvas); +} + +function downloadScreenshot(canvas) { + const a = document.createElement("a"); + a.href = canvas.toDataURL("image/png"); + a.download = imageName(); + a.click(); +} + +function imageName() { + return `demo_${getUUID()}.png`; +} + +function getUUID() { + const uuid = window.crypto.randomUUID(); + return uuid.split("-")[0] ?? uuid; +} + +// function formatDate(date) { +// return new Intl.DateTimeFormat("vi-VN", { +// year: "numeric", +// month: "2-digit", +// day: "2-digit", +// hour: "2-digit", +// minute: "2-digit", +// second: "2-digit", +// }).format(date); +// } diff --git a/static/mindar-target/5/targets.prod.mind b/static/mindar-target/5/targets.prod.mind new file mode 100644 index 0000000..0542588 Binary files /dev/null and b/static/mindar-target/5/targets.prod.mind differ