From d1ecfb0b1b40361975f030d3949a7c69238f972e Mon Sep 17 00:00:00 2001 From: Entry Dev Date: Mon, 7 Feb 2022 01:55:27 +0000 Subject: [PATCH] Entry Js PUBLISH by v3.20220207.434 --- dist/entry.js | 102 +++++++++--------- dist/entry.min.js | 2 +- .../blocks/hardware/block_microbit2.js | 102 +++++++++--------- 3 files changed, 103 insertions(+), 103 deletions(-) diff --git a/dist/entry.js b/dist/entry.js index d767f2a72d..91599926db 100644 --- a/dist/entry.js +++ b/dist/entry.js @@ -316737,37 +316737,37 @@ Entry.Microbit2 = new ( /*#__PURE__*/function () { }, jp: { template: { - microbit2_get_analog: 'ピン %1 のアナログ値', - microbit2_set_analog: 'ピン %1 にアナログ値 %2 を出力する %3', - microbit2_get_digital: 'ピン %1 のデジタル値', - microbit2_set_digital: 'ピン %1 に デジタル値 %2 を出力する %3', + microbit2_get_analog: 'たんし %1 のアナログ値', + microbit2_set_analog: 'たんし %1 のアナログ値 %2 を出力する %3', + microbit2_get_digital: 'たんし %1 のデジタル値', + microbit2_set_digital: 'たんし %1 にデジタル値 %2 を出力する %3', microbit2_screen_toggle: 'LED機能を %1 %2', microbit2_set_led: 'LEDの X: %1 Y: %2 を明るさ %3 にする %4', microbit2_get_led: 'LEDの X: %1 Y: %2 の明るさ', microbit2_show_preset_image: 'LEDに %1 アイコンを表示する %2', - microbit2_show_custom_image: 'LED %1 を表示する %2', + microbit2_show_custom_image: 'LEDに %1 を表示する %2', microbit2_show_string: 'LEDに %1 を表示する %2', microbit2_reset_screen: 'LEDを全部消す %1', - microbit2_radio_toggle: 'ラジオ機能を %1 %2', - microbit2_radio_setting: 'ラジオチャンネルを %1 に変更する %2', - microbit2_radio_send: 'ラジオに %1 送信する %2', - microbit2_radio_received: 'ラジオ受信値', - microbit2_speaker_toggle: 'スピーカー機能 %1 %2', - microbit2_change_tempo: 'テンポを %1 拍に %2 BPMにする %3', - microbit2_set_tone: '%1 音を %2 拍演奏する %3', - microbit2_play_preset_music: '%1 音楽を演奏する %2', - microbit2_play_sound_effect: '%1 効果音を演奏する %2', - microbit2_get_btn: '%1 ボタンが押したkか?', - microbit2_get_logo: 'ロゴをタッチしたじか?', - microbit2_get_gesture: '動きが %1 なのか?', + microbit2_radio_toggle: 'むせん機能を %1 %2', + microbit2_radio_setting: 'むせんのチャンネルを %1 に変える %2', + microbit2_radio_send: 'むせんで %1 を送信する %2', + microbit2_radio_received: '受信した値', + microbit2_speaker_toggle: 'スピーカー機能を %1 %2', + microbit2_change_tempo: '長さ %1 拍、テンポ %2 (bpm)にする %3', + microbit2_set_tone: '%1 音を長さ %2 拍鳴らす %3', + microbit2_play_preset_music: 'メロディ %1 を鳴らす %2', + microbit2_play_sound_effect: '効果音 %1 を鳴らす %2', + microbit2_get_btn: '%1 ボタンを押しているか?', + microbit2_get_logo: 'ロゴをタッチしているか?', + microbit2_get_gesture: '%1 か?', microbit2_get_acc: '%1 の加速度', - microbit2_get_direction: 'コンパス方向', - microbit2_get_field_strength_axis: '%1 の磁場強度', - microbit2_get_light_level: '光センサー値', - microbit2_get_temperature: '温度値', - microbit2_get_sound_level: 'マイク音の大きさ', - microbit2_set_servo: 'ピン %1 に サーボモーターの角度を %2 に設定する %3', - microbit2_set_pwm: 'ピン %1 にサーボパルス幅を2にする %4', + microbit2_get_direction: '方角(°)', + microbit2_get_field_strength_axis: '%1 の磁力', + microbit2_get_light_level: '明るさ', + microbit2_get_temperature: '温度(℃)', + microbit2_get_sound_level: 'まわりの音の大きさ', + microbit2_set_servo: 'たんし %1 にサーボモーターの角度 %2 を出力する %3', + microbit2_set_pwm: 'たんし %1 にサーボパルス幅 %2 %3 を出力する %4', microbit2_common_title: 'Common Blocks', microbit2_v2_title: 'v2 Only' }, @@ -316777,17 +316777,17 @@ Entry.Microbit2 = new ( /*#__PURE__*/function () { xAxis: 'X軸', yAxis: 'Y軸', zAxis: 'Z軸', - up: '上', - down: '下', - left: '右', - right: '左', - face_up: '全面', - face_down: '後面', - freefall: '自由落下', - '3g': '3G', - '6g': '6G', - '8g': '8G', - shake: '振れ', + up: '上をむいている', + down: '下をむいている', + left: '右をむいている', + right: '左をむいている', + face_up: '表をむいている', + face_down: '裏をむいている', + freefall: '落ちている', + '3g': 'しょうとつ(3G)', + '6g': 'しょうとつ(6G)', + '8g': 'しょうとつ(8G)', + shake: '振った', DADADADUM: '運命交響曲', ENTERTAINER: 'エンターネーター', PRELUDE: 'バッハ·プレリュード第1番', @@ -316888,10 +316888,10 @@ Entry.Microbit2 = new ( /*#__PURE__*/function () { microbit_2_ARROW_NW: '北西' }, Helper: { - microbit2_get_analog: '選択したピンのアナログ値です。(0 ~ 1023)', - microbit2_set_analog: '選択したピンに入力したアナログ値を出力します。(0 ~ 1023)', - microbit2_get_digital: '選択したピンのデジタル値です。(0, 1)', - microbit2_set_digital: '選択したピンに入力したデジタル値を出力します。(0, 1)', + microbit2_get_analog: '選択したたんしのアナログ値です。(0 ~ 1023)', + microbit2_set_analog: '選択したたんしに入力したアナログ値を出力します。(0 ~ 1023)', + microbit2_get_digital: '選択したたんしのデジタル値です。(0, 1)', + microbit2_set_digital: '選択したたんしに入力したデジタル値を出力します。(0, 1)', microbit2_screen_toggle: 'LED機能をオンまたはオフにします。', microbit2_set_led: 'X、Y座標で選択したLEDを選択した明るさで点けます。', microbit2_get_led: 'X、Y座標で選択したLEDの明るさです。', @@ -316899,26 +316899,26 @@ Entry.Microbit2 = new ( /*#__PURE__*/function () { microbit2_show_custom_image: 'ブロックで選択したLEDを選択した明るさで点けます。 一度にすべてのLEDを操作できます。', microbit2_show_string: '入力した文字列をLEDに順番に表示します。', microbit2_reset_screen: 'LEDに表示したものをすべて消します。', - microbit2_radio_toggle: 'ラジオ機能をオンまたはオフにします。', - microbit2_radio_setting: 'ラジオチャンネルを入力した数字に変えます。', - microbit2_radio_send: 'ラジオで入力した英数字を送信します。', - microbit2_radio_received: 'ラジオで受信した値です。', + microbit2_radio_toggle: 'むせん機能をオンまたはオフにします。', + microbit2_radio_setting: 'むせんチャンネルを入力した数字に変えます。', + microbit2_radio_send: 'むせんで入力した英数字を送信します。', + microbit2_radio_received: 'むせんで受信した値です。', microbit2_speaker_toggle: 'スピーカー機能をオンまたはオフにします。', - microbit2_change_tempo: 'テンポを選択した拍子とBPMで設定します。', + microbit2_change_tempo: '長さを選択した拍子とBPMで設定します。', microbit2_set_tone: '選択した音を選択した拍子で演奏します。 1~5オクターブ間の音階を選べます。', - microbit2_play_preset_music: '先に設定されていた音楽を演奏します。', + microbit2_play_preset_music: '先に設定されていたメロディを演奏します。', microbit2_play_sound_effect: '先に設定されていた効果音を演奏します。', microbit2_get_btn: '選択したボタンが押されたら、「True」と判断します。', microbit2_get_logo: 'ロゴをタッチすると、「True」と判断します。', microbit2_get_gesture: '選択した動きを感知したら、「True」と判断します。', microbit2_get_acc: '選択した軸の加速度値です。', - microbit2_get_direction: 'コンパス方向の値です。 (0~360)', - microbit2_get_field_strength_axis: '選択した軸の磁場強度の値です。', - microbit2_get_light_level: '光センサーの値です。', + microbit2_get_direction: '方角(°)の値です。 (0~360)', + microbit2_get_field_strength_axis: '選択した軸の磁力の値です。', + microbit2_get_light_level: '明るさの値です。', microbit2_get_temperature: '現在の温度です。 (℃)', - microbit2_get_sound_level: 'マイクボリュームの値です。', - microbit2_set_servo: '選択したピンにサーボモーターの角度を入力した値で設定します。', - microbit2_set_pwm: '選択したピンのサーボパルス幅を選択した値にします。' + microbit2_get_sound_level: 'まわりの音の大きさの値です。', + microbit2_set_servo: '選択したたんしにサーボモーターの角度を入力した値で設定します。', + microbit2_set_pwm: '選択したたんしのサーボパルス幅を選択した値にします。' }, Msgs: { microbit2_compatible_error: '対応するブロックはMicrobitV1と互換性がありません', diff --git a/dist/entry.min.js b/dist/entry.min.js index 382c0aa082..2dbd012a7a 100644 --- a/dist/entry.min.js +++ b/dist/entry.min.js @@ -1,2 +1,2 @@ /*! For license information please see entry.min.js.LICENSE.txt */ -!function(e){function t(t){for(var r,o,a=t[0],i=t[1],s=0,c=[];s1&&void 0!==arguments[1]?arguments[1]:{};return a(e).forEach((function(e){return e(t)})),t},t.isFactory=i,t.assertDependencies=s,t.isOptionalDependency=l,t.stripOptionalNotation=c;var n=r(15),o=r(24);function a(e){var t={};function r(e,o){if(i(e)){if((0,n.contains)(e.dependencies,o.fn||o.name))return!0;if(e.dependencies.some((function(e){return r(t[e],o)})))return!0}return!1}e.forEach((function(e){t[e.fn]=e}));var o=[];function a(e){for(var t=0;t=s.length)throw new o.IndexError(t,s.length);return(0,n.isMatrix)(e)?e.create(i(e.valueOf(),t,r)):i(e,t,r)},t.scatter=function(e,t,r,n,o,a,i,s,l,c,u){var p,d,_,h,f=e._values,y=e._index,m=e._ptr;if(n)for(d=m[t],_=m[t+1],p=d;p<_;p++)h=y[p],r[h]!==a?(r[h]=a,i.push(h),c?(n[h]=l?s(f[p],u):s(u,f[p]),o[h]=a):n[h]=f[p]):(n[h]=l?s(f[p],n[h]):s(n[h],f[p]),o[h]=a);else for(d=m[t],_=m[t+1],p=d;p<_;p++)h=y[p],r[h]!==a?(r[h]=a,i.push(h)):o[h]=a};var n=r(8),o=r(126),a=r(15);function i(e,t,r){var n,o,a,s;if(t<=0){if(Array.isArray(e[0])){for(s=function(e){var t,r,n=e.length,o=e[0].length,a=[];for(r=0;r=0;l--)(a=e[l])&&(s=(i<3?a(s):i>3?a(t,r,s):a(t,r))||s);return i>3&&s&&Object.defineProperty(t,r,s),s},t.__param=function(e,t){return function(r,n){t(r,n,e)}},t.__metadata=function(e,t){if("object"===("undefined"==typeof Reflect?"undefined":(0,o.default)(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},t.__awaiter=function(e,t,r,n){return new(r||(r=Promise))((function(o,a){function i(e){try{l(n.next(e))}catch(e){a(e)}}function s(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,s)}l((n=n.apply(e,t||[])).next())}))},t.__generator=function(e,t){var r,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]1||s(e,t)}))})}function s(e,t){try{(r=o[e](t)).value instanceof c?Promise.resolve(r.value.v).then(l,u):p(a[0][2],r)}catch(e){p(a[0][3],e)}var r}function l(e){s("next",e)}function u(e){s("throw",e)}function p(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}},t.__asyncDelegator=function(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,o){t[n]=e[n]?function(t){return(r=!r)?{value:c(e[n](t)),done:"return"===n}:o?o(t):t}:o}},t.__asyncValues=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=s(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}},t.__makeTemplateObject=function(e,t){Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t;return e},t.__importStar=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t},t.__importDefault=function(e){return e&&e.__esModule?e:{default:e}},t.__classPrivateFieldGet=function(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)},t.__classPrivateFieldSet=function(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r},t.__assign=void 0;var o=n(r(4)),a=function(e,t){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var i=function(){return t.__assign=i=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function l(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i}function c(e){return this instanceof c?(this.v=e,this):new c(e)}t.__assign=i},function(e,t,r){"use strict";e.exports=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arraySize=l,t.validate=function(e,t){if(0===t.length){if(Array.isArray(e))throw new i.DimensionError(e.length,0)}else!function e(t,r,n){var o,a=t.length;if(a!==r[n])throw new i.DimensionError(a,r[n]);if(n")}(e,t,0)},t.validateIndex=function(e,t){if(!(0,o.isNumber)(e)||!(0,n.isInteger)(e))throw new TypeError("Index must be an integer (value: "+e+")");if(e<0||"number"==typeof t&&e>=t)throw new s.IndexError(e,t)},t.resize=function(e,t,r){if(!Array.isArray(e)||!Array.isArray(t))throw new TypeError("Array expected");if(0===t.length)throw new Error("Resizing to scalar is not supported");t.forEach((function(e){if(!(0,o.isNumber)(e)||!(0,n.isInteger)(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+(0,a.format)(t)+")")}));var i=void 0!==r?r:0;return function e(t,r,n,o){var a,i,s=t.length,l=r[n],c=Math.min(s,l);if(t.length=l,n0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]0;)n=Math.random()*t|0,r=e[--t],e[t]=e[n],e[n]=r}function A(e,t,r){return Math.max(e,Math.min(t,r))}function x(e){return e%2==0?e:e+1}function D(e){for(var t=0,r=0;r=r?o():setTimeout(i,s)}}()}))}function H(e,t){for(var r=1,n=-1,o=0;o=0)r*=e[o];else if(-1===e[o]){if(-1!==n)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+o);n=o}else if(e[o]<0)throw Error("Shapes can not be < 0. Found "+e[o]+" at dim "+o);if(-1===n){if(t>0&&t!==r)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===r)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%r!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+r);var a=e.slice();return a[n]=t/r,a}function z(e,t){var r=t.length;return T((e=null==e?t.map((function(e,t){return t})):[].concat(e)).every((function(e){return e>=-r&&es)&&1===e[s]&&(r.push(e[s]),n.push(s)),a[i]<=s&&i++}1!==e[s]&&(r.push(e[s]),n.push(s))}return{newShape:r,keptDims:n}}function V(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(t)}return r}function U(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else if("bool"===e)r=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);r=new Array(t)}return r}function G(e,t){for(var r=0;r=0;--n)r[n]=r[n+1]*e[n+1];return r}function oe(e,t,r){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=L(e)),r&&G(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){for(var n=new Uint8Array(e.length),o=0;o=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+e+"]."}))}))}function ue(e,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",f().platform.encode(e,t)}function pe(e,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",f().platform.decode(e,t)}function de(e,t,r){if(0===t)return 0;if(1===t)return e[0];for(var n=e[e.length-1],o=0;o0?_:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+l+"D "+u+"\t%c"+c+"\t%c"+p+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},e}();function me(e,t,r){return F(Array.isArray(e)?parseFloat(e[0].toFixed(7))+" + "+parseFloat(e[1].toFixed(7))+"j":J(e)?"'"+e+"'":"bool"===r?ge(e):parseFloat(e.toFixed(7)).toString(),t)}function ge(e){return 0===e?"false":"true"}function be(e){for(var t=[],r=0;r=this.shape[r]){var i="Requested out of range element at "+e+". Buffer shape="+this.shape;throw new Error(i)}r++}for(var s=e[e.length-1],l=0;l1)for(var c=0;c20){var u=3*s,p=Array.from(t.slice(0,u)),d=Array.from(t.slice((l-3)*s,l*s));return"complex64"===n&&(p=be(p),d=be(d)),["["+p.map((function(e,t){return me(e,a[t],n)})).join(", ")+", ..., "+d.map((function(e,t){return me(e,a[l-3+t],n)})).join(", ")+"]"]}return["["+("complex64"===n?be(t):Array.from(t)).map((function(e,t){return me(e,a[t],n)})).join(", ")+"]"]}var _=r.slice(1),h=o.slice(1),f=o[0]*s,y=[];if(l>20){for(var m=0;m<3;m++){var g=(b=m*f)+f;y.push.apply(y,e(t.slice(b,g),_,n,h,a,!1))}for(y.push("..."),m=l-3;m0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+e+"'")},e.prototype.runKernelFunc=function(e,t,r,n,o,a,i){var s,l=this;void 0===a&&(a=[]),void 0===i&&(i=[]);var c=[],u=this.isTapeOn();null==n&&(n=null!=this.state.activeScope?this.state.activeScope.name:"");var p,d=function(e){u&&(c=e.map((function(e){return l.keep(l.clone(e))})))},_=this.state.numBytes,h=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var f,y=b(n,this.backendName);return p=null!=y?function(){var e=l.backend.numDataIds();f=y.kernelFunc({inputs:t,attrs:o,backend:l.backend});var r=Array.isArray(f)?f:[f];l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(n,e,r);var s=r.map((function(e){var t=e.dataId,r=e.shape,n=e.dtype;return l.makeTensorFromDataId(t,r,n)})),c=s.filter((function(e,t){return i[t]}));return d((a||[]).slice().concat(c)),s}:function(){var t=l.backend.numDataIds();f=l.tidy((function(){return e(l.backend,d)}));var r=Array.isArray(f)?f:[f];return l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(n,t,r),r},this.scopedRun((function(){return l.state.kernelDepth++}),(function(){return l.state.kernelDepth--}),(function(){s=l.ENV.getBool("DEBUG")?l.profiler.profileKernel(n,t,(function(){return p()})):p()})),u&&this.addTapeNode(n,t,s,r,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:n,bytesAdded:this.state.numBytes-_,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-h,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map((function(e){return t[e].shape})),outputShapes:s.map((function(e){return e.shape}))}),Array.isArray(f)?s:s[0]},e.prototype.makeTensor=function(e,t,r,n){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",n=n||this.backend;var o=e;"string"===r&&J(e[0])&&(o=e.map((function(e){return ue(e)})));var a=n.write(o,t,r),i=new Re(t,r,a,this.nextTensorId());if(this.incRef(i,n),"string"===r){var s=this.state.tensorInfo.get(a),l=Y(o);this.state.numBytes+=l-s.bytes,s.bytes=l}return i},e.prototype.makeTensorFromDataId=function(e,t,r,n){var o=new Re(t,r=r||"float32",e,this.nextTensorId());return this.incRef(o,n),o},e.prototype.makeVariable=function(e,t,r,n){void 0===t&&(t=!0),r=r||this.nextVariableId().toString(),null!=n&&n!==e.dtype&&(e=e.asType(n));var o=new Ce(e,t,r,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},e.prototype.incRef=function(e,t){var r=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++,0===r){this.state.numDataBuffers++;var n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*Q(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n,refCount:0}),this.state.numBytes+=n}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Ce||this.track(e)},e.prototype.disposeTensor=function(e){if(this.state.tensorInfo.has(e.dataId)){this.state.numTensors--,"string"===e.dtype&&this.state.numStringTensors--;var t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?("complex64"!==e.dtype&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}},e.prototype.disposeVariables=function(){for(var e in this.state.registeredVariables){var t=this.state.registeredVariables[e];this.disposeVariable(t)}},e.prototype.disposeVariable=function(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},e.prototype.profile=function(e){return p(this,void 0,void 0,(function(){var t,r;return d(this,(function(n){return this.state.profiling=!0,t=this.state.numBytes,r=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(e){return e.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r,[2,this.state.activeProfile]}))}))},e.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},e.prototype.addTapeNode=function(e,t,r,n,o){var a=this,i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:o},s=v(e);null!=s&&(n=s.gradFunc),null!=n&&(i.gradient=function(e){return e=e.map((function(e,t){if(null==e){var n=r[t],o=se(n.size,n.dtype);return a.makeTensor(o,n.shape,n.dtype)}return e})),n(e.length>1?e:e[0],o)}),this.state.activeTape.push(i)},e.prototype.keep=function(e){return e.kept=!0,e},e.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},e.prototype.endTape=function(){this.state.gradientDepth--},e.prototype.startScope=function(e){var t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t},e.prototype.endScope=function(e){for(var t=this,r=Pe(e),n=new Set(r.map((function(e){return e.id}))),o=0;o0,(function(){return"gradients() received an empty list of xs."})),null!=r&&"float32"!==r.dtype)throw new Error("dy must have 'float32' dtype, but has '"+r.dtype+"'");var a=this.scopedRun((function(){return o.startTape()}),(function(){return o.endTape()}),(function(){return o.tidy("forward",e)}));T(a instanceof Re,(function(){return"The result y returned by f() must be a tensor."}));var i=function(e,t,r){for(var n={},o={},a=0;a=0;a--)for(i=(f=e[a]).inputs,p=0;p0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(function(){var e,n,s={};s[a.id]=null==r?(n=ie(B(e=a.shape),"float32"),je.makeTensor(n,e,"float32")):r,function(e,t,r){for(var n=function(n){var o=t[n],a=[];if(o.outputs.forEach((function(t){var r=e[t.id];null!=r?a.push(r):a.push(null)})),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");var i=o.gradient(a),s=function(t){if(!(t in i))throw new Error("Cannot backprop through input "+t+". Available gradients found: "+Object.keys(i)+".");var n=r((function(){return i[t]()}));if("float32"!==n.dtype)throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input "+t+" must have 'float32' dtype, but has '"+n.dtype+"'");var a=o.inputs[t];if(!I(n.shape,a.shape))throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input '"+t+"' has shape '"+n.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==e[a.id])e[a.id]=n;else{var s=e[a.id];e[a.id]=s.add(n),s.dispose()}};for(var l in o.inputs)s(l)},o=t.length-1;o>=0;o--)n(o)}(s,i,(function(e){return o.tidy(e)}));var l=t.map((function(e){return s[e.id]}));return 0===o.state.gradientDepth&&(o.state.activeTape.forEach((function(e){for(var t=0,r=e.saved;tr||t>r)throw n="["+e+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function gt(e,t){return Dt(e,t,(function(){return e.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function bt(e,t,r,n,o,a,i,s){var l=e.getAttribLocation(r,n);return-1!==l&&(rt(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,o)})),rt(e,t,(function(){return e.vertexAttribPointer(l,a,e.FLOAT,!1,i,s)})),rt(e,t,(function(){return e.enableVertexAttribArray(l)})),!0)}function vt(e,t,r,n){Tt(e,n),rt(e,t,(function(){return e.activeTexture(e.TEXTURE0+n)})),rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,r)}))}function Et(e,t,r,n){return Dt(e,t,(function(){return e.getUniformLocation(r,n)}),'uniform "'+n+'" not present in program.')}function kt(e,t,r){return e.getUniformLocation(t,r)}function St(e,t,r,n,o,a){rt(e,t,(function(){return vt(e,t,n,a)})),rt(e,t,(function(){return e.uniform1i(o,a)}))}function Rt(e,t,r,n){rt(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)})),rt(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0)}))}function wt(e,t,r){rt(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)})),rt(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)}))}function At(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+xt(e,t))}function xt(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Dt(e,t,r,n){var o=rt(e,t,(function(){return r()}));if(null==o)throw new Error(n);return o}function Tt(e,t){var r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(nr)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+r+"].")}function Ot(e,t){return void 0===t&&(t=2),B(e.slice(0,e.length-t))}function Ct(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Lt(e){var t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Ot(e)].concat(Ct(e))),t}function Bt(e,t){var r;void 0===t&&(t=!1);var n=f().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,1===(e=e.map((function(t,r){return r>=e.length-2?x(e[r]):e[r]}))).length&&(e=[2,e[0]])),2!==e.length){var o=j(e);e=o.newShape}var a=B(e);if(e.length<=1&&a<=n)return[1,a];if(2===e.length&&e[0]<=n&&e[1]<=n)return e;if(3===e.length&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){var i=Ot(e),s=2,l=2;return e.length&&(s=(r=Ct(e))[0],l=r[1]),P(a=i*(s/2)*(l/2)).map((function(e){return 2*e}))}return P(a)}function It(e){return e%2==0}function Nt(e,t){if(I(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){var r=e.slice(-1)[0],n=t.slice(-1)[0];if(r===n)return!0;if(It(r)&&It(n)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&It(e[0])&&It(t[0])}function Mt(e){if(null==lt){var t=Je(e);lt=t.getParameter(t.MAX_TEXTURE_SIZE)}return lt}function Pt(e){if(null==ct){var t=Je(e);ct=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ct)}function Ft(e){if(0===e)return 0;var t=Je(e);return Wt(t,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Wt(t,"EXT_disjoint_timer_query")?1:0}function Wt(e,t){return null!=e.getExtension(t)}function Ht(e){try{if(null!=Je(e))return!0}catch(e){return!1}return!1}function zt(e){if(0===e)return!1;var t=Je(e);if(1===e){if(!Wt(t,"OES_texture_float"))return!1}else if(!Wt(t,"EXT_color_buffer_float"))return!1;return Vt(t)}function jt(e){if(0===e)return!1;var t=Je(e);if(1!==e){if(Wt(t,"EXT_color_buffer_float"))return Vt(t);if(Wt(t,"EXT_color_buffer_half_float")){var r=t.getExtension("EXT_color_buffer_half_float");return function(e,t){var r=tt(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,r.internalFormatHalfFloat,1,1,0,r.textureFormatFloat,r.textureTypeHalfFloat,null);var o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);var a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(o),a}(t,r)}return!1}return!!Wt(t,"OES_texture_float")&&!!Wt(t,"WEBGL_color_buffer_float")&&Vt(t)}function Vt(e){var t=tt(e),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var n=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);var o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(n),o}function Ut(e){return 2===e&&null!=Je(e).fenceSync}var Gt=Object.freeze({callAndCheck:rt,canBeRepresented:nt,getWebGLErrorMessage:ot,getExtensionOrThrow:at,createVertexShader:it,createFragmentShader:st,createProgram:pt,linkProgram:dt,validateProgram:_t,createStaticVertexBuffer:ht,createStaticIndexBuffer:ft,getNumChannels:function(){return 2===f().getNumber("WEBGL_VERSION")?1:4},createTexture:yt,validateTextureSize:mt,createFramebuffer:gt,bindVertexBufferToProgramAttribute:bt,bindTextureUnit:vt,unbindTextureUnit:function(e,t,r){Tt(e,r),rt(e,t,(function(){return e.activeTexture(e.TEXTURE0+r)})),rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:Et,getProgramUniformLocation:kt,bindTextureToProgramUniformSampler:St,bindCanvasToFramebuffer:function(e,t){rt(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),rt(e,t,(function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)})),rt(e,t,(function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)}))},bindColorTextureToFramebuffer:Rt,unbindColorTextureFromFramebuffer:wt,validateFramebuffer:At,getFramebufferErrorMessage:xt,getBatchDim:Ot,getRowsCols:Ct,getShapeAs3D:Lt,getTextureShapeFromLogicalShape:Bt,isReshapeFree:Nt,getWebGLMaxTextureSize:Mt,resetMaxTextureSize:function(){lt=null},resetMaxTexturesInShader:function(){ct=null},getMaxTexturesInShader:Pt,getWebGLDisjointQueryTimerVersion:Ft,hasExtension:Wt,isWebGLVersionEnabled:Ht,isCapableOfRenderingToFloatTexture:zt,isDownloadFloatTextureEnabled:jt,isWebGLFenceEnabled:Ut}),Kt=f();function qt(e){f().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Xt(e,t){return je.tidy(e,t)}function Qt(e){Pe(e).forEach((function(e){return e.dispose()}))}function Yt(e){return je.keep(e)}function Jt(){for(var e=[],t=0;t0,(function(){return"Element arr["+n.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"})),T(t.length===r[0],(function(){return"Element arr["+n.join("][")+"] should have "+r[0]+" elements, but has "+t.length+" elements"}));for(var o=r.slice(1),a=0;a=0&&(o=n),$t(n,o,t,r),null==e||!X(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){var a=null==e?"null":e.constructor.name;throw new Error("Argument '"+t+"' passed to '"+r+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=Zt(e,o);X(e)||Array.isArray(e)||(e=[e]);var s="string"!==o?oe(e,o,f().getBool("DEBUG")):L(e,[],!0);return je.makeTensor(s,i,o)}function tr(e,t,r,n){if(void 0===n&&(n="numeric"),!Array.isArray(e))throw new Error("Argument "+t+" passed to "+r+" must be a `Tensor[]` or `TensorLike[]`");return e.map((function(e,n){return er(e,t+"["+n+"]",r)}),n)}function rr(e,t){for(var r=0;r=0&&t0})),Kt.registerFlag("WEBGL_VERSION",(function(){return Ht(2)?2:Ht(1)?1:0})),Kt.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Kt.get("WEBGL_VERSION")})),Kt.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Kt.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Kt.registerFlag("WEBGL_PACK",(function(){return Kt.getBool("HAS_WEBGL")})),Kt.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_CLIP",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Kt.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_PACK_REDUCE",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_CONV_IM2COL",(function(){return Kt.getBool("WEBGL_PACK")})),Kt.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Mt(Kt.getNumber("WEBGL_VERSION"))})),Kt.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return Pt(Kt.getNumber("WEBGL_VERSION"))})),Kt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var e=Kt.getNumber("WEBGL_VERSION");return 0===e?0:Ft(e)})),Kt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Kt.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e})),Kt.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return zt(Kt.getNumber("WEBGL_VERSION"))})),Kt.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Kt.getBool("WEBGL_FORCE_F16_TEXTURES")&&Kt.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Kt.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return jt(Kt.getNumber("WEBGL_VERSION"))})),Kt.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return Ut(Kt.getNumber("WEBGL_VERSION"))})),Kt.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Kt.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),Se=qt;var _r=dr({complex_:function(e,t){var r=er(e,"real","complex"),n=er(t,"imag","complex");return O(r.shape,n.shape,"real and imag shapes, "+r.shape+" and "+n.shape+", must match in call to tf.complex()."),je.runKernelFunc((function(e){return e.complex(r,n)}),{$real:r,$imag:n})}}),hr=dr({real_:function(e){var t=er(e,"input","real");return je.runKernelFunc((function(e){return e.real(t)}),{$input:t})}}),fr=dr({imag_:function(e){var t=er(e,"input","imag");return je.runKernelFunc((function(e){return e.imag(t)}),{$input:t})}});function yr(e,t,r){return mr(e,t,Zt(e,r),r)}function mr(e,t,r,n){if(null==n&&(n=ee(e)),"complex64"===n)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!X(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){ce(t);var o=B(t),a=B(r);T(o===a,(function(){return"Based on the provided shape, ["+t+"], the tensor should have "+o+" values but has "+a}));for(var i=0;i1)return xr([0],n);var o=se(Math.abs(Math.ceil((t-e)/r)),n);t=1,(function(){return"Pass at least one tensor to concat"}));var r=tr(e,"tensors","concat");"complex64"===r[0].dtype&&r.forEach((function(e){if("complex64"!==e.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+e.dtype+". ")})),t=z(t,r[0].shape)[0];var n=pr(r.map((function(e){return e.shape})),t);if(0===B(n))return yr([],n);if(1===(r=r.filter((function(e){return e.size>0}))).length)return r[0];var o=r.map((function(e){return e.shape}));ur(o,t);var a=r,i={axis:t};return je.runKernelFunc((function(e){return e.concat(r,t)}),a,(function(e){var r=o.map((function(e){return e[t]}));return Fr(e,r,t).map((function(e){return function(){return e}}))}),"Concat",i)}}),Ir=dr({concat1d_:function(e){return Br(e,0)}}),Nr=dr({concat2d_:function(e,t){return Br(e,t)}}),Mr=dr({concat3d_:function(e,t){return Br(e,t)}}),Pr=dr({concat4d_:function(e,t){return Br(e,t)}}),Fr=dr({split_:function(e,t,r){void 0===r&&(r=0);var n,o=er(e,"x","split");return r=z(r,o.shape)[0],"number"==typeof t?(T(o.shape[r]%t==0,(function(){return"Number of splits must evenly divide the axis."})),n=new Array(t).fill(o.shape[r]/t)):(T(o.shape[r]===t.reduce((function(e,t){return e+t})),(function(){return"The sum of sizes must match the size of the axis dimension."})),n=t),je.runKernelFunc((function(e){return e.split(o,n,r)}),{$x:o},(function(e){return{$x:function(){return Br(e,r)}}}))}});function Wr(e,t){return e(t={exports:{}},t.exports),t.exports}t.split=Fr,t.concat4d=Pr,t.concat3d=Mr,t.concat2d=Nr,t.concat1d=Ir,t.concat=Br,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e||"undefined"!=typeof self&&self;var Hr=Wr((function(e){!function(e,t,r){function n(e){var t,r=this,n=(t=4022871197,function(e){e=e.toString();for(var r=0;r>>0,t=(n*=t)>>>0,t+=4294967296*(n-=t)}return 2.3283064365386963e-10*(t>>>0)});r.next=function(){var e=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=e-(r.c=0|e)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(e),r.s0<0&&(r.s0+=1),r.s1-=n(e),r.s1<0&&(r.s1+=1),r.s2-=n(e),r.s2<0&&(r.s2+=1),n=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var r=new n(e),a=t&&t.state,i=r.next;return i.int32=function(){return 4294967296*r.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,a&&("object"==(0,s.default)(a)&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.alea=a}(0,e)})),zr=Wr((function(e){!function(e,t,r){function n(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var n=0;n>>0)/4294967296};return i.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=r.next,i.quick=i,a&&("object"==(0,s.default)(a)&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.xor128=a}(0,e)})),jr=Wr((function(e){!function(e,t,r){function n(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:r+=e;for(var n=0;n>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var r=new n(e),a=t&&t.state,i=function(){return(r.next()>>>0)/4294967296};return i.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=r.next,i.quick=i,a&&("object"==(0,s.default)(a)&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)})),Vr=Wr((function(e){!function(e,t,r){function n(e){var t=this;t.next=function(){var e,r,n=t.x,o=t.i;return e=n[o],r=(e^=e>>>7)^e<<24,r^=(e=n[o+1&7])^e>>>10,r^=(e=n[o+3&7])^e>>>3,r^=(e=n[o+4&7])^e<<7,e=n[o+7&7],r^=(e^=e<<13)^e<<9,n[o]=r,t.i=o+1&7,r},function(e,t){var r,n=[];if(t===(0|t))n[0]=t;else for(t=""+t,r=0;r0;--r)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var r=new n(e),a=t&&t.state,i=function(){return(r.next()>>>0)/4294967296};return i.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=r.next,i.quick=i,a&&(a.x&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)})),Ur=Wr((function(e){!function(e,t,r){function n(e){var t=this;t.next=function(){var e,r,n=t.w,o=t.X,a=t.i;return t.w=n=n+1640531527|0,r=o[a+34&127],e=o[a=a+1&127],r^=r<<13,e^=e<<17,r^=r>>>15,e^=e>>>12,r=o[a]=r^e,t.i=a,r+(n^n>>>16)|0},function(e,t){var r,n,o,a,i,s=[],l=128;for(t===(0|t)?(n=t,t=null):(t+="\0",n=0,l=Math.max(l,t.length)),o=0,a=-32;a>>15,n^=n<<4,n^=n>>>13,a>=0&&(i=i+1640531527|0,o=0==(r=s[127&a]^=n+i)?o+1:0);for(o>=128&&(s[127&(t&&t.length||0)]=-1),o=127,a=512;a>0;--a)n=s[o+34&127],r=s[o=o+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[o]=n^r;e.w=i,e.X=s,e.i=o}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var r=new n(e),a=t&&t.state,i=function(){return(r.next()>>>0)/4294967296};return i.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=r.next,i.quick=i,a&&(a.X&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)})),Gr=Wr((function(e){!function(e,t,r){function n(e){var t=this,r="";t.next=function(){var e=t.b,r=t.c,n=t.d,o=t.a;return e=e<<25^e>>>7^r,r=r-n|0,n=n<<24^n>>>8^o,o=o-e|0,t.b=e=e<<20^e>>>12^r,t.c=r=r-n|0,t.d=n<<16^r>>>16^o,t.a=o-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):r+=e;for(var n=0;n>>0)/4294967296};return i.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=r.next,i.quick=i,a&&("object"==(0,s.default)(a)&&o(a,r),i.state=function(){return o(r,{})}),i}t&&t.exports?t.exports=a:this.tychei=a}(0,e)})),Kr=Wr((function(e){!function(t,n){var o,a=this,i=256,l="random",c=n.pow(i,6),u=n.pow(2,52),p=2*u,d=255;function _(e,r,d){var _=[],g=y(function e(t,r){var n,o=[],a=(0,s.default)(t);if(r&&"object"==a)for(n in t)try{o.push(e(t[n],r-1))}catch(e){}return o.length?o:"string"==a?t:t+"\0"}((r=1==r?{entropy:!0}:r||{}).entropy?[e,m(t)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(i):(e=new Uint8Array(i),(a.crypto||a.msCrypto).getRandomValues(e)),m(e)}catch(e){var r=a.navigator,n=r&&r.plugins;return[+new Date,a,n,a.screen,m(t)]}}():e,3),_),b=new h(_),v=function(){for(var e=b.g(6),t=c,r=0;e=p;)e/=2,t/=2,r>>>=1;return(e+r)/t};return v.int32=function(){return 0|b.g(4)},v.quick=function(){return b.g(4)/4294967296},v.double=v,y(m(b.S),t),(r.pass||d||function(e,t,r,o){return o&&(o.S&&f(o,b),e.state=function(){return f(b,{})}),r?(n[l]=e,t):e})(v,g,"global"in r?r.global:this==n,r.state)}function h(e){var t,r=e.length,n=this,o=0,a=n.i=n.j=0,s=n.S=[];for(r||(e=[r++]);o=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*o*s,r=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(t)||(n=!0)}return this.truncated&&!this.isValidTruncated(r)||(this.nextVal=this.convertValue(r)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),Qr=function(){function e(e,t,r,n){this.alpha=e,this.beta=1/t,this.dtype=r;var o=n||Math.random();this.randu=qr(o.toString()),this.randn=new Xr(0,1,r,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}return e.prototype.nextValue=function(){for(var e,t,r,n,o,a;;){do{n=this.randn.nextValue(),a=1+this.c*n}while(a<=0);if(a*=a*a,t=1-.331*(e=n*n)*e,r=.5*e+this.d*(1-a+Math.log(a)),(o=this.randu())=1+t.length,(function(){return"input rank is "+n.rank+" but should be > than blockShape.length "+t.length})),T(r.length===t.length,(function(){return"crops.length is "+r.length+" but should be equal to blockShape.length "+t.length})),T(n.shape[0]%o==0,(function(){return"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockShape "+t.join(" * ")+" === "+o})),je.runKernelFunc((function(e){return e.batchToSpaceND(n,t,r)}),{$x:n},(function(e){return{$x:function(){return e.spaceToBatchND(t,r)}}}))}}),en=dr({broadcastTo_:function(e,t){var r=er(e,"broadcastTo","x"),n=r.shape;if(t.some((function(e){return!(e>0)||e%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.lengthr.rank){for(var o=r.shape.slice();o.length=0;i--)if(r.shape[i]===t[i])a[i]=1;else if(1!==r.shape[i])throw new Error("broadcastTo(): ["+n+"] cannot be broadcast to ["+t+"].");var s=a.map((function(e,t){return e>1?t:-1})).filter((function(e){return e>=0}));return 0===s.length?r.clone():je.runKernelFunc((function(e){return e.tile(r,a)}),{input:r},(function(e){return{input:function(){return e.sum(s,!0)}}}))}}),tn=dr({cast_:function(e,t){var r=er(e,"x","cast");if(!K(t))throw new Error("Failed to cast to unknown dtype "+t);if("string"===t&&"string"!==r.dtype||"string"!==t&&"string"===r.dtype)throw new Error("Only strings can be casted to strings");var n={dtype:t};return je.runKernelFunc((function(e){return e.cast(r,t)}),{x:r},(function(e){return{x:function(){return e.clone()}}}),"Cast",n)}}),rn=dr({clone_:function(e){var t=er(e,"x","clone",null);return je.runKernelFunc((function(){return je.makeTensorFromDataId(t.dataId,t.shape,t.dtype)}),{$x:t},(function(e){return{$x:function(){return e.toFloat()}}}))}}),nn=dr({cumsum_:function(e,t,r,n){void 0===t&&(t=0),void 0===r&&(r=!1),void 0===n&&(n=!1);var o=er(e,"x","cumsum"),a=sr([t|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=cr(1,o.rank)[0],l=je.runKernelFunc((function(e){return e.cumsum(i,s,r,n)}),{permutedX:i},(function(e){return{permutedX:function(){return e.cumsum(t,r,!n)}}}));return null!=a&&(l=l.transpose(a)),l}}),on=dr({depthToSpace_:function(e,t,r){void 0===r&&(r="NHWC");var n=er(e,"x","depthToSpace"),o="NHWC"===r?n.shape[1]:n.shape[2],a="NHWC"===r?n.shape[2]:n.shape[3],i="NHWC"===r?n.shape[3]:n.shape[1];return T(o*t>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+t+" for depthToSpace with input shape\n "+n.shape})),T(a*t>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+n.shape})),T(i%(t*t)==0,(function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+i+" for depthToSpace with input shape "+n.shape})),je.runKernelFunc((function(e){return e.depthToSpace(n,t,r)}),{$x:n})}}),an=dr({expandDims_:function(e,t){void 0===t&&(t=0);var r=er(e,"x","expandDims",null);T(t<=r.rank,(function(){return"Axis must be <= rank of the tensor"}));var n=r.shape.slice();return t<0&&(T(-(r.rank+1)<=t,(function(){return"Axis must be in the interval ["+-(r.rank+1)+", "+r.rank+"]"})),t=r.rank+t+1),n.splice(t,0,1),bn(r,n)}}),sn=dr({eye_:function(e,t,r,n){void 0===n&&(n="float32"),null==t&&(t=e);for(var o=Jr([e,t],n),a=e<=t?e:t,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);r=r||Math.random();var s=1===i?o.as2D(1,-1):o,l=je.runKernelFunc((function(e){return e.multinomial(s,n,t,r)}),{logits2D:s});return 1===i?l.as1D():l}}),cn=dr({oneHot_:function(e,t,r,n){if(void 0===r&&(r=1),void 0===n&&(n=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var o=er(e,"indices","oneHot","int32"),a=o.shape.concat([t]);return o=o.flatten(),je.runKernelFunc((function(e){return e.oneHot(o,t,r,n)}),{$indices:o},(function(e){return{$indices:function(){return xr(o.shape,"float32")}}})).reshape(a)}}),un=dr({pad_:function(e,t,r){void 0===r&&(r=0);var n=er(e,"x","pad");if(0===n.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:t,constantValue:r};return je.runKernelFunc((function(e){return e.pad(n,t,r)}),{x:n},(function(e){var r=t.map((function(e){return e[0]}));return{x:function(){return e.slice(r,n.shape)}}}),"PadV2",o)}}),pn=dr({pad1d_:function(e,t,r){return void 0===r&&(r=0),T(2===t.length,(function(){return"Invalid number of paddings. Must be length of 2."})),un(e,[t],r)}}),dn=dr({pad2d_:function(e,t,r){return void 0===r&&(r=0),T(2===t.length&&2===t[0].length&&2===t[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),un(e,t,r)}}),_n=dr({pad3d_:function(e,t,r){return void 0===r&&(r=0),T(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),un(e,t,r)}}),hn=dr({pad4d_:function(e,t,r){return void 0===r&&(r=0),T(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),un(e,t,r)}}),fn=dr({rand_:function(e,t,r){var n=B(e),o=null;if(null==r||"float32"===r)o=new Float32Array(n);else if("int32"===r)o=new Int32Array(n);else{if("bool"!==r)throw new Error("Unknown data type "+r);o=new Uint8Array(n)}for(var a=0;a=1+t.length,(function(){return"input rank "+n.rank+" should be > than [blockShape] "+t.length})),T(r.length===t.length,(function(){return"paddings.shape[0] "+r.length+" must be equal to [blockShape] "+t.length})),T(n.shape.reduce((function(e,n,o){return o>0&&o<=t.length?e&&(n+r[o-1][0]+r[o-1][1])%t[o-1]==0:e}),!0),(function(){return"input spatial dimensions "+n.shape.slice(1)+" with paddings "+r.toString()+" must be divisible by blockShapes "+t.toString()})),je.runKernelFunc((function(e){return e.spaceToBatchND(n,t,r)}),{$x:n},(function(e){return{$x:function(){return e.batchToSpaceND(t,r)}}}))}}),En=dr({squeeze_:function(e,t){var r=er(e,"x","squeeze");return bn(r,j(r.shape,t).newShape)}}),kn=dr({stack_:function(e,t){void 0===t&&(t=0);var r=tr(e,"tensors","stack");if(T(r.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),1===r.length)return r[0].expandDims(t);var n=r[0].rank,o=r[0].shape,a=r[0].dtype;T(t<=n,(function(){return"Axis must be <= rank of the tensor"})),r.forEach((function(e){O(o,e.shape,"All tensors passed to stack must have matching shapes")})),r.forEach((function(e){T(a===e.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var i=r.map((function(e){return e.expandDims(t)}));return Br(i,t)}}),Sn=dr({tile_:function(e,t){var r=er(e,"x","tile",null);T(r.rank===t.length,(function(){return"Error in transpose: rank of input "+r.rank+" must match length of reps "+t+"."}));var n=[r],o={reps:t};return je.runKernelFunc((function(e,n){var o=e.tile(r,t);return n([r]),o}),{x:r},(function(e,r){var n=r[0];return{x:function(){var r=Lr(n);if(1===n.rank)for(var o=0;o=-r.shape.length&&t=2*t+1||o%2==1?i.push(o):a.push(o);n.push.apply(n,a),n.push(0),n.push.apply(n,i)}return n}function Tn(e,t,r,n){void 0===n&&(n=!0);var o=[];n?o.push(e[0]/r):o.push(e[0]*r);for(var a=1;ae.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+e.rank);if(0===e.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+e.shape+".");for(var r=t.shape,n=r[r.length-1],o=1,a=0;a1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+r.shape+", indices.shape: "+t.shape+", shape: "+e+", sliceDim: "+n+", and batchDim: "+o+".";if(r.rank1?t.shape[n-1]:1,a=r.length,i=1,s=o;s0;)1&e&&t.push(r),e/=2,r++;return t}function zn(e,t,r){for(var n=[],o=0;o0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),A(0,a,s-1)}function Vn(e,t,r,n,o){var a=t[o],i=r[o]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),i>0?A(0,a,s):A(-1,a,s-1)}function Un(e,t,r){for(var n=r.length,o=0;o1){n=o;break}for(o=n+1;o0||r[o]!==e[o])return!1;return!0}function Gn(e,t){for(var r=e.length>0?e[e.length-1]:1,n=0;n0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."}));var i=je.gradients(e,t,null,!0),s=i.value,l=i.grads;T(l.some((function(e){return null!=e})),(function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."})),T(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var c={};return t.forEach((function(e,t){null!=l[t]&&(c[e.name]=l[t])})),null!=o&&o.forEach((function(e){return c[e.name]=null})),{value:s,grads:c}}function Xn(e){return je.customGrad(e)}function Qn(e){if(e.filter((function(e){return null==e})).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}t.slice_util=Kn;var Yn=dr({softmax_:function(e,t){void 0===t&&(t=-1);var r=er(e,"logits","softmax","float32");if(-1===t&&(t=r.rank-1),t!==r.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+r.rank+" and dim was "+t);return je.runKernelFunc((function(e,n){var o=e.softmax(r,t);return n([o]),o}),{logits:r},(function(e,r){var n=r[0],o=e.mul(n);return{logits:function(){return o.sub(o.sum([t],!0).mul(n))}}}),"Softmax",{dim:t},[],[!0])}}),Jn=dr({logSoftmax_:function(e,t){void 0===t&&(t=-1);var r=er(e,"logits","logSoftmax");if(-1===t&&(t=r.rank-1),t!==r.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+r.rank+" and axis was "+t);return Xn((function(e,r){var n=e.max(t,!0),o=e.sub(n),a=o.toFloat().sub(o.exp().sum(t,!0).log());return r([a]),{value:a,gradFunc:function(e,r){var n=r[0].exp();return e.sub(e.sum(t,!0).mul(n))}}}))(r)}}),Zn=function(){function e(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}return e.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},e.prototype.set=function(e,t){this.dataIdsCount++,this.data.set(e,t)},e.prototype.has=function(e){return this.data.has(e)},e.prototype.delete=function(e){return this.dataIdsCount--,this.data.delete(e)},e.prototype.numDataIds=function(){return this.dataIdsCount},e}(),$n=function(){function e(){}return e.prototype.time=function(e){return eo("time")},e.prototype.read=function(e){return eo("read")},e.prototype.readSync=function(e){return eo("readSync")},e.prototype.numDataIds=function(){return eo("numDataIds")},e.prototype.disposeData=function(e){return eo("disposeData")},e.prototype.write=function(e,t,r){return eo("write")},e.prototype.move=function(e,t,r,n){return eo("move")},e.prototype.memory=function(){return eo("memory")},e.prototype.floatPrecision=function(){return eo("floatPrecision")},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.batchMatMul=function(e,t,r,n){return eo("batchMatMul")},e.prototype.fusedBatchMatMul=function(e){return e.a,e.b,e.transposeA,e.transposeB,e.bias,e.activation,e.preluActivationWeights,eo("fusedBatchMatMul")},e.prototype.slice=function(e,t,r){return eo("slice")},e.prototype.stridedSlice=function(e,t,r,n){return eo("stridedSlice")},e.prototype.unstack=function(e,t){return eo("unstack")},e.prototype.reverse=function(e,t){return eo("reverse")},e.prototype.concat=function(e,t){return eo("concat")},e.prototype.neg=function(e){return eo("neg")},e.prototype.add=function(e,t){return eo("add")},e.prototype.addN=function(e){return eo("addN")},e.prototype.subtract=function(e,t){return eo("subtract")},e.prototype.multiply=function(e,t){return eo("multiply")},e.prototype.realDivide=function(e,t){return eo("realDivide")},e.prototype.floorDiv=function(e,t){return eo("floorDiv")},e.prototype.sum=function(e,t){return eo("sum")},e.prototype.prod=function(e,t){return eo("prod")},e.prototype.unsortedSegmentSum=function(e,t,r){return eo("unsortedSegmentSum")},e.prototype.argMin=function(e,t){return eo("argMin")},e.prototype.argMax=function(e,t){return eo("argMax")},e.prototype.equal=function(e,t){return eo("equal")},e.prototype.notEqual=function(e,t){return eo("notEqual")},e.prototype.less=function(e,t){return eo("less")},e.prototype.lessEqual=function(e,t){return eo("lessEqual")},e.prototype.greater=function(e,t){return eo("greater")},e.prototype.greaterEqual=function(e,t){return eo("greaterEqual")},e.prototype.logicalNot=function(e){return eo("logicalNot")},e.prototype.logicalAnd=function(e,t){return eo("logicalAnd")},e.prototype.logicalOr=function(e,t){return eo("logicalOr")},e.prototype.where=function(e){return eo("where")},e.prototype.select=function(e,t,r){return eo("select")},e.prototype.topk=function(e,t,r){return eo("topk")},e.prototype.min=function(e,t){return eo("min")},e.prototype.minimum=function(e,t){return eo("minimum")},e.prototype.mod=function(e,t){return eo("mod")},e.prototype.max=function(e,t){return eo("max")},e.prototype.maximum=function(e,t){return eo("maximum")},e.prototype.all=function(e,t){return eo("all")},e.prototype.any=function(e,t){return eo("any")},e.prototype.squaredDifference=function(e,t){return eo("squaredDifference")},e.prototype.ceil=function(e){return eo("ceil")},e.prototype.floor=function(e){return eo("floor")},e.prototype.round=function(e){return eo("round")},e.prototype.sign=function(e){return eo("sign")},e.prototype.isNaN=function(e){return eo("isNaN")},e.prototype.isInf=function(e){return eo("isInf")},e.prototype.isFinite=function(e){return eo("isFinite")},e.prototype.pow=function(e,t){return eo("pow")},e.prototype.exp=function(e){return eo("exp")},e.prototype.expm1=function(e){return eo("expm1")},e.prototype.softmax=function(e,t){return eo("softmax")},e.prototype.log=function(e){return eo("log")},e.prototype.log1p=function(e){return eo("log1p")},e.prototype.sqrt=function(e){return eo("sqrt")},e.prototype.rsqrt=function(e){return eo("rsqrt")},e.prototype.square=function(e){return eo("square")},e.prototype.reciprocal=function(e){return eo("reciprocal")},e.prototype.relu=function(e){return eo("relu")},e.prototype.relu6=function(e){return eo("relu6")},e.prototype.prelu=function(e,t){return eo("prelu")},e.prototype.elu=function(e){return eo("elu")},e.prototype.eluDer=function(e,t){return eo("eluDer")},e.prototype.selu=function(e){return eo("selu")},e.prototype.int=function(e){return eo("int")},e.prototype.clip=function(e,t,r){return eo("clip")},e.prototype.abs=function(e){return eo("abs")},e.prototype.complexAbs=function(e){return eo("complexAbs")},e.prototype.sigmoid=function(e){return eo("sigmoid")},e.prototype.softplus=function(e){return eo("softplus")},e.prototype.sin=function(e){return eo("sin")},e.prototype.cos=function(e){return eo("cos")},e.prototype.tan=function(e){return eo("tan")},e.prototype.asin=function(e){return eo("asin")},e.prototype.acos=function(e){return eo("acos")},e.prototype.atan=function(e){return eo("atan")},e.prototype.atan2=function(e,t){return eo("atan2")},e.prototype.sinh=function(e){return eo("sinh")},e.prototype.cosh=function(e){return eo("cosh")},e.prototype.tanh=function(e){return eo("tanh")},e.prototype.asinh=function(e){return eo("asinh")},e.prototype.acosh=function(e){return eo("acosh")},e.prototype.atanh=function(e){return eo("atanh")},e.prototype.erf=function(e){return eo("erf")},e.prototype.step=function(e,t){return eo("step")},e.prototype.fusedConv2d=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,eo("fusedConv2d")},e.prototype.conv2d=function(e,t,r){return eo("conv2d")},e.prototype.conv2dDerInput=function(e,t,r){return eo("conv2dDerInput")},e.prototype.conv2dDerFilter=function(e,t,r){return eo("conv2dDerFilter")},e.prototype.fusedDepthwiseConv2D=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,eo("fusedDepthwiseConv2D")},e.prototype.depthwiseConv2D=function(e,t,r){return eo("depthwiseConv2D")},e.prototype.depthwiseConv2DDerInput=function(e,t,r){return eo("depthwiseConv2DDerInput")},e.prototype.depthwiseConv2DDerFilter=function(e,t,r){return eo("depthwiseConv2DDerFilter")},e.prototype.conv3d=function(e,t,r){return eo("conv3d")},e.prototype.conv3dDerInput=function(e,t,r){return eo("conv3dDerInput")},e.prototype.conv3dDerFilter=function(e,t,r){return eo("conv3dDerFilter")},e.prototype.maxPool=function(e,t){return eo("maxPool")},e.prototype.maxPoolBackprop=function(e,t,r,n){return eo("maxPoolBackprop")},e.prototype.avgPool=function(e,t){return eo("avgPool")},e.prototype.avgPoolBackprop=function(e,t,r){return eo("avgPoolBackprop")},e.prototype.avgPool3d=function(e,t){return eo("avgPool3d")},e.prototype.avgPool3dBackprop=function(e,t,r){return eo("avgPool3dBackprop")},e.prototype.maxPool3d=function(e,t){return eo("maxPool3d")},e.prototype.maxPool3dBackprop=function(e,t,r,n){return eo("maxPool3dBackprop")},e.prototype.reshape=function(e,t){return eo("reshape")},e.prototype.cast=function(e,t){return eo("cast")},e.prototype.tile=function(e,t){return eo("tile")},e.prototype.pad=function(e,t,r){return eo("pad")},e.prototype.transpose=function(e,t){return eo("transpose")},e.prototype.gather=function(e,t,r){return eo("gather")},e.prototype.gatherND=function(e,t){return eo("gatherND")},e.prototype.scatterND=function(e,t,r){return eo("scatterND")},e.prototype.batchToSpaceND=function(e,t,r){return eo("batchToSpaceND")},e.prototype.spaceToBatchND=function(e,t,r){return eo("spaceToBatchND")},e.prototype.resizeBilinear=function(e,t,r,n){return eo("resizeBilinear")},e.prototype.resizeBilinearBackprop=function(e,t,r){return eo("resizeBilinearBackprop")},e.prototype.resizeNearestNeighbor=function(e,t,r,n){return eo("resizeNearestNeighbor")},e.prototype.resizeNearestNeighborBackprop=function(e,t,r){return eo("resizeNearestNeighborBackprop")},e.prototype.batchNormalization=function(e,t,r,n,o,a){return eo("batchNormalization")},e.prototype.localResponseNormalization4D=function(e,t,r,n,o){return eo("localResponseNormalization4D")},e.prototype.LRNGrad=function(e,t,r,n,o,a,i){return eo("LRNGrad")},e.prototype.multinomial=function(e,t,r,n){return eo("multinomial")},e.prototype.oneHot=function(e,t,r,n){return eo("oneHot")},e.prototype.cumsum=function(e,t,r,n){return eo("cumsum")},e.prototype.nonMaxSuppression=function(e,t,r,n,o){return eo("nonMaxSuppression")},e.prototype.fft=function(e){return eo("fft")},e.prototype.ifft=function(e){return eo("ifft")},e.prototype.complex=function(e,t){return eo("complex")},e.prototype.real=function(e){return eo("real")},e.prototype.imag=function(e){return eo("imag")},e.prototype.cropAndResize=function(e,t,r,n,o,a){return eo("cropAndResize")},e.prototype.depthToSpace=function(e,t,r){return eo("depthToSpace")},e.prototype.split=function(e,t,r){return eo("split")},e.prototype.sparseToDense=function(e,t,r,n){return eo("sparseToDense")},e.prototype.diag=function(e){return eo("diag")},e.prototype.fill=function(e,t,r){return eo("fill")},e.prototype.onesLike=function(e){return eo("onesLike")},e.prototype.zerosLike=function(e){return eo("zerosLike")},e.prototype.linspace=function(e,t,r){return eo("linspace")},e.prototype.dispose=function(){return eo("dispose")},e}();function eo(e){throw new Error("'"+e+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function to(e,t){for(var r=e.length,n=[],o=0;o1&&1===i&&n.unshift(a)}return n}function ro(e,t){for(var r=[],n=0;n1)&&r.unshift(a)}return r}function no(e,t){for(var r=[],n=Math.max(e.length,t.length),o=0;o>>1)]);s>0?n=a+1:(o=a,i=!s)}return i?n:-n-1}(e,t,r||Ao)}(e,t,r),o=n<0?-(n+1):n;e.splice(o,0,t)}function Ao(e,t){return e>t?1:eo})).sort(Lo),c=a>0?-.5/a:0,u=[],p=[];u.length0;){var d=l.pop(),_=d.score,h=d.boxIndex,f=d.suppressBeginIndex;if(_=f;--m){var g=Oo(e,h,u[m]);if(g>=n){y=!0;break}if(d.score=d.score*Co(n,c,g),d.score<=o)break}d.suppressBeginIndex=u.length,y||(d.score===_?(u.push(h),p.push(d.score)):d.score>o&&wo(l,d,Lo))}var b=u.length;return s&&(u.fill(0,b),p.fill(0,b)),{selectedIndices:br(u,"int32"),selectedScores:br(p,"float32"),numValidOutputs:gr(b,"int32")}}function Oo(e,t,r){var n=e.subarray(4*t,4*t+4),o=e.subarray(4*r,4*r+4),a=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),s=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),c=Math.min(o[0],o[2]),u=Math.min(o[1],o[3]),p=Math.max(o[0],o[2]),d=Math.max(o[1],o[3]),_=(s-a)*(l-i),h=(p-c)*(d-u);if(_<=0||h<=0)return 0;var f=Math.max(a,c),y=Math.max(i,u),m=Math.min(s,p),g=Math.min(l,d),b=Math.max(m-f,0)*Math.max(g-y,0);return b/(_+h-b)}function Co(e,t,r){var n=Math.exp(t*r*r);return r<=e?n:0}function Lo(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}function Bo(e,t,r){var n=new Array(e.rank).fill(0),o=e.shape.slice();return t.map((function(t){o[r]=t;var a=e.slice(n,o);return n[r]+=t,a}))}function Io(e,t){for(var r=new Array(e.rank),n=0;n":"<",l=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+n+"; i++) {\n int inIdx = "+l+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function Ho(e,t){return["x","y","z","w","u","v"].slice(0,t).map((function(t){return e+"."+t}))}function zo(e,t){return 1===t?[e]:Ho(e,t)}function jo(){var e,t,r,n,o,a,i,s,l,c;return 2===f().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",r="out",n="in",o="texture",a="outputColor",i="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",l="",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",r="varying",n="varying",o="texture2D",a="gl_FragColor",i="",s="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:r,varyingFs:n,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:l,defineRound:c}}function Vo(e,t,r){void 0===r&&(r="index");var n=ne(t);return n.map((function(t,o){return"int "+e[o]+" = "+r+" / "+t+"; "+(o===n.length-1?"int "+e[o+1]+" = "+r+" - "+e[o]+" * "+t:"index -= "+e[o]+" * "+t)+";"})).join("")}function Uo(e){var t=ne(e).map((function(e){return e.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+t[0]+" + coords.y * "+t[1]+" + coords.z;\n }\n"}var Go="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function Ko(e,t,r,n){var o=[];e.forEach((function(e){var t=B(e.shapeInfo.logicalShape);e.shapeInfo.isUniform?o.push("uniform float "+e.name+(t>1?"["+t+"]":"")+";"):(o.push("uniform sampler2D "+e.name+";"),o.push("uniform int offset"+e.name+";"))}));var a,i,s=o.join("\n"),l=e.map((function(e){return function(e,t,r){void 0===r&&(r=!1);var n="";n+=r?function e(t){var r,n,o;switch(t.shapeInfo.logicalShape.length){case 0:return r=t.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),o=jo(),"\n vec4 "+n+"() {\n return "+o.texture2D+"("+r+", halfCR);\n }\n ";case 1:return function(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e.shapeInfo.texShape,o=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],a=jo();return"\n vec4 "+r+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+o[0]+", "+o[1]+", index);\n return "+a.texture2D+"("+t+", uv);\n }\n "}(t);case 2:return function(e){var t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),o=e.shapeInfo.texShape,a=o[0],i=o[1],s=jo();if(null!=o&&I(t,o))return"\n vec4 "+n+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n return "+s.texture2D+"("+r+", uv);\n }\n ";var l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return"\n vec4 "+n+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(t[1]/2)+", "+l[0]+", "+l[1]+", row, col);\n return "+s.texture2D+"("+r+", uv);\n }\n "}(t);case 3:return function(t){var r=t.shapeInfo.logicalShape,n=t.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===r[0]){var s=ea(t,r.slice(1));return"\n "+e(s)+"\n vec4 "+o+"(int b, int row, int col) {\n return "+o+"("+ta(["b","row","col"],[1,2])+");\n }\n "}var l=i[0],c=i[1],u=Math.ceil(r[2]/2);return"\n vec4 "+o+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+l+", "+c+", "+u*Math.ceil(r[1]/2)+", "+u+", b, row, col);\n return "+jo().texture2D+"("+n+", uv);\n }\n "}(t);default:return function(e){for(var t=e.shapeInfo.logicalShape,r=t.length,n=e.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],l=i[1],c=Math.ceil(t[r-1]/2),u=c*Math.ceil(t[r-2]/2),p="int b, int row, int col",d="b * "+u+" + (row / 2) * "+c+" + (col / 2)",_=2;_=1?"coords = 0;":l.map((function(e){return"coords."+p[e+u]+" = 0;"})).join("\n");var d;d=s<2&&i>0?"coords":e.shapeInfo.logicalShape.map((function(e,t){return"coords."+p[t+u]})).join(", ");var _="return outputValue;",h=1===B(e.shapeInfo.logicalShape),f=1===B(t.logicalShape);if(1!==i||h||f){if(h&&!f)_=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(l.length){var y=i-2,m=i-1;l.indexOf(y)>-1&&l.indexOf(m)>-1?_="return vec4(outputValue.x);":l.indexOf(y)>-1?_="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":l.indexOf(m)>-1&&(_="return vec4(outputValue.xx, outputValue.zz);")}}else _="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+c+" coords = getOutputCoords();\n "+r+"\n vec4 outputValue = get"+o+"("+d+");\n "+_+"\n }\n "}(e,t):function(e,t){var r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),o="get"+n+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,s=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&s===l&&null==e.shapeInfo.flatOffset&&I(i,a))return"\n float "+o+"() {\n return sampleTexture("+r+", resultUV);\n }\n ";var c=$o(l),u=to(e.shapeInfo.logicalShape,t.logicalShape),p=l-s,d=["x","y","z","w","u","v"];return"\n float "+o+"() {\n "+c+" coords = getOutputCoords();\n "+(0===s?"":l<2&&u.length>=1?"coords = 0;":u.map((function(e){return"coords."+d[e+p]+" = 0;"})).join("\n"))+"\n return get"+n+"("+(l<2&&s>0?"coords":e.shapeInfo.logicalShape.map((function(e,t){return"coords."+d[t+p]})).join(", "))+");\n }\n "}(e,t)),n}(e,t,n)})).join("\n"),c=t.texShape,u=jo(),p=function(e){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+e.texture2D+"(textureSampler, uv).r;\n }\n "}(u),d=function(e){return e.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+e.varyingFs+" vec2 resultUV;\n "+e.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+e.defineSpecialNaN+"\n "+e.defineSpecialInf+"\n "+e.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+qo+"\n "+Xo+"\n "+Qo+"\n "}(u);return t.isPacked?(a=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+r[1]+".0);\n }\n ":1===r[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+r[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n return 2 * (resTexRC.x * "+r[1]+" + resTexRC.y);\n }\n "}(0,t);case 2:return function(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(I(e,t))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+r[0]+", "+r[1]+"));\n }\n ";var n=Math.ceil(e[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n\n int index = resTexRC.x * "+r[1]+" + resTexRC.y;\n int r = 2 * (index / "+n+");\n int c = imod(index, "+n+") * 2;\n\n return ivec2(r, c);\n }\n "}(e,t);case 3:return r=e,n=t,o=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],i=(a=Math.ceil(r[2]/2))*Math.ceil(r[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+o[0]+", "+o[1]+"));\n int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(e,t){for(var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[e.length-1]/2),o=n*Math.ceil(e[e.length-2]/2),a=o,i="",s="b, r, c",l=2;l2,(function(){return"Packed arg"+(r.charAt(0).toUpperCase()+r.slice(1))+" supports only inputs with rank above 2."}));var o=e[e.length-1],a=Math.ceil(o/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");var i,s,l=this.outputShape,c=l.length,u=$o(c),p=zo("coords",c);if(1===a){var d=$o(s=c+1);i="\n "+d+" sourceLocR = "+d+"("+p.join()+", 0);\n ++"+p[c-1]+";\n "+d+" sourceLocG = "+d+"("+p.join()+", 0);\n ++"+p[c-2]+";\n "+d+" sourceLocA = "+d+"("+p.join()+", 0);\n --"+p[c-1]+";\n "+d+" sourceLocB = "+d+"("+p.join()+", 0);\n --"+p[c-2]+";"}else s=c,i="\n "+u+" sourceLocR = coords;\n ++"+p[c-1]+";\n "+u+" sourceLocG = coords;\n ++"+p[c-2]+";\n "+u+" sourceLocA = coords;\n --"+p[c-1]+";\n "+u+" sourceLocB = coords;\n --"+p[c-2]+";";var _=["x","y","z","w","u","v"].slice(0,s),h="."+_[s-1],f=_.map((function(e){return"int "+e})),y=zo("sourceLocR",s-1).concat("inIdx.r"),m=zo("sourceLocG",s-1).concat("inIdx.g"),g=zo("sourceLocB",s-1).concat("inIdx.b"),b=zo("sourceLocA",s-1).concat("inIdx.a"),v="max"===r?"greaterThan":"lessThan",E=n?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+b.join()+")));",k="vec4(\n getAChannel("+y.join()+"),\n hasNextCol ? getAChannel("+m.join()+") : 0.,\n hasNextRow ? getAChannel("+g.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",S=n?"":"\n float getBestIndicesAChannel("+f.join()+") {\n return getChannel(getBestIndicesA("+_.join()+"),\n vec2("+_.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+f.join()+") {\n return getChannel(getA("+_.join()+"),\n vec2("+_.slice(-2).join()+"));\n }\n "+S+"\n void main() {\n "+u+" coords = getOutputCoords();\n bool hasNextCol = "+p[c-1]+" < "+(l[c-1]-1)+";\n bool hasNextRow = "+p[c-2]+" < "+(l[c-2]-1)+";\n "+i+"\n ivec4 srcIdx = ivec4(sourceLocR"+h+", sourceLocG"+h+",\n sourceLocB"+h+", sourceLocA"+h+") * "+t+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+k+";\n\n for (int i = 0; i < "+t+"; i++) {\n inIdx = srcIdx;\n "+E+"\n vec4 candidate = "+k+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+v+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},na=function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=s-1-e.padInfo.top,u=l-1-e.padInfo.left,p=1/(t*r);this.userCode="\n const ivec2 pads = ivec2("+c+", "+u+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},oa=function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,s=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,_=u-1-e.padInfo.front,h=p-1-e.padInfo.top,f=d-1-e.padInfo.left,y=1/(t*r*n);this.userCode="\n const ivec3 pads = ivec3("+_+", "+h+", "+f+");\n const float avgMultiplier = float("+y+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+u+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+o+".0;\n\n if (dyD < 0.0 || dyD >= "+e.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+l+") {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+d+";\n wC += "+c+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},aa=function(e,t,r,n,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],no(e,t),no(e,r);var i="0.0";null!=n&&(no(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(no(e,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},ia=function(e,t,r,n,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],no(e,t),no(e,r);var i="vec4(0.0)";null!=n&&(no(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(no(e,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n vec4 offset = "+i+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},sa=function(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=no(t,r),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+e+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},la="return a + b;",ca="return a - b;",ua="return a * b;",pa="return (a < 0.) ? b * a : a;",da=function(e,t,r){this.variableNames=["A","B"],this.outputShape=no(t,r),this.userCode="\n float binaryOperation(float a, float b) {\n "+e+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},_a="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",ha=function(e,t,r,n){void 0===n&&(n=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=no(t,r);var o=this.outputShape.length,a="";if(n)if(0===o||1===B(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+$o(o)+" coords = getOutputCoords();\n ",1===o)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=zo("coords",o);a+="\n bool nextRowOutOfBounds =\n ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+i[o-1]+" + 1) >= "+this.outputShape[o-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+e+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+a+"\n\n setOutput(result);\n }\n "},fa=function(){function e(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return e.prototype.getCustomSetupFunc=function(e,t){var r=this;return function(n,o){null==r.minLoc&&(r.minLoc=n.getUniformLocationNoThrow(o,"minVal"),r.maxLoc=n.getUniformLocationNoThrow(o,"maxVal")),n.gl.uniform1f(r.minLoc,e),n.gl.uniform1f(r.maxLoc,t)}},e}(),ya=function(){function e(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return e.prototype.getCustomSetupFunc=function(e,t){var r=this;return function(n,o){null==r.minLoc&&(r.minLoc=n.getUniformLocationNoThrow(o,"minVal"),r.maxLoc=n.getUniformLocationNoThrow(o,"maxVal")),n.gl.uniform1f(r.minLoc,e),n.gl.uniform1f(r.maxLoc,t)}},e}(),ma=function(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},ga=function(e){this.outputShape=[],this.outputShape=pr(e,1),this.variableNames=e.map((function(e,t){return"T"+t}));var t=new Array(e.length-1);t[0]=e[0][1];for(var r=1;r= "+s[l-1]+") {\n return getChannel(\n getT"+l+"("+va(i,c,_)+"),\n vec2("+va(u,c,_)+"));\n }"}var h=s.length,f=s[s.length-1];d+="\n return getChannel(\n getT"+h+"("+va(i,c,f)+"),\n vec2("+va(u,c,f)+"));",this.userCode="\n float getValue("+i.map((function(e){return"int "+e}))+") {\n "+d+"\n }\n\n void main() {\n "+o+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n "+a[n-1]+" = "+a[n-1]+" + 1;\n if ("+a[n-1]+" < "+r[n-1]+") {\n result.g = getValue("+a+");\n }\n\n "+a[n-2]+" = "+a[n-2]+" + 1;\n if ("+a[n-2]+" < "+r[n-2]+") {\n result.a = getValue("+a+");\n }\n\n "+a[n-1]+" = "+a[n-1]+" - 1;\n if ("+a[n-2]+" < "+r[n-2]+" &&\n "+a[n-1]+" < "+r[n-1]+") {\n result.b = getValue("+a+");\n }\n setOutput(result);\n }\n "};function va(e,t,r){var n=e.indexOf(t);return e.map((function(e,t){return t===n?e+" - "+r:e})).join()}var Ea=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,o=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+n+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},ka=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,o=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,s=r-1-e.padInfo.left,l=a?1:2,c=a?2:3,u=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+u+"];\n\n ivec2 dyCorner = ivec2(coords["+l+"], coords["+c+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Sa=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,o=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yF = 0; yF < "+e.outDepth+"; yF++) {\n int xF = wF + yF * "+t+" - "+o+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+r+" - "+a+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ra=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,s=t-1-e.padInfo.front,l=r-1-e.padInfo.top,c=n-1-e.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+l+", "+c+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+t+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+o+".0;\n\n if (dyF < 0.0 || dyF >= "+e.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+t+" - 1 - wF;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+r+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},wa=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,o=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+n+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Aa=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,o=e.strideWidth,a=t-1-e.padInfo.top,i=r-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},xa=function(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=null),void 0===n&&(n=!1),this.variableNames=["x","W"],this.outputShape=e.outShape;var o=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,s=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,u=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),_=e.inChannels%4,h="channelsLast"===e.dataFormat,f=h?1:2,y=h?2:3,m=h?3:1,g="",b="";r&&(g=n?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+r+"\n }":"\n float activation(float x) {\n "+r+"\n }\n ",b="result = activation(result);");var v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+g+"\n\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+m+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+f+"], coords["+y+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+u+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+c+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+d+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+h+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===_)+") {\n\n if ("+h+") {\n dotProd +=\n getX(batch, xR, xC, "+d+") *\n getW(wR, wC, "+d+", d2);\n } else {\n dotProd +=\n getX(batch, "+d+", xR, xC) *\n getW(wR, wC, "+d+", d2);\n }\n\n } else if ("+(2===_)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+d+", d2),\n getW(wR, wC, "+d+" + 1, d2)\n );\n\n if ("+h+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+d+"),\n getX(batch, xR, xC, "+d+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+d+", xR, xC),\n getX(batch, "+d+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===_)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+d+", d2),\n getW(wR, wC, "+d+" + 1, d2),\n getW(wR, wC, "+d+" + 2, d2)\n );\n\n if ("+h+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+d+"),\n getX(batch, xR, xC, "+d+" + 1),\n getX(batch, xR, xC, "+d+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+d+", xR, xC),\n getX(batch, "+d+" + 1, xR, xC),\n getX(batch, "+d+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+v+"\n "+b+"\n setOutput(result);\n }\n "},Da=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.front,r=e.padInfo.top,n=e.padInfo.left,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,s=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.filterDepth,p=e.filterHeight,d=e.filterWidth,_=4*Math.floor(e.inChannels/4),h=e.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+t+", "+r+", "+n+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+u+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+c+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+_+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===h)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+_+") *\n getW(wF, wR, wC, "+_+", d2);\n } else if ("+(2===h)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+_+"),\n getX(batch, xF, xR, xC, "+_+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+_+", d2),\n getW(wF, wR, wC, "+_+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===h)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+_+"),\n getX(batch, xF, xR, xC, "+_+" + 1),\n getX(batch, xF, xR, xC, "+_+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+_+", d2),\n getW(wF, wR, wC, "+_+" + 1, d2),\n getW(wF, wR, wC, "+_+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ta=function(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=null),void 0===n&&(n=!1),this.variableNames=["x","W"],this.outputShape=e.outShape;var o=e.inHeight,a=e.inWidth,i=e.padInfo.top,s=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,_=e.filterWidth,h=e.outChannels/e.inChannels,f="",y="";r&&(f=n?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+r+"\n }":"\n float activation(float x) {\n "+r+"\n }\n ",y="result = activation(result);");var m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const ivec2 strides = ivec2("+l+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+h+";\n int q = d2 - d1 * "+h+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+d+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+o+") {\n continue;\n }\n\n for (int wC = 0; wC < "+_+"; wC++) {\n int xC = xCCorner + wC * "+p+";\n\n if (xC < 0 || xC >= "+a+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+m+"\n "+y+"\n setOutput(result);\n }\n "},Oa=function(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=null),void 0===n&&(n=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;for(var o=e.inHeight,a=e.inWidth,i=e.padInfo.top,s=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,_=e.filterWidth,h=_,f="int xR; int xC; int xCOffset;",y=0;y= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+m+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n xTexelR"+y+"C"+m+".zw = vec2(0.);\n }\n } else {\n xTexelR"+y+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n previous.zw = vec2(0.);\n }\n\n xR"+y+"C"+m+" = vec4(previous.zw, xTexelR"+y+"C"+m+".xy);\n } else {\n xR"+y+"C"+m+" = vec4(0, 0, xTexelR"+y+"C"+m+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n xTexelR"+y+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+y+"C"+m+" = vec4(0.);\n }\n\n xR"+y+"C"+m+" = xTexelR"+y+"C"+m+";\n ",m+1<_)){var b=s%2==0?x(p):p;p%2==0&&s%2==1||p%2!=0&&s%2!=1?(f+="\n xCOffset = xC + "+s%2+" + "+b+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",p>1&&(f+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+y+"C"+m+" = vec4(0.);\n }\n "),f+="\n xR"+y+"C"+(m+1)+" = vec4(\n xTexelR"+y+"C"+m+".zw, xTexelR"+y+"C"+(m+2)+".xy);\n "):f+="\n xCOffset = xC + "+b+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+y+"C"+(m+1)+" = xTexelR"+y+"C"+(m+2)+";\n "}}else m<_&&(f+="\n if(xR >= 0 && xR < "+o+") {\n ",s%2==1?(f+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+y+"C"+m+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+a+") {\n xTexelR"+y+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+y+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+y+"C"+m+" = vec4(\n xTexelR"+y+"C"+m+".zw, xTexelR"+y+"C"+(m+2)+".zw);\n ",m+1<_&&(f+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+y+"C"+(m+1)+" = vec4(xTexelR"+y+"C"+(m+2)+".xy, final.xy);\n ")):(f+="\n if(xC >= 0 && xC < "+a+") {\n xTexelR"+y+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+y+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+y+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+y+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+y+"C"+m+" = vec4(\n xTexelR"+y+"C"+m+".xy, xTexelR"+y+"C"+(m+2)+".xy);\n ",m+1<_&&(f+="\n xR"+y+"C"+(m+1)+" = vec4(\n xTexelR"+y+"C"+m+".zw, xTexelR"+y+"C"+(m+2)+".zw);\n ")),f+="}");m<_&&(f+="\n vec4 wTexelR"+y+"C"+m+" = getW("+y+", "+m+", d1, q);\n wR"+y+"C"+m+" = vec4(wTexelR"+y+"C"+m+".xz, wTexelR"+y+"C"+m+".xz);\n ",m+1<_&&(f+="\n vec4 wTexelR"+y+"C"+(m+1)+" = getW("+y+", "+(m+1)+", d1, q);\n wR"+y+"C"+(m+1)+" =\n vec4(wTexelR"+y+"C"+(m+1)+".xz, wTexelR"+y+"C"+(m+1)+".xz);"))}for(y=0;y1?[""+(i-1)/(u-1),"(y2-y1) * height_ratio","y1*"+h+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+h],m=y[0],g=y[1],b=y[2],v=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+f+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+f],E=v[0],k=v[1],S=v[2];this.userCode="\n const float height_ratio = float("+m+");\n const float width_ratio = float("+E+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+a+") {\n return;\n }\n\n float height_scale = "+g+";\n float width_scale = "+k+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+h+" ) {\n setOutput(float("+o+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+f+" ) {\n setOutput(float("+o+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+d+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},La=function(e,t,r){this.variableNames=["x"],this.outputShape=e;var n=e.length,o=e[e.length-1],a=r?"<":">";this.userCode="\n int getIndex(int i) {\n "+(r?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+$o(n)+" coords = getOutputCoords();\n int end = "+Ba(n,"coords")+";\n float val = 0.0;\n for (int i = "+o+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+Ba(n,"coords")+" = idx;\n val += getX("+function(e,t){if(1===e)return""+t;if(2===e)return t+".x, "+t+".y";if(3===e)return t+".x, "+t+".y, "+t+".z";if(4===e)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}(n,"coords")+");\n }\n setOutput(val);\n }\n "};function Ba(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}var Ia=function(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ge.DENSE;var t=$e(e),r=jo();this.outputShape=e,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Vo(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = 4 * (resTexRC.x * "+t[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+r.output+" = result;\n }\n "},Na=function(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ge.DENSE;var t=$e(e),r=jo();this.outputShape=e,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Vo(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = 4 * (resTexRC.x * "+t[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+r.output+" = result;\n }\n "},Ma=function(){function e(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+t+";\n int offset_h = imod(h, "+t+");\n int in_w = w / "+t+";\n int offset_w = imod(w, "+t+");\n int offset_d = (offset_h * "+t+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}(),Pa=function(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},Fa=function(e){this.variableNames=["A"],this.outTexUsage=Ke.DOWNLOAD;var t=jo();this.outputShape=e,this.userCode="\n "+Go+"\n\n void main() {\n float x = getAAtOutCoords();\n "+t.output+" = encode_float(x);\n }\n "},Wa=function(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ke.DOWNLOAD;var t=jo();this.outputShape=e,this.userCode="\n "+Go+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+t.output+" = encode_float(x);\n }\n "},Ha=function(e,t,r){void 0===r&&(r=!1),this.variableNames=["A"];var n=jo(),o=t[0],a=t[1];this.outputShape=e;var i="result";r&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+Uo(e)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n vec4 values = "+n.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+n.output+" = vec4("+i+", 0., 0., 0.);\n }\n "},za=function(e,t,r){void 0===r&&(r=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var n=jo(),o=t[0],a=t[1];this.outputShape=e;var i="",s="result";r&&(s="floor(result * 255. + 0.5)");for(var l=0;l<=1;l++)for(var c=0;c<=1;c++){var u=2*l+c;i+="\n localCoords = coords;\n if(localCoords[2] + "+c+" < "+e[2]+") {\n localCoords[2] += "+c+";\n if(localCoords[1] + "+l+" < "+e[1]+") {\n localCoords[1] += "+l+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n values = "+n.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+u+"] = values[0];\n } else if(offset == 1) {\n result["+u+"] = values[1];\n } else if(offset == 2) {\n result["+u+"] = values[2];\n } else {\n result["+u+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Uo(e)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+i+"\n\n "+n.output+" = "+s+";\n }\n "},ja=function(e,t,r){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var o=r?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=r?n+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+o+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+e+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+n+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+n+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},Va=function(){function e(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(r,n){null==t.valueLoc&&(t.valueLoc=r.getUniformLocationNoThrow(n,"value")),r.gl.uniform1f(t.valueLoc,e)}},e}(),Ua=function(e,t,r){this.variableNames=["A","indices"];var n=e.slice();n[r]=t,this.outputShape=n,this.rank=n.length;var o=$o(this.rank),a=function(e,t){var r=e.length;if(r>4)throw Error("Gather for rank "+r+" is not yet supported");if(1===r)return"int(getIndices(resRC))";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],a=0;a1?"strides[j]":"strides";this.userCode="\n "+n+" strides = "+n+"("+this.strides+");\n void main() {\n "+o+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function Ka(e,t){var r=jo();return it(e,t,r.version+"\n precision highp float;\n "+r.attribute+" vec3 clipSpacePos;\n "+r.attribute+" vec2 uv;\n "+r.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function qa(e,t){return ht(e,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Xa(e,t){return ft(e,t,new Uint16Array([0,1,2,2,1,3]))}function Qa(e,t,r,n,o,a,i){mt(r,n);var s=yt(e,t),l=e.TEXTURE_2D;return rt(e,t,(function(){return e.bindTexture(l,s)})),rt(e,t,(function(){return e.texParameteri(l,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)})),rt(e,t,(function(){return e.texParameteri(l,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)})),rt(e,t,(function(){return e.texParameteri(l,e.TEXTURE_MIN_FILTER,e.NEAREST)})),rt(e,t,(function(){return e.texParameteri(l,e.TEXTURE_MAG_FILTER,e.NEAREST)})),rt(e,t,(function(){return e.texImage2D(l,0,o,r,n,0,a,i,null)})),rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)})),s}function Ya(e,t,r,n,o){var a=Ze(r,n);return Qa(e,t,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,e.FLOAT)}function Ja(e,t,r,n,o){var a=Ze(r,n);return Qa(e,t,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Za(e,t,r,n,o){var a=Ze(r,n);return Qa(e,t,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function $a(e,t,r,n,o){var a=et(r,n);return Qa(e,t,a[0],a[1],o.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function ei(e,t,r,n,o){var a=et(r,n);return Qa(e,t,a[0],a[1],o.internalFormatPackedHalfFloat,e.RGBA,o.textureTypeHalfFloat)}function ti(e,t,r,n){return rt(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,n)})),bt(e,t,r,"clipSpacePos",n,3,20,0)&&bt(e,t,r,"uv",n,2,20,12)}function ri(e,t,r,n,o,a,i){var s,l,c;rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,r)})),a instanceof Uint8Array?(s=new Uint8Array(n*o*4),l=e.UNSIGNED_BYTE,c=e.RGBA):(s=new Float32Array(n*o*4),l=e.FLOAT,c=i.internalFormatPackedFloat),s.set(a),rt(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,c,n,o,0,e.RGBA,l,s)})),rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function ni(e,t,r,n){rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,r)})),n.data instanceof Uint8Array?rt(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)})):rt(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)})),rt(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function oi(e,t,r,n,o){var a=e.createBuffer();rt(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,a)}));var i=16*r*n;return rt(e,t,(function(){return e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)})),rt(e,t,(function(){return e.readPixels(0,0,n,r,e.RGBA,e.FLOAT,0)})),rt(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,null)})),a}function ai(e,t,r){var n=e,o=new Float32Array(r);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function ii(e,t,r,n,o){var a=Ze(r,n),i=a[0],s=a[1],l=new Uint8Array(r*n*4);return rt(e,t,(function(){return e.readPixels(0,0,i,s,o.downloadTextureFormat,e.UNSIGNED_BYTE,l)})),new Float32Array(l.buffer)}function si(e,t,r,n,o,a,i,s){var l=e,c=new Float32Array(function(e,t){var r=et(e,t);return r[0]*r[1]*4}(a,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function li(e,t,r,n){var o=new Float32Array(r*n*4);return rt(e,t,(function(){return e.readPixels(0,0,n,r,e.RGBA,e.FLOAT,o)})),o}var ci=Object.freeze({createVertexShader:Ka,createVertexBuffer:qa,createIndexBuffer:Xa,createFloat32MatrixTexture:Ya,createFloat16MatrixTexture:Ja,createUnsignedBytesMatrixTexture:Za,createPackedMatrixTexture:$a,createFloat16PackedMatrixTexture:ei,bindVertexProgramAttributeStreams:ti,uploadDenseMatrixToTexture:ri,uploadPixelDataToTexture:ni,createBufferFromOutputTexture:oi,downloadFloat32MatrixFromBuffer:ai,downloadByteEncodedFloatMatrixFromOutputTexture:ii,downloadPackedMatrixFromBuffer:si,downloadMatrixFromPackedOutputTexture:li}),ui=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var t=f().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,Ye(t,e)):this.gl=Je(t);var r="WEBGL_color_buffer_float";if(1===f().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=at(this.gl,this.debug,"OES_texture_float"),Wt(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=at(this.gl,this.debug,"OES_texture_half_float");else if(f().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(r),Wt(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=at(this.gl,this.debug,"EXT_color_buffer_half_float");else if(f().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(r="EXT_color_buffer_float",Wt(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else{if(!Wt(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=qa(this.gl,this.debug),this.indexBuffer=Xa(this.gl,this.debug),this.framebuffer=gt(this.gl,this.debug),this.textureConfig=tt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return f().getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var t=this.gl;rt(t,this.debug,(function(){return t.finish()})),rt(t,this.debug,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),rt(t,this.debug,(function(){return t.deleteFramebuffer(e.framebuffer)})),rt(t,this.debug,(function(){return t.bindBuffer(t.ARRAY_BUFFER,null)})),rt(t,this.debug,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)})),rt(t,this.debug,(function(){return t.deleteBuffer(e.indexBuffer)})),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),Ya(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),Ja(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),Za(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),ni(this.gl,this.debug,e,t)},e.prototype.uploadDenseMatrixToTexture=function(e,t,r,n){this.throwIfDisposed(),ri(this.gl,this.debug,e,t,r,n,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(e,t){return this.throwIfDisposed(),ei(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),$a(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(wt(this.gl,this.debug,this.framebuffer),this.outputTexture=null),rt(this.gl,this.debug,(function(){return t.gl.deleteTexture(e)}))},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,(function(){return ii(n.gl,n.debug,t,r,n.textureConfig)}))},e.prototype.downloadPackedMatrixFromBuffer=function(e,t,r,n,o,a){return si(this.gl,e,0,0,0,o,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(e,t){return ai(this.gl,e,t)},e.prototype.createBufferFromTexture=function(e,t,r){this.bindTextureToFrameBuffer(e);var n=oi(this.gl,this.debug,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),n},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(e){var t,r,n=this;if(f().getBool("WEBGL_FENCE_API_ENABLED")){var o=e,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=function(){var e=o.clientWaitSync(a,0,0);return e===o.ALREADY_SIGNALED||e===o.CONDITION_SATISFIED},t=a}else f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=function(){return n.isQueryAvailable(t,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:t,isFencePassed:r}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,(function(){return li(n.gl,n.debug,t,r)}))},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,r=st(t,this.debug,e),n=Ka(t,this.debug),o=pt(t,this.debug);return rt(t,this.debug,(function(){return t.attachShader(o,n)})),rt(t,this.debug,(function(){return t.attachShader(o,r)})),dt(t,this.debug,o),this.debug&&_t(t,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=ti(t,this.debug,this.program,this.vertexBuffer)),o},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&rt(this.gl,this.debug,(function(){return t.gl.deleteProgram(e)}))},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&_t(this.gl,this.debug,this.program),rt(this.gl,this.debug,(function(){return t.gl.useProgram(e)}))},e.prototype.getUniformLocation=function(e,t,r){return void 0===r&&(r=!0),this.throwIfDisposed(),r?Et(this.gl,this.debug,e,t):kt(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var r=this;return this.throwIfDisposed(),rt(this.gl,this.debug,(function(){return r.gl.getAttribLocation(e,t)}))},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),St(this.gl,this.debug,this.program,e,t,r)},e.prototype.setOutputMatrixTexture=function(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,r){this.throwIfDisposed();var n=et(t,r),o=n[0],a=n[1];this.setOutputMatrixTextureDriver(e,o,a)},e.prototype.setOutputMatrixWriteRegion=function(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&_t(this.gl,this.debug,this.program),At(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.debug&&this.debugValidate(),rt(e,this.debug,(function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)}))},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),rt(this.gl,this.debug,(function(){return e.gl.finish()}))},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=at(this.gl,this.debug,2===f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,r),r}var n=this.getQueryTimerExtensionWebGL1(),o=n.createQueryEXT();return n.beginQueryEXT(n.TIME_ELAPSED_EXT,o),o},e.prototype.endQuery=function(){if(2!==f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return p(this,void 0,void 0,(function(){var t=this;return d(this,(function(r){switch(r.label){case 0:return[4,W((function(){return t.disposed||t.isQueryAvailable(e,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return r.sent(),[2,this.getQueryTime(e,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}var n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var r=this.gl,n=this.getQueryTimerExtensionWebGL2(),o=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),o&&!this.disjoint}return o=(n=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),o&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise((function(r){t.addItemToPoll((function(){return e.isFencePassed()}),(function(){return r()}))}))},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0;t1||W((function(){return r.pollItems(),0===r.itemsToPoll.length}))},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),Rt(this.gl,this.debug,e,this.framebuffer),this.debug&&At(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Rt(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&At(this.gl)):wt(this.gl,this.debug,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var r=t();return this.unbindTextureToFrameBuffer(),r},e.prototype.setOutputMatrixTextureDriver=function(e,t,r){this.throwIfDisposed();var n=this.gl;Rt(n,this.debug,e,this.framebuffer),this.debug&&At(n),this.outputTexture=e,rt(n,this.debug,(function(){return n.viewport(0,0,t,r)})),rt(n,this.debug,(function(){return n.scissor(0,0,t,r)}))},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,r,n){var o=this;this.throwIfDisposed(),rt(this.gl,this.debug,(function(){return o.gl.scissor(e,t,r,n)}))},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function pi(e,t){if(e.length!==t.length)throw Error("Binary was compiled with "+e.length+" inputs, but was executed with "+t.length+" inputs");e.forEach((function(e,r){var n=e.logicalShape,o=t[r],a=o.shape;if(!I(n,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+n+" and "+a+" must match");if(!e.isUniform||!o.isUniform){var i=e.texShape,s=o.isUniform?null:o.texData.texShape;if(!I(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}}))}var di=function(e,t,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var n=r.filterWidth,o=r.inChannels,a=r.strideWidth,i=r.strideHeight,s=r.padInfo,l=r.outWidth,c=r.dilationWidth,u=r.dilationHeight,p=r.dataFormat,d=s.left,_=s.top,h=o*n,f=jo(),y="channelsLast"===p,m=y?0:1,g=y?1:2,b="",v=0;v<=1;v++)for(var E=0;E<=1;E++)b+="\n blockIndex = rc.y + "+E+";\n pos = rc.x + "+v+";\n\n if(blockIndex < "+e[1]+" && pos < "+e[0]+") {\n offsetY = int(blockIndex / ("+l+")) * "+i+" - "+_+";\n d0 = offsetY + "+u+" * (pos / "+h+");\n\n if(d0 < "+t[m]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+l+".) * "+a+". - "+d+".);\n d1 = offsetX + "+c+" * (int(mod(float(pos), "+h+".) / "+o+".));\n\n if(d1 < "+t[g]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+o+".));\n\n if ("+y+") {\n innerDims = vec2(d1, ch);\n result["+(2*v+E)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*v+E)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+f.output+" = result;\n }\n "},_i=function(e,t,r,n,o){this.variableNames=["x"],this.outputShape=[];var a,i=t,s=e[3]-1;this.outputShape=e;var l="float("+r+") + float("+n+") * sum";a=.5===o?"inversesqrt("+l+")":1===o?"1.0/("+l+")":"exp(log("+l+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+i+"; j <= "+i+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+a+";\n setOutput(val);\n }\n "},hi=function(e,t,r,n,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=n,this.beta=o,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+t+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+t+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+n+") * norm + float("+r+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+n+")\n * float("+o+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+o+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},fi=function(e,t,r,n,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=t,s=e[3]-1;this.outputShape=e;var l="float("+r+") + float("+n+") * sum";a=.5===o?"inversesqrt("+l+")":1===o?"1.0/("+l+")":"exp(log("+l+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+i+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+i+"; j <= "+i+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+a+";\n setOutput(result);\n }\n "},yi=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideHeight,r=e.strideWidth,n=e.dilationHeight,o=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=o-1-e.padInfo.top,s=a-1-e.padInfo.left,l=o*a-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+o+";\n wR += "+n+") {\n float dyR = float(dyRCorner + wR) / "+t+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+a+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+l+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},mi=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,o=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=s-1-e.padInfo.front,p=l-1-e.padInfo.top,d=c-1-e.padInfo.left,_=s*l*c-1;this.userCode="\n const ivec3 pads = ivec3("+u+", "+p+", "+d+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+o+") {\n float dyD = float(dyDCorner + wD) / "+t+".0;\n\n if (dyD < 0.0 || dyD >= "+e.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+l+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+c+";\n wC += "+i+") {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+_+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+l+" * "+c+" +\n wR * "+c+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},gi=function(e,t,r,n,o,a,i){void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=r?e[1]:e[2],l=Math.ceil(s/2),c=r?"i * 2, rc.y":"rc.y, i * 2",u=n?"rc.z, i * 2":"i * 2, rc.z",p=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],d=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],_="",h="";a&&(_=i?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",h="result = activation(result);");var f=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+_+"\n\n const float sharedDimension = "+l+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+l+"; i++) {\n vec4 a = getMatrixA(rc.x, "+c+");\n vec4 b = getMatrixB(rc.x, "+u+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+d[0]+");\n result += ("+p[1]+" * "+d[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+f+"\n\n "+h+"\n\n setOutput(result);\n }\n "},bi=function(){function e(e,t,r){this.variableNames=["probs"],this.outputShape=[e,r],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(t-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(t-1)+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(r,n){null==t.seedLoc&&(t.seedLoc=r.getUniformLocation(n,"seed")),r.gl.uniform1f(t.seedLoc,e)}},e}(),vi=function(e,t,r,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+n+"), float("+r+"),\n float(index == coords.y)));\n }\n "},Ei=function(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;var t=e.length;if(0===t)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var r=zo("rc",t),n=$o(t),o=function(e,t,r){if(1===e)return"rc > "+t[0];for(var n="",o=e-2;o= "+t[o],o= "+t+";\n bool rEdge = rp1 >= "+r+";\n "}(t,e[e.length-1],e[e.length-2],r),i=function(e,t){var r=e.length,n=function(e,t){for(var r=[],n=0;n<=1;n++)for(var o=0;o<=1;o++){for(var a=(0===n?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i= "+e[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+n[0]+"),\n cEdge ? 0. : getA("+n[1]+"),\n rEdge ? 0. : getA("+n[2]+"),\n rEdge || cEdge ? 0. : getA("+n[3]+")"}(e,r);this.userCode="\n void main() {\n "+n+" rc = getOutputCoords();\n\n if("+o+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+i+"));\n }\n }\n "}},ki=function(e,t,r){this.variableNames=["x"],this.outputShape=t.map((function(t,r){return t[0]+e[r]+t[1]}));var n=e.length,o=$o(n),a=t.map((function(e){return e[0]})).join(","),i=t.map((function(t,r){return t[0]+e[r]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=1!==n?"\n "+o+" start = "+o+"("+a+");\n "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+r+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+r+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Si=function(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((function(t,r){return t[0]+e[r]+t[1]}));for(var n=e.length,o=$o(n),a=t.map((function(e){return e[0]})).join(","),i=t.map((function(t,r){return t[0]+e[r]})).join(","),s=zo("rc",n),l=zo("source",n),c=s[n-1]+" < "+this.outputShape[n-1],u=1===n?"source":"vec2("+l.slice(-2).join()+")",p=[o+" rc = outputLoc;",s[n-1]+" += 1;\n if("+c+") {\n ",1===n?"":"}\n rc = outputLoc;\n "+s[n-2]+" += 1;\n if("+s[n-2]+" < "+this.outputShape[n-2]+") {",1===n?"":" "+s[n-1]+" += 1;\n if("+c+") {"],d=1===n?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",_="",h=0,f=1===n?2:4;h= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+c+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var h=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(h="avgValue / count");var f=4*Math.floor(n/4),y=n%4,m="\n if ("+d+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+u+", "+p+");\n const float initializationValue = "+_+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+_+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+l+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+m+"\n }\n\n int xC = xCCorner + "+f+";\n if ("+(1===y)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+m+"\n } else if ("+(2===y)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+m+"\n } else if ("+(3===y)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+m+"\n }\n }\n setOutput("+h+");\n }\n "}},wi=function(e,t,r){if(this.variableNames=["x"],"avg"===t&&r)throw new Error("Cannot compute positions for average pool.");var n=e.filterWidth,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,s=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,_=e.padInfo.front,h=e.padInfo.top,f=e.padInfo.left;this.outputShape=e.outShape;var y="avg"===t,m="0.0";if(y||(m="-1.0 / 1e-20"),r)this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+_+", "+h+", "+f+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+u+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+";\n wC += "+c+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+p+" * "+d+" +\n wR * "+d+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var g=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(g="avgValue / count");var b=4*Math.floor(n/4),v=n%4,E="\n if ("+y+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+_+", "+h+", "+f+");\n const float initializationValue = "+m+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+m+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+u+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+c+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n getValue(batch, xD, xR, xC + 3 * "+c+", ch)\n );\n\n "+E+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===v)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+E+"\n } else if ("+(2===v)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n initializationValue,\n initializationValue\n );\n\n "+E+"\n } else if ("+(3===v)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n initializationValue\n );\n\n "+E+"\n }\n }\n setOutput("+g+");\n }\n }\n "}},Ai=function(e,t){this.variableNames=["x"];var r=e.windowSize,n=e.batchSize,o=e.inSize,a=Math.ceil(o/r);this.outputShape=[n,a];var i="0.0",s="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",s="min"):"max"===t&&(i="-1.0 / 1e-20",s="max");var l=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t?l="sumValue":"prod"===t?l="prodValue":"all"===t?l="allValue":"any"===t&&(l="anyValue");var c=4*Math.floor(r/4),u=r%4,p="\n if ("+("sum"===t)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===t)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",d="vec4";"all"===t?(i="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",d="bvec4"):"any"===t&&(i="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",d="bvec4");var _="";o%r>0&&(_="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+_+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n vec4 minMaxValue = vec4("+i+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+c+"; i += 4) {\n int inIdx = inOffset + i;\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+c+";\n if ("+(1===u)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===u)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===u)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+l+");\n }\n "},xi=function(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var r="",n=0;n<4;n++){var o="thisRC = rc;";n%2==1&&(o+="thisRC.z += 1;"),n>1&&(o+="thisRC.y += 1;"),r+="\n "+o+"\n "+(n>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+n+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(n>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+Vo(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n \n "+Uo(e)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+e[1]+";\n int cols = "+e[2]+";\n\n "+r+"\n\n setOutput(result);\n }\n "},Di=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=e.shape,s=i[1],l=i[2],c=[r&&s>1?o-1:o,r&&l>1?a-1:a],u=[r&&s>1?s-1:s,r&&l>1?l-1:l],p=c[0]/u[0],d=c[1]/u[1],_=1/p,h=1/d,f=2*Math.ceil(_)+2,y=2*Math.ceil(h)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+_+");\n const float invWidthScale = float("+h+");\n\n const int winHeight = int("+f+");\n const int winWidth = int("+y+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+l+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(o-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Ti=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var o=e[0],a=e[1],i=e[2],s=e[3];this.outputShape=[o,t,r,s];var l=[n&&t>1?a-1:a,n&&r>1?i-1:i],c=[n&&t>1?t-1:t,n&&r>1?r-1:r];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+l[0]/c[0]+",\n "+l[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},Oi=function(e,t,r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=e[0],a=e[1],i=e[2],s=e[3];this.outputShape=[o,t,r,s];var l=[n&&t>1?a-1:a,n&&r>1?i-1:i],c=[n&&t>1?t-1:t,n&&r>1?r-1:r];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+l[0]/c[0]+",\n "+l[1]/c[1]+",\n "+l[1]/c[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n "+i+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(r-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Ci=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=e.shape,s=i[1],l=i[2],c=[r&&s>1?o-1:o,r&&l>1?a-1:a],u=[r&&s>1?s-1:s,r&&l>1?l-1:l],p=c[0]/u[0],d=c[1]/u[1],_=1/p,h=1/d,f=2*Math.ceil(_)+2,y=2*Math.ceil(h)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+_+");\n const float invWidthScale = float("+h+");\n\n const int winHeight = int("+f+");\n const int winWidth = int("+y+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+l+") {\n continue;\n }\n\n float sourceFracRow =\n float("+c[0]+") *\n (float(dyR) / float("+u[0]+"));\n\n float sourceFracCol =\n float("+c[1]+") *\n (float(dyC) / float("+u[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+o+") - 1),\n "+r+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 1),\n "+r+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Li=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var o=e[0],a=e[1],i=e[2],s=e[3];this.outputShape=[o,t,r,s];var l=[n&&t>1?a-1:a,n&&r>1?i-1:i],c=[n&&t>1?t-1:t,n&&r>1?r-1:r],u=n?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+l[0]/c[0]+",\n "+l[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+u+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},Bi=function(e,t){this.variableNames=["x"];var r=e.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");if(this.outputShape=e,1!==r){var n=e.map((function(r,n){return function(r){return-1!==t.indexOf(r)&&1!==e[r]?e[r]+" - coords["+r+"] - 1":"coords["+r+"]"}(n)})).join(","),o=$o(r);this.userCode="\n void main() {\n "+o+" coords = getOutputCoords();\n setOutput(getX("+n+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "},Ii=function(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var r=e.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");this.outputShape=e;var n=zo("rc",r),o=n[r-1]+" + 1 < "+this.outputShape[r-1],a=n[r-2]+" + 1 < "+this.outputShape[r-2],i=$o(r);function s(r){var n=e.map((function(n,o){return function(r,n){return-1!==t.indexOf(r)&&1!==e[r]?e[r]+" - "+n[r]+" - 1":""+n[r]}(o,r)}));return"getChannel(getX("+n.join(",")+"), vec2("+n.slice(-2).join(",")+"))"}this.userCode=1===r?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+e[0]+" - rc - 1),\n "+e[0]+" - rc - 1);\n if("+o+"){\n result.g = getChannel(getX("+e[0]+" - (rc + 1) - 1),\n "+e[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(e){return s(e)}(n.slice())+";\n if("+o+"){\n result.g = "+function(e){return e[r-1]="("+e[r-1]+" + 1)",s(e)}(n.slice())+";\n }\n if("+a+") {\n result.b = "+function(e){return e[r-2]="("+e[r-2]+" + 1)",s(e)}(n.slice())+";\n if("+o+") {\n result.a = "+function(e){return e[r-1]="("+e[r-1]+" + 1)",e[r-2]="("+e[r-2]+" + 1)",s(e)}(n.slice())+";\n }\n }\n setOutput(result);\n }\n "},Ni=function(e,t,r,n,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=$o(o.length),l=$o(a.length),c="";1===r?c="i":2===r&&(c="i, j");var u="getIndices("+c+")",p="";1===n?p="i":2===n&&(p="i, coords[1]");var d="getUpdates("+p+")",_=t>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+o+");\n\n void main() {\n "+l+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+e+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+t+"; j++) {\n int index = round("+u+");\n flattenedIndex += index * "+_+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+d+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Mi=function(e,t){this.variableNames=["x","segmentIds"];var r=e.windowSize,n=e.batchSize,o=e.inSize,a=e.numSegments,i=a*Math.ceil(o/r);this.outputShape=[n,i];var s=4*Math.floor(r/4),l=r%4,c="\n sumValue += dot(values, segFilter);\n ",u="";o%r>0&&(u="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n ");var p="";o%r>0&&(p="\n if (inIdx < 0 || inIdx >= "+o+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+u+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+a+")) * float("+r+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+c+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===l)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(2===l)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(3===l)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+c+"\n }\n setOutput(sumValue);\n }\n "},Pi=function(e,t,r){var n,o;if(this.variableNames=["c","a","b"],this.outputShape=t,r>4)throw Error("Where for rank "+r+" is not yet supported");if(1===r)o="resRC",n="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],l=0;l= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "},Fi=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t,r=$o(this.rank),n="uniform int start["+this.rank+"];",o=function(e){if(1===e)return"sourceLoc";if(e<=6)return Wi.slice(0,e).map((function(e){return"sourceLoc."+e})).join(",");throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);t="\n "+r+" sourceLoc;\n "+r+" coords = getOutputCoords();\n "+e.map((function(e,t){return"sourceLoc."+Wi[t]+" = start["+t+"] + coords."+Wi[t]+";"})).join("\n")+"\n ",this.userCode="\n "+n+"\n void main() {\n "+t+"\n setOutput(getSource("+o+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(r,n){null==t.startLoc&&(t.startLoc=r.getUniformLocationNoThrow(n,"start"),null==t.startLoc)||r.gl.uniform1iv(t.startLoc,e)}},e}(),Wi=["x","y","z","w","u","v"],Hi=function(){function e(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;var t=$o(this.rank),r=zo("coords",this.rank),n=zo("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+n.slice(-2).join()+")",a="getChannel(getSource("+n.join()+"), "+o+")",i="\n result.x = "+a+";\n if (++"+r[this.rank-1]+" < "+e[this.rank-1]+") {\n ++"+n[this.rank-1]+";\n result.y = "+a+";\n --"+n[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+r[this.rank-1]+";\n if (++"+r[this.rank-2]+" < "+e[this.rank-2]+") {\n ++"+n[this.rank-2]+";\n result.z = "+a+";\n if (++"+r[this.rank-1]+" < "+e[this.rank-1]+") {\n ++"+n[this.rank-1]+";\n result.w = "+a+";\n }\n }\n ",l=this.rank<=4?"sourceLoc = coords +\n "+t+"("+e.map((function(e,t){return"start["+t+"]"})).join()+");":e.map((function(e,t){return n[t]+" = "+r[t]+" + start["+t+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+t+" coords = getOutputCoords();\n "+t+" sourceLoc;\n "+l+"\n vec4 result = vec4(0.);\n "+i+"\n "+s+"\n setOutput(result);\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(r,n){null==t.startLoc&&(t.startLoc=r.getUniformLocationNoThrow(n,"start"),null==t.startLoc)||r.gl.uniform1iv(t.startLoc,e)}},e}(),zi=function(e,t,r){this.variableNames=["x"],this.outputShape=r;var n=r.length,o=$o(r.length),a=$o(r.length),i="";if(1===n)i="coords * strides + begin";else{var s=0;i=r.map((function(e,t){return s++,1===r.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(s-1)+"] * strides["+t+"] + begin["+t+"]"})).join(",")}this.userCode="\n "+o+" begin = "+o+"("+e+");\n "+o+" strides = "+o+"("+t+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "},ji=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t,r){var n,o=Vi(t,r),a=Ui(e,o,r);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===qe.PACKED_2X2_FLOAT32?n=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):o===qe.PACKED_2X2_FLOAT16?n=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):o===qe.UNPACKED_FLOAT32?n=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):o===qe.UNPACKED_FLOAT16?n=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):o===qe.PACKED_4X1_UNSIGNED_BYTE&&(n=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(n),n},e.prototype.releaseTexture=function(e,t,r,n){if(null!=this.freeTextures){var o=Ui(t,Vi(r,n),n);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));for(var t in this.usedTextures)this.usedTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function Vi(e,t){if(e===Ke.UPLOAD)return qe.PACKED_2X2_FLOAT32;if(e===Ke.RENDER||null==e)return function(e){return f().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?qe.PACKED_2X2_FLOAT32:qe.UNPACKED_FLOAT32:e?qe.PACKED_2X2_FLOAT16:qe.UNPACKED_FLOAT16}(t);if(e===Ke.DOWNLOAD||e===Ke.PIXELS)return qe.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function Ui(e,t,r){return e[0]+"_"+e[1]+"_"+t+"_"+r}var Gi=function(e,t){this.variableNames=["A"];for(var r=new Array(e.length),n=0;n5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[],o=0;o6)throw Error("Transpose for rank "+t+" is not yet supported");for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t),o=0;o6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=$o(this.rank),a=Ho("rc",this.rank),i=new Array(this.rank);for(n=0;n0?[4,Promise.all(o)]:[3,2];case 1:return s=l.sent(),i.kernelMs=D(s),i.getExtraProfileInfo=function(){return s.map((function(e,t){return{name:a[t],ms:e}})).map((function(e){return e.name+": "+e.ms})).join(", ")},[3,3];case 2:i.kernelMs={error:"WebGL query timers are not supported in this environment."},l.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,i]}}))}))},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:le(),endMs:null}},t.prototype.endTimer=function(e){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=le(),e)},t.prototype.getQueryTime=function(e){return p(this,void 0,void 0,(function(){var t;return d(this,(function(r){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]}))}))},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var t=this.texData.get(e),r=t.texture,n=t.dtype,o=t.texShape,a=t.usage,i=t.isPacked,s=t.slice,l=s&&s.origDataId||e,c=this.dataRefCount.get(l);c>1?this.dataRefCount.set(l,c-1):(this.dataRefCount.delete(l),null!=r&&(this.numBytesInGPU-=this.computeBytes(o,n),this.textureManager.releaseTexture(r,o,a,i)));var u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return f().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=je.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,t){var r=this;return void 0===t&&(t=128),null!=this.getCPUBackend()&&e.every((function(e){return null==r.texData.get(e.dataId).texture&&e.sizef().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(e.length/2),a=this.concat(e.slice(0,o),t),i=this.concat(e.slice(o),t);return this.concat([a,i],t)}if(f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var s=new ba(e.map((function(e){return e.shape})),t);return this.compileAndRun(s,e)}var l=pr(e.map((function(e){return e.shape})),t),c=e.map((function(e){return e.as2D(-1,B(e.shape.slice(t)))})),u=new ga(c.map((function(e){return e.shape})));return this.compileAndRun(u,c).reshape(l)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,rs,e.dtype);var t=new Yi(e.shape,rs);return this.compileAndRun(t,[e])},t.prototype.batchMatMul=function(e,t,r,n){var o=r?e.shape[2]:e.shape[1],a=n?t.shape[1]:t.shape[2],i=r?e.shape[1]:e.shape[2],s=e.shape[0];if((1===o||1===a)&&i>1e3){r&&(e=e.transpose([0,2,1])),n&&(t=t.transpose([0,2,1]));var l=1===a?e:e.as3D(s,i,1),c=1===a?2:1,u=1===a?t.as3D(s,1,i):t;return this.multiply(l,u).sum(c,!0)}var p=Be(e.dtype,t.dtype),d=new gi(e.shape,[s,o,a],r,n);return this.compileAndRun(d,[e,t],p)},t.prototype.fusedBatchMatMul=function(e){var t=e.a,r=e.b,n=e.transposeA,o=e.transposeB,a=e.bias,i=e.activation,s=e.preluActivationWeights,l=n?t.shape[2]:t.shape[1],c=o?r.shape[1]:r.shape[2],u=t.shape[0],p=Be(t.dtype,r.dtype),d=null!=a,_=null!=s,h=i?hs(i,!0):null,f=new gi(t.shape,[u,l,c],n,o,d,h,_),y=[t,r];return a&&y.push(a),s&&y.push(s),this.compileAndRun(f,y,p)},t.prototype.multiply=function(e,t){if("complex64"===e.dtype){var r=this.texData.get(e.dataId),n=this.texData.get(t.dataId),o=new sa("return areal * breal - aimag * bimag;",e.shape,t.shape),a=new sa("return areal * bimag + aimag * breal;",e.shape,t.shape),i=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag),this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],s=this.compileAndRun(o,i),l=this.compileAndRun(a,i),c=this.complex(s,l);return s.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,ua,e.dtype);var u=new da(ua,e.shape,t.shape);return this.compileAndRun(u,[e,t],e.dtype)},t.prototype.batchNormalization=function(e,t,r,n,o,a){var i=[e,t,r],s=null;null!=a&&(s=a.shape,i.push(a));var l=null;if(null!=o&&(l=o.shape,i.push(o)),f().getBool("WEBGL_PACK_NORMALIZATION")){var c=new ia(e.shape,t.shape,r.shape,s,l,n);return this.compileAndRun(c,i)}var u=new aa(e.shape,t.shape,r.shape,s,l,n);return this.compileAndRun(u,i)},t.prototype.localResponseNormalization4D=function(e,t,r,n,o){var a=f().getBool("WEBGL_PACK_NORMALIZATION")?new fi(e.shape,t,r,n,o):new _i(e.shape,t,r,n,o);return this.compileAndRun(a,[e])},t.prototype.LRNGrad=function(e,t,r,n,o,a,i){var s=new hi(t.shape,n,o,a,i);return this.compileAndRun(s,[t,r,e])},t.prototype.tile=function(e,t){if("string"===e.dtype){var r=this.readSync(e.dataId).map((function(e){return pe(e)}));return Io(Jr(e.shape,e.dtype,r),t)}var n=new Gi(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.pad=function(e,t,r){var n=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Si(e.shape,t,r):new ki(e.shape,t,r);return this.compileAndRun(n,[e])},t.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var r=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qi(e.shape,t):new Ki(e.shape,t);return this.compileAndRun(r,[e])},t.prototype.gather=function(e,t,r){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,r);var n=new Ua(e.shape,t.size,r);return this.compileAndRun(n,[e,t])},t.prototype.batchToSpaceND=function(e,t,r){T(e.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var n=t.reduce((function(e,t){return e*t})),o=xn(e.shape,t,n),a=Dn(o.length,t.length),i=Tn(e.shape,t,n),s=On(r,t.length),l=Cn(i,r,t.length);return e.reshape(o).transpose(a).reshape(i).slice(s,l)},t.prototype.spaceToBatchND=function(e,t,r){T(e.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var n=t.reduce((function(e,t){return e*t})),o=[[0,0]];o.push.apply(o,r);for(var a=1+t.length;at||r===e?n=!0:r=re(e,r+1);return r}(i,o),l=new Mi({windowSize:s,inSize:i,batchSize:a,numSegments:o},t),c=this.compileAndRun(l,[e,r],n);return c.shape[1]===o?c:(r=Or(0,o).tile([i/s]),this.segOpCompute(c,t,r,n,o))},t.prototype.argMinMaxReduce=function(e,t,r){var n=[t];if(ir("arg"+r.charAt(0).toUpperCase()+r.slice(1),n,e.rank),!f().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var o=or(e.shape,n),a=o[0],i=B(o[1]),s=e.as2D(-1,i);return this.argReduce(s,r).reshape(a)}return this.argReducePacked(e,r)},t.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,"min")},t.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,"max")},t.prototype.cumsum=function(e,t,r,n){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var o=new La(e.shape,r,n);return this.compileAndRun(o,[e])},t.prototype.equal=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(equal(a, b));\n","bool");var r=new da("return float(a == b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.notEqual=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(notEqual(a, b));\n","bool");var r=new da("return float(a != b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(lessThan(a, b));\n","bool");var r=new da("return float(a < b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.lessEqual=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(lessThanEqual(a, b));\n","bool");var r=new da("return float(a <= b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(greaterThan(a, b));\n","bool");var r=new da("return float(a > b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.greaterEqual=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(greaterThanEqual(a, b));\n","bool");var r=new da("return float(a >= b);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.logicalNot=function(e){var t=new Yi(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},t.prototype.logicalAnd=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var r=new da("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.logicalOr=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var r=new da("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape);return this.compileAndRun(r,[e,t],"bool")},t.prototype.select=function(e,t,r){var n=new Pi(e.rank,t.shape,t.rank);return this.compileAndRun(n,[e,t,r],Be(t.dtype,r.dtype))},t.prototype.where=function(e){Jt("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return Mo(e.shape,t)},t.prototype.topk=function(e,t,r){return No(e.dataSync(),e.shape,e.dtype,t)},t.prototype.min=function(e,t){ir("min",t,e.rank);var r=or(e.shape,t),n=r[0],o=B(r[1]),a=e.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(n)},t.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new da("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.mod=function(e,t){var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new da("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);ir("max",t,e.rank);var r=or(e.shape,t),n=r[0],o=B(r[1]),a=e.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(n)},t.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new da("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.all=function(e,t){ir("all",t,e.rank);var r=or(e.shape,t),n=r[0],o=B(r[1]),a=e.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(n)},t.prototype.any=function(e,t){ir("any",t,e.rank);var r=or(e.shape,t),n=r[0],o=B(r[1]),a=e.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(n)},t.prototype.realDivide=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var r=new da("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",e.shape,t.shape);return this.compileAndRun(r,[e,t],"float32")},t.prototype.floorDiv=function(e,t){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var r=new da("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",e.shape,t.shape);return this.compileAndRun(r,[e,t],"int32")},t.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,la);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);var r=Be(e.dtype,t.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,la,r);var n=new da(la,e.shape,t.shape);return this.compileAndRun(n,[e,t],r)},t.prototype.packedUnaryOp=function(e,t,r){var n=new ps(e.shape,t);return this.compileAndRun(n,[e],r)},t.prototype.packedBinaryOp=function(e,t,r,n,o){void 0===o&&(o=!1);var a=new ha(r,e.shape,t.shape,o);return this.compileAndRun(a,[e,t],n)},t.prototype.complexSeparableBinaryOp=function(e,t,r){var n=this,o=this.texData.get(e.dataId),a=this.texData.get(t.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map((function(o){var a=o[0],i=o[1],s=n.makeComplexComponentTensorInfo(e,a),l=n.makeComplexComponentTensorInfo(t,i),c=new da(r,e.shape,t.shape);return n.compileAndRun(c,[s,l],Be(a.dtype,i.dtype))})),s=i[0],l=i[1],c=this.complex(s,l);return s.dispose(),l.dispose(),c},t.prototype.makeComplexComponentTensorInfo=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},t.prototype.addN=function(e){if(1===e.length)return e[0];if(e.length>f().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var t=Math.floor(e.length/2),r=this.addN(e.slice(0,t)),n=this.addN(e.slice(t));return this.addN([r,n])}var o=e.map((function(e){return e.dtype})).reduce((function(e,t){return Be(e,t)})),a=e.map((function(e){return e.shape})),i=f().getBool("WEBGL_PACK")?new Fo(e[0].shape,a):new Po(e[0].shape,a);return this.compileAndRun(i,e,o)},t.prototype.subtract=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,ca);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);var r=Be(e.dtype,t.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,ca,e.dtype);var n=new da(ca,e.shape,t.shape);return this.compileAndRun(n,[e,t],r)},t.prototype.pow=function(e,t){var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new da("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,t.shape),n=Be(e.dtype,t.dtype);return this.compileAndRun(r,[e,t],n)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ns,e.dtype);var t=new Yi(e.shape,ns);return this.compileAndRun(t,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,os,e.dtype);var t=new Yi(e.shape,os);return this.compileAndRun(t,[e])},t.prototype.sign=function(e){var t=new Yi(e.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(t,[e])},t.prototype.isNaN=function(e){var t=new Yi(e.shape,"return float(isnan(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.isInf=function(e){var t=new Yi(e.shape,"return float(isinf(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.isFinite=function(e){var t=new Yi(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.round=function(e){var t=new Yi(e.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(t,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,as,e.dtype);var t=new Yi(e.shape,as);return this.compileAndRun(t,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,is,e.dtype);var t=new Yi(e.shape,is);return this.compileAndRun(t,[e])},t.prototype.softmax=function(e,t){var r=z([t],e.shape),n=this.max(e,r),o=ar(n.shape,r),a=this.subtract(e,n.reshape(o)),i=this.exp(a),s=this.sum(i,r).reshape(o);return this.realDivide(i,s)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",e.dtype);var t=new Yi(e.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(t,[e])},t.prototype.log1p=function(e){var t=new Yi(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},t.prototype.sqrt=function(e){var t=new Yi(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var t=new Yi(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},t.prototype.reciprocal=function(e){var t=new Yi(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},t.prototype.relu=function(e){var t;return t=f().getBool("WEBGL_PACK")?new ps(e.shape,ls):new Yi(e.shape,$i),this.compileAndRun(t,[e])},t.prototype.relu6=function(e){var t;return t=f().getBool("WEBGL_PACK")?new ps(e.shape,cs):new Yi(e.shape,es),this.compileAndRun(t,[e])},t.prototype.prelu=function(e,t){var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha(_a,e.shape,t.shape):new da(pa,e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.elu=function(e){if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,us,e.dtype);var t=new Yi(e.shape,ts);return this.compileAndRun(t,[e])},t.prototype.eluDer=function(e,t){var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",e.shape,t.shape):new da("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.selu=function(e){var t=new Yi(e.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[e])},t.prototype.int=function(e){var t=new Yi(e.shape,"return float(int(x));");return this.compileAndRun(t,[e],"int32")},t.prototype.clip=function(e,t,r){var n,o=(n=f().getBool("WEBGL_PACK_CLIP")?new ya(e.shape):new fa(e.shape)).getCustomSetupFunc(t,r);return this.compileAndRun(n,[e],null,o)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Zi,e.dtype);var t=new Yi(e.shape,Zi);return this.compileAndRun(t,[e])},t.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),r=new ma(e.shape),n=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(r,n)},t.prototype.sigmoid=function(e){var t=new Yi(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},t.prototype.softplus=function(e){var t=new Yi(e.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(t,[e])},t.prototype.sin=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(t,[e])},t.prototype.cos=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(t,[e])},t.prototype.tan=function(e){var t=new Yi(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},t.prototype.asin=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(t,[e])},t.prototype.acos=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(t,[e])},t.prototype.atan=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e])},t.prototype.atan2=function(e,t){var r=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ha("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new da("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(r,[e,t])},t.prototype.sinh=function(e){var t=new Yi(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},t.prototype.cosh=function(e){var t=new Yi(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},t.prototype.tanh=function(e){var t=new Yi(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},t.prototype.asinh=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e])},t.prototype.acosh=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(t,[e])},t.prototype.atanh=function(e){var t=new Yi(e.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(t,[e])},t.prototype.erf=function(e){var t=new Yi(e.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(t,[e])},t.prototype.step=function(e,t){var r=new Yi(e.shape,function(e){return void 0===e&&(e=0),Ji+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(r,[e])},t.prototype.conv2dByMatMul=function(e,t,r,n,o,a){var i=e.shape,s=this.texData.get(e.dataId),l=r.inChannels,c=i[0]*i[1]*i[2],u=r.outChannels,p="channelsLast"===r.dataFormat,d=(1===c||1===u)&&l>1e3,_=i[2]%2!=0&&!!s.isPacked;if(d||!f().getBool("WEBGL_LAZILY_UNPACK")||!f().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!_){var h=p?i[0]*i[1]*i[2]:i[0]*i[2]*i[3],y=this.reshape(e,[1,h,r.inChannels]),m=this.reshape(t,[1,r.inChannels,r.outChannels]);return this.reshape(this.fusedBatchMatMul({a:y,b:m,transposeA:!1,transposeB:!1,bias:n,activation:o,preluActivationWeights:a}),r.outShape)}var g=p?i[0]*i[1]*(i[2]+1):i[0]*i[2]*(i[3]+1),b={dataId:e.dataId,shape:[1,g,r.inChannels],dtype:e.dtype},v=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,T(Nt(s.shape,b.shape),(function(){return"packed reshape "+s.shape+" to "+b.shape+" isn't free"}));var E=this.reshape(t,[1,r.inChannels,r.outChannels]),k=this.fusedBatchMatMul({a:b,b:E,transposeA:!1,transposeB:!1,bias:n,activation:o,preluActivationWeights:a}),S=this.texData.get(k.dataId);return T(S.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=v,S.shape=r.outShape,je.makeTensorFromDataId(k.dataId,r.outShape,k.dtype)},t.prototype.conv2dWithIm2Row=function(e,t,r,n,o,a){var i=r.filterWidth,s=r.filterHeight,l=r.inChannels,c=r.outWidth,u=r.outHeight,p="channelsLast"===r.dataFormat,d=i*s*l,_=u*c,h=[d,_],f=e.squeeze([0]),y=t.reshape([1,d,-1]),m=new di(h,f.shape,r),g=this.compileAndRun(m,[f]).reshape([1,h[0],h[1]]),b=null!=n,v=null!=a,E=o?hs(o,!0):null,k=new gi(g.shape,[1,_,r.outChannels],!0,!1,b,E,v),S=[g,y];n&&S.push(n),v&&S.push(a);var R=this.compileAndRun(k,S);return p?R.reshape([1,u,c,r.outChannels]):R.reshape([1,r.outChannels,u,c])},t.prototype.fusedConv2d=function(e){var t=e.input,r=e.filter,n=e.convInfo,o=e.bias,a=e.activation,i=e.preluActivationWeights;if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,r,n,o,a,i);if(f().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,r,n,o,a,i);var s=null!=o,l=null!=i,c=a?hs(a,!1):null,u=new xa(n,s,c,l),p=[t,r];return o&&p.push(o),i&&p.push(i),this.compileAndRun(u,p)},t.prototype.conv2d=function(e,t,r){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,t,r);if(f().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,t,r);var n=new xa(r);return this.compileAndRun(n,[e,t])},t.prototype.conv2dDerInput=function(e,t,r){var n=new ka(r);return this.compileAndRun(n,[e,t])},t.prototype.conv2dDerFilter=function(e,t,r){var n=new Ea(r);return this.compileAndRun(n,[e,t])},t.prototype.fusedDepthwiseConv2D=function(e){var t,r=e.input,n=e.filter,o=e.convInfo,a=e.bias,i=e.activation,s=e.preluActivationWeights,l=f().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,c=i?hs(i,l):null,u=[r,n],p=null!=a,d=null!=s;return p&&u.push(a),d&&u.push(s),l?(t=new Oa(o,p,c,d),this.compileAndRun(t,u)):(t=new Ta(o,p,c,d),this.compileAndRun(t,u))},t.prototype.depthwiseConv2D=function(e,t,r){var n;return f().getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels==1?(n=new Oa(r),this.compileAndRun(n,[e,t])):(n=new Ta(r),this.compileAndRun(n,[e,t]))},t.prototype.depthwiseConv2DDerInput=function(e,t,r){var n=new Aa(r);return this.compileAndRun(n,[e,t])},t.prototype.depthwiseConv2DDerFilter=function(e,t,r){var n=new wa(r);return this.compileAndRun(n,[e,t])},t.prototype.conv3d=function(e,t,r){var n=new Da(r);return this.compileAndRun(n,[e,t])},t.prototype.conv3dDerInput=function(e,t,r){var n=new Ra(r);return this.compileAndRun(n,[e,t])},t.prototype.conv3dDerFilter=function(e,t,r){var n=new Sa(r);return this.compileAndRun(n,[e,t])},t.prototype.maxPool=function(e,t){var r=new Ri(t,"max",!1);return this.compileAndRun(r,[e])},t.prototype.avgPool=function(e,t){var r=new Ri(t,"avg",!1);return this.compileAndRun(r,[e],"float32")},t.prototype.maxPoolBackprop=function(e,t,r,n){var o=new Ri(n,"max",!0),a=this.compileAndRun(o,[t]),i=new yi(n),s=this.compileAndRun(i,[e,a],t.dtype);return a.dispose(),s},t.prototype.avgPoolBackprop=function(e,t,r){var n=new na(r);return this.compileAndRun(n,[e],t.dtype)},t.prototype.cast=function(e,t){return mo(e,t,this)},t.prototype.unstack=function(e,t){for(var r=e.shape[t],n=new Array(e.rank-1),o=0,a=0;a1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+t}));var n=e.shape[0],o="NHWC"===r?e.shape[1]:e.shape[2],a="NHWC"===r?e.shape[2]:e.shape[3],i="NHWC"===r?e.shape[3]:e.shape[1],s=o*t,l=a*t,c=i/(t*t),u=new Ma("NHWC"===r?[n,s,l,c]:[n,c,s,l],t,r);return this.compileAndRun(u,[e])},t.prototype.split=function(e,t,r){return Bo(e,t,r)},t.prototype.scatterND=function(e,t,r){var n=Pn(0,e,r),o=n.sliceRank,a=n.numUpdates,i=n.sliceSize,s=n.strides,l=n.outputSize,c=[l/i,i],u=e.reshape([a,o]),p=t.reshape([a,i]);if(0===l)return go(yr([]),r);var d=gr(0),_=new Ni(a,o,u.rank,p.rank,s,c);return this.compileAndRun(_,[p,u,d]).reshape(r)},t.prototype.sparseToDense=function(e,t,r,n){var o=Pn(0,e,r),a=o.sliceRank,i=o.numUpdates,s=o.strides,l=o.outputSize,c=new Ni(i,a,e.rank,t.rank,s,[l,1],!1);return this.compileAndRun(c,[t,e,n]).reshape(r)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,t){var r=this.texData.get(e.dataId),n=new ja("return real * expR - imag * expI;",e.shape,t),o=new ja("return real * expI + imag * expR;",e.shape,t),a=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],i=this.compileAndRun(n,a),s=this.compileAndRun(o,a),l=this.complex(i,s).as2D(e.shape[0],e.shape[1]);return i.dispose(),s.dispose(),l},t.prototype.gatherND=function(e,t){var r=t.shape,n=r[r.length-1],o=Ln(e,t),a=o[0],i=o[1],s=o[2],l=o[3],c=t.reshape([i,n]),u=e.reshape([e.size/s,s]),p=new Ga(n,l,[i,s]);return this.compileAndRun(p,[u,c]).reshape(a)},t.prototype.fill=function(e,t,r){if("string"===(r=r||ee(t))){var n=U(r,B(e));return n.fill(t),je.makeTensor(n,e,r,this)}var o=new Va(e,t),a=o.getCustomSetupFunc(t);return this.compileAndRun(o,[],r,a)},t.prototype.onesLike=function(e){if("string"===e.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,"string"===e.dtype?"":0,e.dtype)},t.prototype.linspace=function(e,t,r){return bo(e,t,r)},t.prototype.makeTensorInfo=function(e,t){var r=this.write(null,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}},t.prototype.makeOutput=function(e,t){var r=this.makeTensorInfo(e,t).dataId;return je.makeTensorFromDataId(r,e,t,this)},t.prototype.unpackTensor=function(e){var t=new ds(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},t.prototype.packTensor=function(e){var t=new Ei(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,t){var r=[Ot(e.shape)].concat(Ct(e.shape)),n={dtype:e.dtype,shape:r,dataId:e.dataId},o=[Ot(t)].concat(Ct(t)),a=new xi(o,r),i=this.runWebGLProgram(a,[n],e.dtype,null,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}},t.prototype.decode=function(e){var t,r=this.texData.get(e),n=r.isPacked,o=r.shape,a=r.dtype,i=Lt(o);return t=n?new Na(i):new Ia(i),{dtype:a,shape:o,dataId:this.runWebGLProgram(t,[{shape:i,dtype:a,dataId:e}],a,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,t,r,n,o){var a=this;void 0===o&&(o=!1);var i=this.makeTensorInfo(e.outputShape,r),s=this.texData.get(i.dataId);if(e.packedOutput&&(s.isPacked=!0),e.outPackingScheme===Ge.DENSE){var l=$e(e.outputShape);s.texShape=l.map((function(e){return 2*e}))}if(null!=e.outTexUsage&&(s.usage=e.outTexUsage),0===B(i.shape))return s.values=V(i.dtype,0),i;var c=[],u=t.map((function(t){if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var r=a.texData.get(t.dataId);if(null==r.texture){if(!e.packedInputs&&B(t.shape)<=f().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:r.values};e.packedInputs&&(r.isPacked=!0,r.shape=t.shape)}else if(!!r.isPacked!=!!e.packedInputs)t=r.isPacked?a.unpackTensor(t):a.packTensor(t),c.push(t),r=a.texData.get(t.dataId);else if(r.isPacked&&!Nt(r.shape,t.shape)){var n=t,o=t.shape;t.shape=r.shape,t=a.packedReshape(t,o),c.push(t),r=a.texData.get(t.dataId),n.shape=o}return a.uploadToGPU(t.dataId),{shape:t.shape,texData:r,isUniform:!1}}));this.uploadToGPU(i.dataId);var p,d={shape:i.shape,texData:s,isUniform:!1},_=function(e,t,r){var n="";t.concat(r).forEach((function(e){var t=null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0,r=e.isUniform?"uniform":e.texData.texShape;n+=e.shape+"_"+r+"_"+t}));var o=e.userCode;return e.constructor.name+"_"+n+"_"+o}(e,u,d),h=this.getAndSaveBinary(_,(function(){return function(e,t,r,n){var o=t.userCode,a=r.map((function(e,r){var n={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(n.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[r],shapeInfo:n}})),i=a.map((function(e){return e.shapeInfo})),s={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},l=Ko(a,s,o,t.packedInputs),c=e.createProgram(l),u=null,p=e.getUniformLocation(c,"NAN",!1);1===f().getNumber("WEBGL_VERSION")&&(u=e.getUniformLocation(c,"INFINITY",!1));for(var d={},_=0;_0)return 32}return 16}))),this.floatPrecisionValue},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var t,r=this.texData.get(e),n=r.shape,o=r.dtype,a=r.values,i=r.texture,s=r.usage,l=r.isPacked;if(null==i){var c,u=null!=this.activeTimers;u&&(c=le());var p=r.texShape;if(null==p&&(p=Bt(n,l),r.texShape=p),null!=a){var d=Lt(n),_=void 0,h=p[1],f=p[0],y=a instanceof Uint8Array;l?(h=(t=et(p[0],p[1]))[0],f=t[1],_=new za(d,[f,h],y)):_=new Ha(d,[f,h],y);var m=this.makeTensorInfo([f,h],o);this.texData.get(m.dataId).usage=y?Ke.PIXELS:Ke.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(m.dataId),h,f,a);var g=this.runWebGLProgram(_,[m],o,null,!0),b=this.texData.get(g.dataId);r.texture=b.texture,r.texShape=b.texShape,r.isPacked=b.isPacked,r.usage=b.usage,this.disposeData(m.dataId),this.texData.delete(g.dataId),r.values=null,u&&(this.uploadWaitMs+=le()-c)}else{var v=this.acquireTexture(p,s,o,l);r.texture=v}}},t.prototype.convertAndCacheOnCPU=function(e,t){var r=this.texData.get(e),n=r.dtype;return this.releaseGPUData(e),null!=t&&(r.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var r="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),n=0;n1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,t,n)},t.prototype.computeBytes=function(e,t){return e[0]*e[1]*Q(t)},t}($n);Ve()&&je.registerBackend("webgl",(function(){return new fs}),2);var ys=dr({square_:function(e){var t=er(e,"x","square"),r=[t];return je.runKernelFunc((function(e,r){return r([t]),e.square(t)}),{x:t},null,"Square",{},r,[])}}),ms="SquaredDifference";t.square=ys;var gs=dr({squaredDifference_:function(e,t){var r,n=er(e,"a","squaredDifference"),o=er(t,"b","squaredDifference");r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape);var a={a:n,b:o},i=[n,o];return je.runKernelFunc((function(e,t){var r=e.squaredDifference(n,o);return t([n,o]),r}),a,(function(e,t){var r=t[0],n=t[1],o=gr(2);return{a:function(){return e.mul(r.sub(n).mul(o))},b:function(){return e.mul(n.sub(r).mul(o))}}}),ms,{},i,[])}});t.squaredDifference=gs;var bs=dr({abs_:function(e){var t=er(e,"x","abs");return"complex64"===t.dtype?je.runKernelFunc((function(e){return e.complexAbs(t)}),{$x:t}):je.runKernelFunc((function(e,r){var n=e.abs(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return e.mul(r.toFloat().step(-1))}}}),"Abs")}}),vs=dr({acos_:function(e){var t=er(e,"x","acos");return je.runKernelFunc((function(e,r){var n=e.acos(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.divStrict(gr(1).sub(r.toFloat().square()).sqrt()).neg()}}}))}}),Es=dr({acosh_:function(e){var t=er(e,"x","acosh");return je.runKernelFunc((function(e,r){var n=e.acosh(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.divStrict(r.toFloat().square().sub(1).sqrt())}}}))}}),ks=dr({asin_:function(e){var t=er(e,"x","asin");return je.runKernelFunc((function(e,r){var n=e.asin(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.divStrict(gr(1).sub(r.toFloat().square()).sqrt())}}}))}}),Ss=dr({asinh_:function(e){var t=er(e,"x","asinh");return je.runKernelFunc((function(e,r){var n=e.asinh(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.divStrict(gr(1).add(r.toFloat().square()).sqrt())}}}))}}),Rs=dr({atan_:function(e){var t=er(e,"x","atan");return je.runKernelFunc((function(e,r){var n=e.atan(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(r.toFloat().square().add(1))}}}))}}),ws=dr({atanh_:function(e){var t=er(e,"x","atanh");return je.runKernelFunc((function(e,r){var n=e.atanh(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(gr(1).sub(r.toFloat().square()))}}}))}}),As=dr({ceil_:function(e){var t=er(e,"x","ceil");return je.runKernelFunc((function(e){return e.ceil(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),xs=dr({clipByValue_:function(e,t,r){var n=er(e,"x","clipByValue");T(t<=r,(function(){return"Error in clip: min ("+t+") must be less than or equal to max ("+r+")."}));var o=[n],a={min:t,max:r};return je.runKernelFunc((function(e,o){var a=e.clip(n,t,r);return o([n]),a}),{x:n},(function(e,n){var o=n[0];return{x:function(){return e.where(o.greaterEqual(t).logicalAnd(o.lessEqual(r)),Lr(e))}}}),"ClipByValue",a,o)}}),Ds=dr({cos_:function(e){var t=er(e,"x","cos"),r=[t];return je.runKernelFunc((function(e,r){var n=e.cos(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return r.toFloat().sin().neg().mul(e)}}}),"Cos",{},r)}}),Ts=dr({cosh_:function(e){var t=er(e,"x","cosh");return je.runKernelFunc((function(e,r){var n=e.cosh(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return r.toFloat().sinh().mulStrict(e)}}}))}}),Os=dr({erf_:function(e){var t=er(e,"x","erf");return T("int32"===t.dtype||"float32"===t.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===t.dtype&&(t=t.toFloat()),je.runKernelFunc((function(e,r){var n=e.erf(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.mul(r.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),Cs=dr({exp_:function(e){var t=er(e,"x","exp");return je.runKernelFunc((function(e,r){var n=e.exp(t);return r([n]),n}),{x:t},(function(e,t){return{x:function(){return e.mulStrict(t[0])}}}),"Exp",{},[],[!0])}}),Ls=dr({expm1_:function(e){var t=er(e,"x","expm1");return je.runKernelFunc((function(e,r){var n=e.expm1(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.mul(r.exp())}}}))}}),Bs=dr({floor_:function(e){var t=er(e,"x","floor");return je.runKernelFunc((function(e){return e.floor(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Is=dr({log_:function(e){var t=er(e,"x","log"),r=[t];return je.runKernelFunc((function(e,r){var n=e.log(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return e.div(r.toFloat())}}}),"Log",{},r)}}),Ns=dr({log1p_:function(e){var t=er(e,"x","log1p");return je.runKernelFunc((function(e,r){var n=e.log1p(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(r.add(1))}}}))}}),Ms=dr({logSigmoid_:function(e){var t=er(e,"x","logSigmoid");return je.runKernelFunc((function(e,r){var n=e.softplus(t.neg()).neg();return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.mul(r.neg().sigmoid())}}}))}}),Ps=dr({neg_:function(e){var t=er(e,"x","neg"),r=[t];return je.runKernelFunc((function(e){return e.neg(t)}),{x:t},(function(e){return{x:function(){return e.neg()}}}),"Neg",{},r)}}),Fs=dr({reciprocal_:function(e){var t=er(e,"x","reciprocal");return je.runKernelFunc((function(e,r){var n=e.reciprocal(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(r.square().neg())}}}))}}),Ws=dr({round_:function(e){var t=er(e,"x","round");return je.runKernelFunc((function(e){return e.round(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Hs=dr({rsqrt_:function(e){var t=er(e,"x","rsqrt"),r=[t];return je.runKernelFunc((function(e,r){var n=e.rsqrt(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return e.div(r.pow(1.5).mul(2)).neg()}}}),"Rsqrt",{},r)}}),zs=dr({sigmoid_:function(e){var t=er(e,"x","sigmoid");return je.runKernelFunc((function(e,r){var n=e.sigmoid(t);return r([n]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return e.mul(r.mul(gr(1).sub(r)))}}}),"Sigmoid")}}),js=dr({sign_:function(e){var t=er(e,"x","sign");return je.runKernelFunc((function(e){return e.sign(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Vs=dr({isNaN_:function(e){var t=er(e,"x","isNaN");return je.runKernelFunc((function(e){return e.isNaN(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Us=dr({isInf_:function(e){var t=er(e,"x","isInf");return je.runKernelFunc((function(e){return e.isInf(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Gs=dr({isFinite_:function(e){var t=er(e,"x","isFinite");return je.runKernelFunc((function(e){return e.isFinite(t)}),{$x:t},(function(e){return{$x:function(){return Lr(e)}}}))}}),Ks=dr({sin_:function(e){var t=er(e,"x","sin"),r=[t];return je.runKernelFunc((function(e,r){var n=e.sin(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return r.toFloat().cos().mul(e)}}}),"Sin",{},r)}}),qs=dr({sinh_:function(e){var t=er(e,"x","sinh");return je.runKernelFunc((function(e,r){var n=e.sinh(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return r.toFloat().cosh().mulStrict(e)}}}))}}),Xs=dr({softplus_:function(e){var t=er(e,"x","softplus");return je.runKernelFunc((function(e,r){var n=e.softplus(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.mul(r.sigmoid())}}}))}}),Qs=dr({sqrt_:function(e){var t=er(e,"x","sqrt");return je.runKernelFunc((function(e,r){var n=e.sqrt(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(r.toFloat().sqrt().mul(2))}}}))}}),Ys=dr({step_:function(e,t){void 0===t&&(t=0);var r=er(e,"x","step");return je.runKernelFunc((function(e){return e.step(r,t)}),{$x:r},(function(e){return{$x:function(){return Lr(e)}}}))}}),Js=dr({tan_:function(e){var t=er(e,"x","tan");return je.runKernelFunc((function(e,r){var n=e.tan(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){return e.div(r.cos().square())}}}))}}),Zs=dr({tanh_:function(e){var t=er(e,"x","tanh");return je.runKernelFunc((function(e,r){var n=e.tanh(t);return r([n]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return gr(1).sub(r.square()).mulStrict(e)}}}),"Tanh",{},null,[!0])}});function $s(e,t,r,n,o,a){var i,s,l=er(e,"x","batchNorm"),c=er(t,"mean","batchNorm"),u=er(r,"variance","batchNorm");return null!=o&&(i=er(o,"scale","batchNorm")),null!=n&&(s=er(n,"offset","batchNorm")),T(2===l.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+l.rank+"."})),T(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),T(2===u.rank||1===u.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+u.rank+"."})),null!=i&&T(2===i.rank||1===i.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),rl(l,c,u,s,i,a)}function el(e,t,r,n,o,a){var i,s,l=er(e,"x","batchNorm"),c=er(t,"mean","batchNorm"),u=er(r,"variance","batchNorm");return null!=o&&(i=er(o,"scale","batchNorm")),null!=n&&(s=er(n,"offset","batchNorm")),T(3===l.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+l.rank+"."})),T(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),T(3===u.rank||1===u.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+u.rank+"."})),null!=i&&T(3===i.rank||1===i.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),rl(l,c,u,s,i,a)}function tl(e,t,r,n,o,a){var i,s,l=er(e,"x","batchNorm"),c=er(t,"mean","batchNorm"),u=er(r,"variance","batchNorm");return null!=o&&(i=er(o,"scale","batchNorm")),null!=n&&(s=er(n,"offset","batchNorm")),T(4===l.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+l.rank+"."})),T(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),T(4===u.rank||1===u.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+u.rank+"."})),null!=i&&T(4===i.rank||1===i.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),rl(l,c,u,s,i,a)}function rl(e,t,r,n,o,a){null==a&&(a=.001);var i,s,l,c=er(e,"x","batchNorm"),u=er(t,"mean","batchNorm"),p=er(r,"variance","batchNorm");null!=o&&(i=er(o,"scale","batchNorm")),null!=n&&(s=er(n,"offset","batchNorm")),T(u.rank===p.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),T(null==s||u.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),T(null==i||u.rank===i.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."})),l=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var d=[c,u,p,i];return je.runKernelFunc((function(e,t){var r=e.batchNormalization(l,nl(u),nl(p),a,nl(i),nl(s));return t([c,u,p,i]),r}),{x:c,mean:u,variance:p,scale:i,offset:s},(function(e,t){var r=t,n=r[0],o=r[1],i=r[2],s=r[3],c=null==s?gr(1):s,u=ro(o.shape,l.shape),p=[];if(1===o.rank){for(var d=0;d0&&(t=t.sum(r)),t.reshape(n.shape)},b:function(){var t=e,r=ro(o.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(o.shape)}}}),"Add")}}),vl=dr({addN_:function(e){T(Array.isArray(e),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),T(e.length>=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length}));var t=e.map((function(e,t){return er(e,"tensors"+t,"addN")})),r=t[0];t.forEach((function(e){if(e.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((function(e){if(!I(e.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var n=t;return je.runKernelFunc((function(e){return e.addN(t)}),n,(function(e){var r={};return t.forEach((function(t,n){r[n]=function(){return e.clone()}})),r}),"AddN")}}),El=dr({addStrict_:function(e,t){var r=er(e,"a","addStrict"),n=er(t,"b","addStrict");return O(r.shape,n.shape,"Error in addStrict: "),r.add(n)}}),kl=dr({atan2_:function(e,t){var r,n=er(e,"a","atan2"),o=er(t,"b","atan2");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape);return je.runKernelFunc((function(e,t){var r=e.atan2(n,o);return t([n,o]),r}),{$a:n,$b:o},(function(e,t){var r=t[0],n=t[1];return{$a:function(){var t=bl(r.square(),n.square()),o=e.mul(n.div(t)),i=ro(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)},$b:function(){var t=bl(r.square(),n.square()),o=Ps(e.mul(r.div(t))),i=ro(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)}}}))}}),Sl=dr({div_:function(e,t){var r,n=er(e,"a","div"),o=er(t,"b","div");if(r=Ne(n,o),n=r[0],o=r[1],"int32"===n.dtype&&"int32"===o.dtype)return Al(n,o);var a=no(n.shape,o.shape);return je.runKernelFunc((function(e,t){var r=e.realDivide(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){var t=e.div(n.toFloat()),o=ro(r.shape,a);return o.length>0?t.sum(o).reshape(r.shape):t},b:function(){var t=e.mul(r.toFloat()),o=ro(n.shape,a);o.length>0&&(t=t.sum(o).reshape(n.shape));var i=n.square();return t.div(i.toFloat()).neg()}}}),"Div")}}),Rl=dr({divNoNan_:function(e,t){var r,n=er(e,"a","div"),o=er(t,"b","div");n=(r=Ne(n,o))[0],o=r[1];var a=Sl(n,o),i=Lr(a),s=o.equal(i);return ml(s,i,a)}}),wl=dr({divStrict_:function(e,t){var r=er(e,"a","div"),n=er(t,"b","div");return O(r.shape,n.shape,"Error in divideStrict: "),r.div(n)}}),Al=dr({floorDiv_:function(e,t){var r,n=er(e,"a","floorDiv"),o=er(t,"b","floorDiv");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape);return je.runKernelFunc((function(e,t){var r=e.floorDiv(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){var t=e.div(n.toFloat()),o=ro(r.shape,a);return o.length>0?t.sum(o).reshape(r.shape):t},b:function(){var t=e.mul(r.toFloat()),o=ro(n.shape,a);o.length>0&&(t=t.sum(o).reshape(n.shape));var i=n.square();return t.div(i.toFloat()).neg()}}}),"FloorDiv")}}),xl=dr({maximum_:function(e,t){var r,n=er(e,"a","maximum"),o=er(t,"b","maximum");return r=Ne(n,o),n=r[0],o=r[1],"bool"===n.dtype&&(n=n.toInt(),o=o.toInt()),no(n.shape,o.shape),je.runKernelFunc((function(e,t){var r=e.maximum(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){return e.mul(r.greaterEqual(n).toFloat())},b:function(){return e.mul(r.less(n).toFloat())}}}),"Maximum")}}),Dl=dr({maximumStrict_:function(e,t){var r=er(e,"a","maximumStrict"),n=er(t,"b","maximumStrict");return O(r.shape,n.shape,"Error in maximumStrict: "),r.maximum(n)}}),Tl=dr({minimum_:function(e,t){var r,n=er(e,"a","minimum"),o=er(t,"b","minimum");return r=Ne(n,o),n=r[0],o=r[1],"bool"===n.dtype&&(n=n.toInt(),o=o.toInt()),no(n.shape,o.shape),je.runKernelFunc((function(e,t){var r=e.minimum(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){return e.mul(r.lessEqual(n).toFloat())},b:function(){return e.mul(r.greater(n).toFloat())}}}),"Minimum")}}),Ol=dr({minimumStrict_:function(e,t){var r=er(e,"a","minimumStrict"),n=er(t,"b","minimumStrict");return O(r.shape,n.shape,"Error in minimumStrict: "),r.minimum(n)}}),Cl=dr({mod_:function(e,t){var r,n=er(e,"a","mod"),o=er(t,"b","mod");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape);return je.runKernelFunc((function(e,t){var r=e.mod(n,o);return t([n,o]),r}),{$a:n,$b:o},(function(e,t){var r=t[0],n=t[1];return{$a:function(){var t=ro(r.shape,a);return t.length>0?e.sum(t).reshape(r.shape):e},$b:function(){var t=e.mul(r.div(n).floor().neg()),o=ro(n.shape,a);return o.length>0?t.sum(o).reshape(n.shape):t}}}))}}),Ll=dr({modStrict_:function(e,t){var r=er(e,"a","modStrict"),n=er(t,"b","modStrict");return O(r.shape,n.shape,"Error in modStrict: "),r.mod(n)}}),Bl=dr({mul_:function(e,t){var r,n=er(e,"a","mul"),o=er(t,"b","mul");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape);return je.runKernelFunc((function(e,t){var r=e.multiply(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){var t=e.mul(n.toFloat()),o=ro(r.shape,a);return o.length>0?t.sum(o).reshape(r.shape):t},b:function(){var t=e.mul(r.toFloat()),o=ro(n.shape,a);return o.length>0?t.sum(o).reshape(n.shape):t}}}),"Mul")}}),Il=dr({mulStrict_:function(e,t){var r=er(e,"a","mul"),n=er(t,"b","mul");return O(r.shape,n.shape,"Error in multiplyStrict: "),r.mul(n)}}),Nl=dr({pow_:function(e,t){var r,n=er(e,"base","pow"),o=er(t,"exp","pow");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape),i=[n,o];return je.runKernelFunc((function(e,t){var r=e.pow(n,o);return t([n,o,r]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1],o=t[2];return{a:function(){var t=n.toFloat(),o=e.mul(t.mul(r.pow(t.sub(gr(1))))),i=ro(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)},b:function(){var t=r.greater(0),i=r.log().where(t,Lr(r)),s=e.mul(o.mul(i)),l=ro(n.shape,a);return l.length>0&&(s=s.sum(l)),s.reshape(n.shape)}}}),"Pow",{},i,[!0])}}),Ml=dr({powStrict_:function(e,t){return O(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),Pl=dr({squaredDifferenceStrict_:function(e,t){var r=er(e,"a","squaredDifferenceStrict"),n=er(t,"b","squaredDifferenceStrict");return O(r.shape,n.shape,"Error in squaredDifferenceStrict: "),r.squaredDifference(n)}}),Fl=dr({sub_:function(e,t){var r,n=er(e,"a","sub"),o=er(t,"b","sub");r=Ne(n,o),n=r[0],o=r[1];var a=no(n.shape,o.shape);return je.runKernelFunc((function(e){return e.subtract(n,o)}),{a:n,b:o},(function(e){return{a:function(){var t=e,r=ro(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},b:function(){var t=e,r=ro(o.shape,a);return r.length>0&&(t=t.sum(r)),t.neg().reshape(o.shape)}}}),"Sub")}}),Wl=dr({subStrict_:function(e,t){var r=er(e,"a","subStrict"),n=er(t,"b","subStrict");return O(r.shape,n.shape,"Error in subStrict: "),r.sub(n)}});t.subStrict=Wl,t.sub=Fl,t.squaredDifferenceStrict=Pl,t.powStrict=Ml,t.pow=Nl,t.mulStrict=Il,t.mul=Bl,t.modStrict=Ll,t.mod=Cl,t.minimumStrict=Ol,t.minimum=Tl,t.maximumStrict=Dl,t.maximum=xl,t.floorDiv=Al,t.divStrict=wl,t.divNoNan=Rl,t.div=Sl,t.atan2=kl,t.addStrict=El,t.addN=vl,t.add=bl;var Hl=dr({equal_:function(e,t){var r,n=er(e,"a","equal"),o=er(t,"b","equal");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e){return e.equal(n,o)}),{$a:n,$b:o})}}),zl=dr({equalStrict_:function(e,t){var r=er(e,"a","equalStrict"),n=er(t,"b","equalStrict");return O(r.shape,n.shape,"Error in equalStrict: "),r.equal(n)}}),jl=dr({greater_:function(e,t){var r,n=er(e,"a","greater"),o=er(t,"b","greater");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e){return e.greater(n,o)}),{a:n,b:o},null,"Greater")}}),Vl=dr({greaterEqual_:function(e,t){var r,n=er(e,"a","greaterEqual"),o=er(t,"b","greaterEqual");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e,t){var r=e.greaterEqual(n,o);return t([n,o]),r}),{a:n,b:o},(function(e,t){var r=t[0],n=t[1];return{a:function(){return Lr(r)},b:function(){return Lr(n)}}}),"GreaterEqual")}}),Ul=dr({greaterEqualStrict_:function(e,t){var r=er(e,"a","greaterEqualStrict"),n=er(t,"b","greaterEqualStrict");return O(r.shape,n.shape,"Error in greaterEqualStrict: "),r.greaterEqual(n)}}),Gl=dr({greaterStrict_:function(e,t){var r=er(e,"a","greaterStrict"),n=er(t,"b","greaterStrict");return O(r.shape,n.shape,"Error in greaterStrict: "),r.greater(n)}}),Kl=dr({less_:function(e,t){var r,n=er(e,"a","less"),o=er(t,"b","less");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e){return e.less(n,o)}),{a:n,b:o},null,"Less")}}),ql=dr({lessEqual_:function(e,t){var r,n=er(e,"a","lessEqual"),o=er(t,"b","lessEqual");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e,t){var r=e.lessEqual(n,o);return t([n,o]),r}),{a:n,b:o},null,"LessEqual")}}),Xl=dr({lessEqualStrict_:function(e,t){var r=er(e,"a","lessEqualStrict"),n=er(t,"b","lessEqualStrict");return O(r.shape,n.shape,"Error in lessEqualStrict: "),r.lessEqual(n)}}),Ql=dr({lessStrict_:function(e,t){var r=er(e,"a","lessStrict"),n=er(t,"b","lessStrict");return O(r.shape,n.shape,"Error in lessStrict: "),r.less(n)}}),Yl=dr({notEqual_:function(e,t){var r,n=er(e,"a","notEqual"),o=er(t,"b","notEqual");return r=Ne(n,o),n=r[0],o=r[1],no(n.shape,o.shape),je.runKernelFunc((function(e){return e.notEqual(n,o)}),{a:n,b:o},null,"NotEqual")}}),Jl=dr({notEqualStrict_:function(e,t){var r=er(e,"a","notEqualStrict"),n=er(t,"b","notEqualStrict");return O(r.shape,n.shape,"Error in notEqualStrict: "),r.notEqual(n)}});function Zl(e,t){for(var r=[],n=e;n0,(function(){return"mask cannot be scalar"})),O(s.slice(a,a+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=a;c=2&&i.rank>=2&&a.rank===i.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."})),T(I(p,d),(function(){return"Error in matMul: outer dimensions ("+p+") and ("+d+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."})),T(s===l,(function(){return"Error in matMul: inner shapes ("+s+") and ("+l+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+r+" and transposeB="+n+" must match."}));var f=a.shape.slice(0,-2).concat([c,u]),y=r?a.as3D(_,s,c):a.as3D(_,c,s),m=n?i.as3D(h,u,l):i.as3D(h,l,u),g={transposeA:r,transposeB:n};return je.runKernelFunc((function(e,t){var o=e.batchMatMul(y,m,r,n);return t([y,m]),o}),{a:y,b:m},(function(e,t){var o=t,a=o[0],i=o[1];return r||n?!r&&n?{a:function(){return e.matMul(i,!1,!1)},b:function(){return e.matMul(a,!0,!1)}}:r&&!n?{a:function(){return i.matMul(e,!1,!0)},b:function(){return a.matMul(e,!1,!1)}}:{a:function(){return i.matMul(e,!0,!0)},b:function(){return e.matMul(a,!0,!0)}}:{a:function(){return e.matMul(i,!1,!0)},b:function(){return a.matMul(e,!0,!1)}}}),"BatchMatMul",g).reshape(f)}}),gc=dr({dot_:function(e,t){var r=er(e,"t1","dot"),n=er(t,"t2","dot");T(!(1!==r.rank&&2!==r.rank||1!==n.rank&&2!==n.rank),(function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+r.rank+" and "+n.rank+"."}));var o=1===r.rank?r.size:r.shape[1],a=1===n.rank?n.size:n.shape[0];return T(o===a,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."})),1===r.rank&&1===n.rank?r.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():1===r.rank&&2===n.rank?r.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():2===r.rank&&1===n.rank?r.matMul(n.as2D(-1,1)).as1D():r.matMul(n.as2D(n.shape[0],n.shape[1]))}}),bc=dr({outerProduct_:function(e,t){var r=er(e,"v1","outerProduct"),n=er(t,"v2","outerProduct");return T(1===r.rank&&1===n.rank,(function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+r.rank+" and "+n.rank+"."})),r.as2D(-1,1).matMul(n.as2D(1,-1))}});t.outerProduct=bc,t.dot=gc,t.matMul=mc;var vc=dr({reverse_:function(e,t){var r=er(e,"x","reverse");if(0===r.rank)return r.clone();var n=z(t,r.shape);return je.runKernelFunc((function(e){return e.reverse(r,n)}),{$x:r},(function(e){return{$x:function(){return e.reverse(n)}}})).reshapeAs(r)}}),Ec=dr({reverse1d_:function(e){var t=er(e,"x","reverse");return T(1===t.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."})),vc(t,0)}}),kc=dr({reverse2d_:function(e,t){var r=er(e,"x","reverse");return T(2===r.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+r.rank+"."})),vc(r,t)}}),Sc=dr({reverse3d_:function(e,t){var r=er(e,"x","reverse");return T(3===r.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+r.rank+"."})),vc(r,t)}}),Rc=dr({reverse4d_:function(e,t){var r=er(e,"x","reverse");return T(4===r.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+r.rank+"."})),vc(r,t)}});function wc(e,t,r,n,o,a){var i=er(e,"x","maxPool"),s=i,l=!1;3===i.rank&&(l=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==n&&(n=[1,1]),T(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),T(fo(r,n),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+n+"'"})),null!=a&&T(N(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=oo(s.shape,t,r,n,o,a);if(1===c.filterWidth&&1===c.filterHeight&&I(c.inShape,c.outShape))return i.clone();var u=[s],p=je.runKernelFunc((function(e,t){var r=e.maxPool(s,c);return t([s,r]),r}),{x:s},(function(e,a){var i=a[0],s=a[1];return{x:function(){return function(e,t,r,n,o,a,i,s){var l=er(e,"dy","maxPoolBackprop"),c=er(t,"input","maxPoolBackprop"),u=er(r,"output","maxPoolBackprop");T(c.rank===l.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+l.rank+")"})),null==a&&(a=[1,1]),T(fo(o,a),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),T(4===l.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."})),T(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."}));var p=oo(c.shape,n,o,a,i,s);return je.runKernelFunc((function(e){return e.maxPoolBackprop(l,c,u,p)}),{$dy:l,$input:c})}(e,i,s,t,r,n,o)}}}),"MaxPool",c,u);return l?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function Ac(e,t,r,n,o,a){var i=er(e,"x","avgPool","float32");null==n&&(n=[1,1]),T(fo(r,n),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+n+"'"}));var s=i,l=!1;3===i.rank&&(l=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=a&&T(N(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=oo(s.shape,t,r,n,o,a);if(1===c.filterWidth&&1===c.filterHeight&&I(c.inShape,c.outShape))return i.clone();var u=je.runKernelFunc((function(e){return e.avgPool(s,c)}),{x:s},(function(e){return{x:function(){return function(e,t,r,n,o,a){var i=er(e,"dy","avgPoolBackprop"),s=er(t,"input","avgPoolBackprop");T(s.rank===i.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"})),null==o&&(o=[1,1]),T(fo(n,o),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}));var l=s,c=i,u=!1;3===s.rank&&(u=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),T(4===l.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}));var p=oo(l.shape,r,n,o,a),d=je.runKernelFunc((function(e){return e.avgPoolBackprop(c,l,p)}),{dy4D:c,input4D:l});return u?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}(e,s,t,r,n,o)}}}),"AvgPool",c);return u=u.cast(i.dtype),l?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}t.reverse4d=Rc,t.reverse3d=Sc,t.reverse2d=kc,t.reverse1d=Ec,t.reverse=vc;var xc=dr({maxPool_:function(e,t,r,n,o){return wc(e,t,r,1,n,o)}}),Dc=dr({avgPool_:function(e,t,r,n,o){return Ac(e,t,r,1,n,o)}}),Tc=dr({pool_:function(e,t,r,n,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===n&&(n="valid");var i=er(e,"x","maxPool"),s=i,l=!1;3===i.rank&&(l=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(fo(a,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"}));var c,u=oo(s.shape,t,a,o,n),p=[u.dilationHeight,u.dilationWidth];c="same"===n?function(e,t){var r=e.map((function(e,r){return e+(e-1)*(t[r]-1)})).map((function(e){return e-1})),n=r.map((function(e){return Math.floor(e/2)})),o=r.map((function(e,t){return e-n[t]}));return r.map((function(e,t){return[n[t],o[t]]}))}([u.filterHeight,u.filterWidth],p):[[0,0],[0,0]];var d=1===p[0]&&1===p[1],_=function(e,t,r){var n=r.map((function(e){return e[0]})),o=r.map((function(e){return e[1]})),a=e.concat(n,o),i=t.map((function(e,t){return(e-a[t]%e)%e})),s=o.map((function(e,t){return e+i[t]}));return[t.map((function(e,t){return[n[t],s[t]]})),t.map((function(e,t){return[0,i[t]]}))]}([u.inHeight,u.inWidth],p,c),h=_[0],f=_[1],y=d?n:"valid",m=d?s:vn(s,p,h),g=("avg"===r?function(){return Ac(m,t,a,1,y)}:function(){return wc(m,t,a,1,y)})(),b=d?g:$r(g,p,f);return l?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),Oc=dr({maxPool3d_:function(e,t,r,n,o,a,i){void 0===a&&(a="NDHWC");var s=er(e,"x","maxPool3d"),l=s,c=!1;4===s.rank&&(c=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),T(5===l.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+l.rank+"."})),T("NDHWC"===a,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),T(fo(r,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"})),null!=o&&T(N(n),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."}));var u=ao(l.shape,t,r,i,n,o,a),p=je.runKernelFunc((function(e,t){var r=e.maxPool3d(l,u);return t([l,r]),r}),{x:l},(function(e,a){var s=a[0],l=a[1];return{x:function(){return function(e,t,r,n,o,a,i,s){var l=er(e,"dy","maxPool3dBackprop"),c=er(t,"input","maxPool3dBackprop"),u=er(r,"output","maxPool3dBackprop"),p=l,d=c,_=u,h=!1;4===c.rank&&(h=!0,p=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),_=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),T(5===p.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."})),T(5===d.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+d.rank+"."})),T(5===_.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+_.rank+"."})),null==a&&(a=[1,1,1]),T(fo(o,a),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),null!=s&&T(N(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var f=ao(d.shape,n,o,a,i,s),y=je.runKernelFunc((function(e){return e.maxPool3dBackprop(p,d,_,f)}),{dy5D:p,input5D:d});return h?y.as4D(y.shape[1],y.shape[2],y.shape[3],y.shape[4]):y}(e,s,l,t,r,i,n,o)}}}));return c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),Cc=dr({avgPool3d_:function(e,t,r,n,o,a,i){void 0===a&&(a="NDHWC");var s=er(e,"x","avgPool3d","float32"),l=s,c=!1;4===s.rank&&(c=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),T(5===l.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+l.rank+"."})),T("NDHWC"===a,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),T(fo(r,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"})),null!=o&&T(N(n),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."}));var u=ao(l.shape,t,r,i,n,o,a),p=je.runKernelFunc((function(e){return e.avgPool3d(l,u)}),{x:l},(function(e){return{x:function(){return function(e,t,r,n,o,a,i){var s=er(e,"dy","avgPool3dBackprop"),l=er(t,"input","avgPool3dBackprop"),c=s,u=l,p=!1;4===l.rank&&(p=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),u=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3])),T(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),T(5===u.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+u.rank+"."})),null==o&&(o=[1,1,1]),T(fo(n,o),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=i&&T(N(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var d=ao(u.shape,r,n,o,a,i),_=je.runKernelFunc((function(e){return e.avgPool3dBackprop(c,u,d)}),{dy5D:c,input5D:u});return p?_.as4D(_.shape[1],_.shape[2],_.shape[3],_.shape[4]):_}(e,l,t,r,i,n,o)}}}));return p=p.cast(l.dtype),c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}});t.avgPool3d=Cc,t.maxPool3d=Oc,t.pool=Tc,t.avgPool=Dc,t.maxPool=xc;var Lc=dr({slice_:function(e,t,r){var n,o,a=er(e,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(n="number"==typeof t?[t].concat(new Array(a.rank-1).fill(0)):t.length=0?e:(T(-1===e,(function(){return"Negative size values should be exactly -1 but got "+e+" for the slice() size at index "+t+"."})),a.shape[t]-n[t])})),Wn(a,n,o);var i=a.shape,s={begin:n,size:o};return je.runKernelFunc((function(e){return e.slice(a,n,o)}),{x:a},(function(e){for(var t=[],r=0;r0&&(t=t.sum(a)),t.reshape(n.shape)}}}),"Prelu")}}),Zc=dr({relu_:function(e){var t=er(e,"x","relu");return"bool"===t.dtype?t.toInt():je.runKernelFunc((function(e,r){var n=e.relu(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0];return{x:function(){return e.mulStrict(r.step().toFloat())}}}),"Relu")}}),$c=dr({relu6_:function(e){var t=er(e,"x","relu6");return"bool"===t.dtype?t.toInt():je.runKernelFunc((function(e,r){var n=e.relu6(t);return r([t]),n}),{x:t},(function(e,t){var r=t[0],n=r.lessEqual(6).mul(r.step());return{x:function(){return e.mulStrict(n.toFloat())}}}),"Relu6")}}),eu=dr({selu_:function(e){var t=er(e,"x","selu");return je.runKernelFunc((function(e,r){var n=e.selu(t);return r([t]),n}),{$x:t},(function(e,t){var r=t[0];return{$x:function(){var t=r.greater(gr(0)),n=gr(Xi),o=gr(Qi),a=e.mul(o),i=e.mul(n).mul(r.toFloat().exp());return ml(t,a,i)}}}))}});t.selu=eu,t.relu6=$c,t.relu=Zc,t.prelu=Jc,t.leakyRelu=Yc,t.elu=Qc;var tu=dr({transpose_:function(e,t){var r=er(e,"x","transpose");if(null==t&&(t=r.shape.map((function(e,t){return t})).reverse()),T(r.rank===t.length,(function(){return"Error in transpose: rank of input "+r.rank+" must match length of perm "+t+"."})),t.forEach((function(e){T(e>=0&&eo)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+t);var a=je.runKernelFunc((function(e){return e.topk(n,t,r)}),{$x:n});return{values:a[0],indices:a[1]}}});t.topk=lu;var cu=dr({scatterND_:function(e,t,r){var n=er(e,"indices","scatterND","int32"),o=er(t,"updates","scatterND");return Mn(o,n,r),je.runKernelFunc((function(e){return e.scatterND(n,o,r)}),{indices:n,updates:o},null,"ScatterNd",{shape:r})}});t.scatterND=cu;var uu=dr({fft_:function(e){T("complex64"===e.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+e.dtype+"."}));var t=e.shape[e.shape.length-1],r=e.size/t,n=e.as2D(r,t);return je.runKernelFunc((function(e){return e.fft(n)}),{input:e}).reshape(e.shape)}}),pu=dr({ifft_:function(e){T("complex64"===e.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+e.dtype+"."}));var t=e.shape[e.shape.length-1],r=e.size/t,n=e.as2D(r,t);return je.runKernelFunc((function(e){return e.ifft(n)}),{input:e}).reshape(e.shape)}}),du=dr({rfft_:function(e,t){T("float32"===e.dtype,(function(){return"The dtype for rfft() must be real value but got "+e.dtype}));var r,n=e.shape[e.shape.length-1],o=e.size/n;if(null!=t&&tn){var s=e.shape.map((function(e){return e}));s[e.shape.length-1]=t-n,r=e.concat(xr(s),e.shape.length-1),n=t}else r=e;var l=r.zerosLike(),c=_r(r,l).as2D(o,n),u=uu(c),p=Math.floor(n/2)+1,d=hr(u),_=fr(u),h=d.split([p,n-p],d.shape.length-1),f=_.split([p,n-p],_.shape.length-1),y=r.shape.slice();return y[r.shape.length-1]=p,_r(h[0],f[0]).reshape(y)}}),_u=dr({irfft_:function(e){var t=e.shape[e.shape.length-1],r=e.size/t;if(t<=2){var n=e.as2D(r,t),o=pu(n);return hr(o)}var a=[r,2*(t-1)],i=hr(e).as2D(r,t),s=fr(e).as2D(r,t),l=i.slice([0,1],[r,t-2]).reverse(1),c=s.slice([0,1],[r,t-2]).reverse(1).mul(gr(-1)),u=i.concat(l,1),p=s.concat(c,1);return n=_r(u,p).as2D(a[0],a[1]),o=pu(n),hr(o)}}),hu=Object.freeze({fft:uu,ifft:pu,rfft:du,irfft:_u});t.spectral=hu,t.irfft=_u,t.rfft=du,t.ifft=pu,t.fft=uu;var fu=dr({sparseToDense_:function(e,t,r,n){void 0===n&&(n=0);var o=er(e,"sparseIndices","sparseToDense","int32"),a=er(t,"sparseValues","sparseToDense"),i=er(n,"defaultValue","sparseToDense",a.dtype);return function(e,t,r,n){if("int32"!==e.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+e.shape+".");var o=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(r.length!==a)throw new Error("outputShape has incorrect number of elements:, "+r.length+", should be: "+a+".");var i=t.size;if(0!==t.rank&&(1!==t.rank||i!==o))throw new Error("sparseValues has incorrect shape "+t.shape+", should be [] or ["+o+"]");if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,r,i),je.runKernelFunc((function(e){return e.sparseToDense(o,a,r,i)}),{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});t.sparseToDense=fu;var yu=dr({gatherND_:function(e,t){var r=er(t,"indices","gatherND","int32"),n=er(e,"x","gatherND");return je.runKernelFunc((function(e){return e.gatherND(n,r)}),{x:n,indices:r},null,"GatherNd")}});t.gatherND=yu;var mu=dr({diag_:function(e){var t=er(e,"x","diag").flatten(),r=e.shape.concat(e.shape);return je.runKernelFunc((function(e){return e.diag(t)}),{$x:t}).reshape(r)}});t.diag=mu;var gu=dr({dropout_:function(e,t,r,n){var o=er(e,"x","dropout");if(T("float32"===o.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."})),T(t>=0&&t<1,(function(){return"rate must be a float in the range [0, 1), but got "+t+"."})),0===t)return e instanceof Re?o.clone():o;var a=function(e,t){if(null==t)return e.shape.slice();if(I(e.shape,t))return t;if(e.shape.length===t.length){for(var r=[],n=0;n1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank})),T(n.rank-1===o.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+o.rank})),O(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=n.shape[n.shape.length-1],T(r>0&&r<=a,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+a+"), but got "+r})),[4,n.data()];case 1:return i=d.sent(),[4,o.data()];case 2:for(s=d.sent(),l=[i.length/a,a],u=l[1],p=V("bool",c=l[0]),_=0;_1?s.div(gr(i)):s}if(r===wu.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(gr(n.size));var l=o.mul(Ar(n.shape)).notEqual(gr(0)).sum().toFloat();return a.sum().div(l)}throw Error("Unknown reduction: "+r)}}),Tu=dr({cosineDistance_:function(e,t,r,n,o){void 0===o&&(o=wu.SUM_BY_NONZERO_WEIGHTS);var a=er(e,"labels","cosineDistance"),i=er(t,"predictions","cosineDistance"),s=null;null!=n&&(s=er(n,"weights","cosineDistance")),O(a.shape,i.shape,"Error in cosineDistance: ");var l=gr(1).sub(a.mul(i).sum(r,!0));return Du(l,s,o)}}),Ou=dr({hingeLoss_:function(e,t,r,n){void 0===n&&(n=wu.SUM_BY_NONZERO_WEIGHTS);var o=er(e,"labels","hingeLoss"),a=er(t,"predictions","hingeLoss"),i=null;null!=r&&(i=er(r,"weights","hingeLoss")),O(o.shape,a.shape,"Error in hingeLoss: ");var s=gr(1);o=gr(2).mul(o).sub(s);var l=s.sub(o.mul(a)).relu();return Du(l,i,n)}}),Cu=dr({huberLoss_:function(e,t,r,n,o){void 0===n&&(n=1),void 0===o&&(o=wu.SUM_BY_NONZERO_WEIGHTS);var a=er(e,"labels","huberLoss"),i=er(t,"predictions","huberLoss"),s=null;null!=r&&(s=er(r,"weights","huberLoss")),O(a.shape,i.shape,"Error in huberLoss: ");var l=gr(n),c=i.sub(a).abs(),u=Tl(c,l),p=c.sub(u),d=gr(.5).mul(u.square()).add(l.mul(p));return Du(d,s,o)}}),Lu=dr({logLoss_:function(e,t,r,n,o){void 0===n&&(n=1e-7),void 0===o&&(o=wu.SUM_BY_NONZERO_WEIGHTS);var a=er(e,"labels","logLoss"),i=er(t,"predictions","logLoss"),s=null;null!=r&&(s=er(r,"weights","logLoss")),O(a.shape,i.shape,"Error in logLoss: ");var l=gr(1),c=gr(n),u=a.mul(i.add(c).log()).neg().sub(l.sub(a).mul(l.sub(i).add(c).log()));return Du(u,s,o)}}),Bu=dr({meanSquaredError_:function(e,t,r,n){void 0===n&&(n=wu.SUM_BY_NONZERO_WEIGHTS);var o=er(e,"labels","meanSquaredError"),a=er(t,"predictions","meanSquaredError"),i=null;null!=r&&(i=er(r,"weights","meanSquaredError")),O(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return Du(s,i,n)}}),Iu=dr({sigmoidCrossEntropy_:function(e,t,r,n,o){void 0===n&&(n=0),void 0===o&&(o=wu.SUM_BY_NONZERO_WEIGHTS);var a=er(e,"multiClassLabels","sigmoidCrossEntropy"),i=er(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=r&&(s=er(r,"weights","sigmoidCrossEntropy")),O(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){var l=gr(n),c=gr(1),u=gr(.5);a=a.mul(c.sub(l)).add(u.mul(l))}var p=function(e,t){var r=er(e,"labels","sigmoidCrossEntropyWithLogits"),n=er(t,"logits","sigmoidCrossEntropyWithLogits");O(r.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=n.relu(),a=n.mul(r),i=n.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return Du(p,s,o)}}),Nu=dr({softmaxCrossEntropy_:function(e,t,r,n,o){void 0===n&&(n=0),void 0===o&&(o=wu.SUM_BY_NONZERO_WEIGHTS);var a=er(e,"onehotLabels","softmaxCrossEntropy"),i=er(t,"logits","softmaxCrossEntropy"),s=null;if(null!=r&&(s=er(r,"weights","softmaxCrossEntropy")),O(a.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){var l=gr(n),c=gr(1),u=gr(a.shape[1]);a=a.mul(c.sub(l)).add(l.div(u))}var p=function(e,t,r){if(void 0===r&&(r=-1),-1===r&&(r=t.rank-1),r!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+t.rank+" and dim was "+r);return Xn((function(e,t,n){var o=t.logSumExp([r],!0),a=t.toFloat().sub(o);return n([e,a]),{value:a.mul(e).neg().sum([r]),gradFunc:function(e,t){var n=t[0],o=t[1],a=ar(e.shape,[r]);return[e.reshape(a).mul(n.toFloat().sub(o.exp())),e.reshape(a).mul(o.exp().sub(n.toFloat()))]}}}))(e,t)}(a,i);return Du(p,s,o)}}),Mu=Object.freeze({get Reduction(){return wu},absoluteDifference:xu,computeWeightedLoss:Du,cosineDistance:Tu,hingeLoss:Ou,huberLoss:Cu,logLoss:Lu,meanSquaredError:Bu,sigmoidCrossEntropy:Iu,softmaxCrossEntropy:Nu});function Pu(e,t){return void 0===t&&(t=!1),je.tidy((function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var r=e.shape[0],n=e.shape[1],o=sn(r),a=e.clone(),i=vr([[1]],[1,1]),s=i.clone(),l=r>=n?n:r,c=function(e){var t,l=a,c=s,u=o;t=je.tidy((function(){var t=a.slice([e,e],[r-e,1]),l=t.norm(),c=a.slice([e,e],[1,1]),u=vr([[-1]]).where(c.greater(0),vr([[1]])),p=c.sub(u.mul(l)),d=t.div(p);s=1===d.shape[0]?i.clone():i.concat(d.slice([1,0],[d.shape[0]-1,d.shape[1]]),0);var _=u.matMul(p).div(l).neg(),h=a.slice([e,0],[r-e,n]),f=_.mul(s);if(0===e)a=h.sub(f.matMul(s.transpose().matMul(h)));else{var y=h.sub(f.matMul(s.transpose().matMul(h)));a=a.slice([0,0],[e,n]).concat(y,0)}var m=o.slice([0,e],[r,o.shape[1]-e]);if(0===e)o=m.sub(m.matMul(s).matMul(f.transpose()));else{var g=m.sub(m.matMul(s).matMul(f.transpose()));o=o.slice([0,0],[r,e]).concat(g,1)}return[s,a,o]})),s=t[0],a=t[1],o=t[2],Qt([l,c,u])},u=0;un&&(o=o.slice([0,0],[r,n]),a=a.slice([0,0],[n,n])),[o,a]}))}t.losses=Mu;var Fu=dr({bandPart_:function(e,t,r){if(t%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+t+".");if(r%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+r+".");var n=er(e,"a","bandPart");if(n.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+n.rank+".");var o=n.shape,a=n.shape.slice(-2),i=a[0],s=a[1];if(!(t<=i))throw new Error("bandPart(): numLower ("+t+") must not be greater than the number of rows ("+i+").");if(!(r<=s))throw new Error("bandPart(): numUpper ("+r+") must not be greater than the number of columns ("+s+").");t<0&&(t=i),r<0&&(r=s);var l=Or(0,i,1,"int32").reshape([-1,1]),c=Or(0,s,1,"int32"),u=Fl(l,c),p=_l(u.lessEqual(gr(+t,"int32")),u.greaterEqual(gr(-r,"int32"))),d=xr([i,s],n.dtype);return kn(wn(n.reshape([-1,i,s])).map((function(e){return ml(p,e,d)}))).reshape(o)}}),Wu=dr({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,T(null!=e&&e.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var r=e[0].shape[0],n=function(t){T(e[t].shape[0]===r,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+e[t].shape[0]+" vs. "+r+")"}))},o=1;o0)for(var r=0;r= 2, but got rank "+e.rank);if(2===e.rank)return Pu(e,t);var r=e.shape.slice(0,e.shape.length-2).reduce((function(e,t){return e*t})),n=wn(e.reshape([r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),o=[],a=[];return n.forEach((function(e){var r=Pu(e,t),n=r[0],i=r[1];o.push(n),a.push(i)})),[kn(o,0).reshape(e.shape),kn(a,0).reshape(e.shape)]}}),zu=Object.freeze({bandPart:Fu,gramSchmidt:Wu,qr:Hu});function ju(e,t,r,n,o,a){null==n&&(n=.5),null==o&&(o=Number.NEGATIVE_INFINITY),null==a&&(a=0);var i=e.shape[0];return r=Math.min(r,i),T(0<=n&&n<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+n+"'"})),T(2===e.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"})),T(4===e.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]})),T(1===t.rank,(function(){return"scores must be a 1D tensor"})),T(t.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]})),T(0<=a&&a<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"})),{maxOutputSize:r,iouThreshold:n,scoreThreshold:o,softNmsSigma:a}}t.linalg=zu;var Vu=dr({resizeBilinear_:function(e,t,r){void 0===r&&(r=!1);var n=er(e,"images","resizeBilinear");T(3===n.rank||4===n.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."})),T(2===t.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."}));var o=n,a=!1;3===n.rank&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],l=je.runKernelFunc((function(e,t){return t([o]),e.resizeBilinear(o,i,s,r)}),{x:o},(function(e,t){return{x:function(){return je.runKernelFunc((function(n){return n.resizeBilinearBackprop(e,t[0],r)}),{})}}}),"ResizeBilinear",{alignCorners:r,newHeight:i,newWidth:s});return a?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),Uu=dr({resizeNearestNeighbor_:function(e,t,r){void 0===r&&(r=!1);var n=er(e,"images","resizeNearestNeighbor");T(3===n.rank||4===n.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."})),T(2===t.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."})),T("float32"===n.dtype||"int32"===n.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var o=n,a=!1;3===n.rank&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],l=je.runKernelFunc((function(e,t){return t([o]),e.resizeNearestNeighbor(o,i,s,r)}),{batchImages:o},(function(e,t){return{batchImages:function(){return je.runKernelFunc((function(n){return n.resizeNearestNeighborBackprop(e,t[0],r)}),{})}}}));return a?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),Gu=dr({nonMaxSuppression_:function(e,t,r,n,o){void 0===n&&(n=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=er(e,"boxes","nonMaxSuppression"),i=er(t,"scores","nonMaxSuppression"),s=ju(a,i,r,n,o);r=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold;var l={maxOutputSize:r,iouThreshold:n,scoreThreshold:o};return je.runKernelFunc((function(e){return e.nonMaxSuppression(a,i,r,n,o)}),{boxes:a,scores:i},null,"NonMaxSuppressionV3",l)}}),Ku=dr({nonMaxSuppressionWithScore_:function(e,t,r,n,o,a){void 0===n&&(n=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===a&&(a=0);var i=er(e,"boxes","nonMaxSuppression"),s=er(t,"scores","nonMaxSuppression"),l=ju(i,s,r,n,o,a),c={maxOutputSize:r=l.maxOutputSize,iouThreshold:n=l.iouThreshold,scoreThreshold:o=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},u=je.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:u[0],selectedScores:u[1]}}}),qu=dr({cropAndResize_:function(e,t,r,n,o,a){var i=er(e,"image","cropAndResize"),s=er(t,"boxes","cropAndResize","float32"),l=er(r,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return T(4===i.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),T(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),T(1===l.rank&&l.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),T(2===n.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."})),T(n[0]>=1&&n[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+n})),T("bilinear"===o||"nearest"===o,(function(){return"method must be bilinear or nearest, but was "+o})),je.runKernelFunc((function(e,t){return e.cropAndResize(i,s,l,n,o,a)}),{images:i,boxes:s,boxInd:l},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:n})}}),Xu=Object.freeze({resizeBilinear:Vu,resizeNearestNeighbor:Uu,nonMaxSuppression:Gu,nonMaxSuppressionAsync:function(e,t,r,n,o){return void 0===n&&(n=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),p(this,void 0,void 0,(function(){var a,i,s,l,c,u,p;return d(this,(function(d){switch(d.label){case 0:return a=er(e,"boxes","nonMaxSuppressionAsync"),i=er(t,"scores","nonMaxSuppressionAsync"),s=ju(a,i,r,n,o),r=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([a.data(),i.data()])];case 1:return l=d.sent(),c=l[0],u=l[1],p=xo(c,u,r,n,o),a!==e&&a.dispose(),i!==t&&i.dispose(),[2,p]}}))}))},nonMaxSuppressionWithScore:Ku,nonMaxSuppressionWithScoreAsync:function(e,t,r,n,o,a){return void 0===n&&(n=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===a&&(a=0),p(this,void 0,void 0,(function(){var i,s,l,c,u,p,_;return d(this,(function(d){switch(d.label){case 0:return i=er(e,"boxes","nonMaxSuppressionAsync"),s=er(t,"scores","nonMaxSuppressionAsync"),l=ju(i,s,r,n,o,a),r=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,a=l.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return c=d.sent(),u=c[0],p=c[1],_=Do(u,p,r,n,o,a),i!==e&&i.dispose(),s!==t&&s.dispose(),[2,_]}}))}))},cropAndResize:qu}),Qu=function(e,t){return!(e>0)||"linear"===t},Yu=function(e,t,r){if(null==r||"linear"===r)return e;if("relu"===r)return e.mul(t.step());throw new Error("Gradient for activation "+r+" has not been implemented yet.")},Ju=function(e,t){var r=t,n=ro(e.shape,t.shape);return n.length>0&&(r=r.sum(n)),r.reshape(e.shape)},Zu=function(e,t,r){if("linear"===t)return e;if("relu"===t)return Zc(e);if("elu"===t)return Qc(e);if("relu6"===t)return $c(e);if("prelu"===t)return Jc(e,r);throw new Error("Unknown fused activation "+t+".")};t.image=Xu;var $u=dr({fusedMatMul_:function(e){var t,r=e.a,n=e.b,o=e.transposeA,a=void 0!==o&&o,i=e.transposeB,s=void 0!==i&&i,c=e.bias,u=e.activation,p=void 0===u?"linear":u,d=e.preluActivationWeights;if(!1===Qu(je.state.gradientDepth,p)){var _=mc(r,n,a,s);return null!=c&&(_=bl(_,c)),Zu(_,p,d)}var h=er(r,"a","fused matMul"),f=er(n,"b","fused matMul");t=Ne(h,f),h=t[0],f=t[1];var y=a?h.shape[h.rank-2]:h.shape[h.rank-1],m=s?f.shape[f.rank-1]:f.shape[f.rank-2],g=a?h.shape[h.rank-1]:h.shape[h.rank-2],b=s?f.shape[f.rank-2]:f.shape[f.rank-1],v=h.shape.slice(0,-2),E=f.shape.slice(0,-2),k=B(v),S=B(E);T(h.rank>=2&&f.rank>=2&&h.rank===f.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+h.rank+" and "+f.rank+"."})),T(I(v,E),(function(){return"Error in fused matMul: outer dimensions ("+v+") and ("+E+") of Tensors with shapes "+h.shape+" and "+f.shape+" must match."})),T(y===m,(function(){return"Error in fused matMul: inner shapes ("+y+") and ("+m+") of Tensors with shapes "+h.shape+" and "+f.shape+" and transposeA="+a+" and transposeB="+s+" must match."}));var R,w,A=h.shape.slice(0,-2).concat([g,b]),x=a?h.as3D(k,y,g):h.as3D(k,g,y),D=s?f.as3D(S,b,m):f.as3D(S,m,b);null!=c&&no(A,(R=Ne(R=er(c,"bias","fused matMul"),h)[0]).shape),null!=d&&(w=er(d,"prelu weights","fused matMul"));var O={a:x,b:D};null!=c&&(O.bias=R),null!=d&&(O.preluActivationWeights=w);var C=[x,D];return je.runKernelFunc((function(e,t){var r=e.fusedBatchMatMul({a:x,b:D,transposeA:a,transposeB:s,bias:R,activation:p,preluActivationWeights:w});return t([x,D,r]),r}),O,(function(e,t){var r=t[0],n=t[1],o=t[2],i=Yu(e,o,p),u={};return null!=c&&(u={bias:function(){return Ju(R,i)}}),a||s?!a&&s?(0,l.default)({a:function(){return i.matMul(n,!1,!1)},b:function(){return i.matMul(r,!0,!1)}},u):a&&!s?(0,l.default)({a:function(){return n.matMul(i,!1,!0)},b:function(){return r.matMul(i,!1,!1)}},u):(0,l.default)({a:function(){return n.matMul(i,!0,!0)},b:function(){return i.matMul(r,!0,!0)}},u):(0,l.default)({a:function(){return i.matMul(n,!1,!0)},b:function(){return r.matMul(i,!0,!1)}},u)}),"_FusedMatMul",{transposeA:a,transposeB:s,activation:p},C,[!0]).reshape(A)}}),ep=dr({fusedConv2d_:function(e){var t=e.x,r=e.filter,n=e.strides,o=e.pad,a=e.dataFormat,i=void 0===a?"NHWC":a,s=e.dilations,c=void 0===s?[1,1]:s,u=e.dimRoundingMode,p=e.bias,d=e.activation,_=void 0===d?"linear":d,h=e.preluActivationWeights;if(_=_||"linear",!1===Qu(je.state.gradientDepth,_)){var f=sc(t,r,n,o,i,c,u);return null!=p&&(f=bl(f,p)),Zu(f,_,h)}var y=er(t,"x","conv2d"),m=er(r,"filter","conv2d"),g=y,b=!1;3===y.rank&&(b=!0,g=y.as4D(1,y.shape[0],y.shape[1],y.shape[2])),T(4===g.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),T(4===m.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."})),null!=u&&T(N(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+o+"."})),T(g.shape[3]===m.shape[2],(function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+m.shape[2]+"."})),T(fo(n,c),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+c+"'"})),T("NHWC"===i,(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var v,E,k=io(g.shape,m.shape,n,c,o,u);null!=p&&(v=Ne(v=er(p,"bias","fused conv2d"),y)[0],no(k.outShape,v.shape)),null!=h&&(E=er(h,"prelu weights","fused conv2d"));var S={x:g,filter:m};null!=p&&(S.bias=v),null!=h&&(S.preluActivationWeights=E);var R=[m,g],w=je.runKernelFunc((function(e,t){var r=e.fusedConv2d({input:g,filter:m,convInfo:k,bias:v,activation:_,preluActivationWeights:E});return t([m,g,r]),r}),S,(function(e,t){var r=t,a=r[0],i=r[1],s=r[2],u=Yu(e,s,_);T(ho(c),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+c+"'"}));var d={};return null!=p&&(d={bias:function(){return Ju(v,u)}}),(0,l.default)({x:function(){return uc(i.shape,u,a,n,o)},filter:function(){return cc(i,u,a.shape,n,o)}},d)}),"FusedConv2D",{convInfo:k,activation:_},R,[!0]);return b?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),tp=dr({fusedDepthwiseConv2d_:function(e){var t=e.x,r=e.filter,n=e.strides,o=e.pad,a=e.dataFormat,i=void 0===a?"NHWC":a,s=e.dilations,c=void 0===s?[1,1]:s,u=e.dimRoundingMode,p=e.bias,d=e.activation,_=void 0===d?"linear":d,h=e.preluActivationWeights;if(!1===Qu(je.state.gradientDepth,_)){var f=pc(t,r,n,o,i,c,u);return null!=p&&(f=bl(f,p)),Zu(f,_,h)}var y=er(t,"x","depthwiseConv2d"),m=er(r,"filter","depthwiseConv2d"),g=y,b=!1;3===y.rank&&(b=!0,g=y.as4D(1,y.shape[0],y.shape[1],y.shape[2])),T(4===g.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),T(4===m.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."})),T(g.shape[3]===m.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+m.shape[2]+"."})),null==c&&(c=[1,1]),T(fo(n,c),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+c+"'"})),null!=u&&T(N(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+u+" but got pad "+o+"."}));var v,E,k=io(g.shape,m.shape,n,c,o,u,!0);null!=p&&(v=Ne(v=er(p,"bias","fused conv2d"),y)[0],no(k.outShape,v.shape)),null!=h&&(E=er(h,"prelu weights","fused depthwiseConv2d"));var S={x:g,filter:m};null!=p&&(S.bias=v),null!=h&&(S.preluActivationWeights=E);var R=[m,g],w=je.runKernelFunc((function(e,t){var r=e.fusedDepthwiseConv2D({input:g,filter:m,convInfo:k,bias:v,activation:_,preluActivationWeights:E});return t([m,g,r]),r}),S,(function(e,t){T(ho(c),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+c+"'"}));var r=t[0],n=t[1],o=t[2],a=Yu(e,o,_),i={};return null!=p&&(i={bias:function(){return Ju(v,a)}}),(0,l.default)({x:function(){return dc(n.shape,a,r,k)},filter:function(){return _c(n,a,r.shape,k)}},i)}),"FusedDepthwiseConv2D",{convInfo:k,activation:_},R,[!0]);return b?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),rp=Object.freeze({matMul:$u,conv2d:ep,depthwiseConv2d:tp}),np=Object.freeze({image:Xu,linalg:zu,losses:Mu,spectral:hu,fused:rp,signal:Ru,square:ys,squaredDifference:gs,conv1d:ic,conv2d:sc,conv3d:lc,depthwiseConv2d:pc,separableConv2d:hc,conv2dTranspose:fc,conv3dTranspose:yc,op:dr,batchNormalization2d:al,batchNormalization3d:il,batchNormalization4d:sl,batchNormalization:ll,batchNorm:cl,batchNorm2d:ul,batchNorm3d:pl,batchNorm4d:dl,booleanMaskAsync:rc,complex:_r,real:hr,imag:fr,concat:Br,concat1d:Ir,concat2d:Nr,concat3d:Mr,concat4d:Pr,split:Fr,matMul:mc,dot:gc,outerProduct:bc,reverse:vc,reverse1d:Ec,reverse2d:kc,reverse3d:Sc,reverse4d:Rc,maxPool:xc,avgPool:Dc,pool:Tc,maxPool3d:Oc,avgPool3d:Cc,slice:Lc,slice1d:Bc,slice2d:Ic,slice3d:Nc,slice4d:Mc,abs:bs,acos:vs,acosh:Es,asin:ks,asinh:Ss,atan:Rs,atanh:ws,ceil:As,clipByValue:xs,cos:Ds,cosh:Ts,erf:Os,exp:Cs,expm1:Ls,floor:Bs,log:Is,log1p:Ns,logSigmoid:Ms,neg:Ps,reciprocal:Fs,round:Ws,rsqrt:Hs,sigmoid:zs,sign:js,isNaN:Vs,isInf:Us,isFinite:Gs,sin:Ks,sinh:qs,softplus:Xs,sqrt:Qs,step:Ys,tan:Js,tanh:Zs,all:Fc,any:Wc,argMax:Hc,argMin:zc,logSumExp:jc,max:Vc,mean:Uc,min:Gc,moments:Kc,sum:qc,prod:Xc,equal:Hl,equalStrict:zl,greater:jl,greaterEqual:Vl,greaterEqualStrict:Ul,greaterStrict:Gl,less:Kl,lessEqual:ql,lessEqualStrict:Xl,lessStrict:Ql,notEqual:Yl,notEqualStrict:Jl,add:bl,addN:vl,addStrict:El,atan2:kl,div:Sl,divNoNan:Rl,divStrict:wl,floorDiv:Al,maximum:xl,maximumStrict:Dl,minimum:Tl,minimumStrict:Ol,mod:Cl,modStrict:Ll,mul:Bl,mulStrict:Il,pow:Nl,powStrict:Ml,squaredDifferenceStrict:Pl,sub:Fl,subStrict:Wl,elu:Qc,leakyRelu:Yc,prelu:Jc,relu:Zc,relu6:$c,selu:eu,logicalAnd:_l,logicalNot:hl,logicalOr:fl,logicalXor:yl,where:ml,whereAsync:gl,buffer:Jr,print:Zr,batchToSpaceND:$r,broadcastTo:en,cast:tn,clone:rn,cumsum:nn,depthToSpace:on,expandDims:an,eye:sn,multinomial:ln,oneHot:cn,pad:un,pad1d:pn,pad2d:dn,pad3d:_n,pad4d:hn,rand:fn,randomNormal:yn,randomGamma:mn,randomUniform:gn,reshape:bn,spaceToBatchND:vn,squeeze:En,stack:kn,tile:Sn,truncatedNormal:Rn,unstack:wn,setdiff1dAsync:An,fill:Dr,linspace:Tr,ones:Ar,range:Or,scalar:gr,tensor:yr,tensor1d:br,tensor2d:vr,tensor3d:Er,tensor4d:kr,tensor5d:Sr,tensor6d:Rr,variable:wr,zeros:xr,onesLike:Cr,zerosLike:Lr,transpose:tu,softmax:Yn,logSoftmax:Jn,localResponseNormalization:ru,norm:nu,gather:ec,unsortedSegmentSum:tc,basicLSTMCell:ou,multiRNNCell:au,movingAverage:iu,stridedSlice:su,topk:lu,scatterND:cu,fft:uu,ifft:pu,rfft:du,irfft:_u,sparseToDense:fu,gatherND:yu,diag:mu,dropout:gu,hannWindow:vu,hammingWindow:Eu,frame:ku,stft:Su,inTopKAsync:Au});function op(e,t){Array.isArray(e)||(e=[e]),e.forEach((function(e){null!=e&&T("complex64"!==e.dtype,(function(){return t+" does not support complex64 tensors."}))}))}function ap(e,t,r,n){if("linear"===r)return e.linear(t);if("relu"===r)return e.relu(t);if("elu"===r)return e.elu(t);if("relu6"===r)return e.relu6(t);if("prelu"===r)return e.prelu(t,n);throw new Error("Activation "+r+" has not been implemented for the CPU backend.")}t.fused=rp;var ip=function(e){function t(){var t=e.call(this)||this;return t.blockSize=48,t.firstUse=!0,t.data=new Zn(t,je),t}return u(t,e),t.prototype.write=function(e,t,r){this.firstUse&&(this.firstUse=!1,f().get("IS_NODE")&&Jt("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));var n={};return this.data.set(n,{values:e,dtype:r}),n},t.prototype.move=function(e,t,r,n){this.data.set(e,{values:t,dtype:n})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return p(this,void 0,void 0,(function(){return d(this,(function(t){return[2,this.readSync(e)]}))}))},t.prototype.readSync=function(e){var t=this.data.get(e),r=t.dtype,n=t.complexTensors;return"complex64"===r?Eo(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),r=t;if("string"===e.dtype)try{r=t.map((function(e){return pe(e)}))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Jr(e.shape,e.dtype,r)},t.prototype.makeOutput=function(e,t,r){var n=this.write(e,t,r);return je.makeTensorFromDataId(n,t,r,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return p(this,void 0,void 0,(function(){var t;return d(this,(function(r){return t=le(),e(),[2,{kernelMs:le()-t}]}))}))},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.complex=function(e,t){var r=this.makeOutput(null,e.shape,"complex64");return this.data.get(r.dataId).complexTensors={real:je.keep(e.clone()),imag:je.keep(t.clone())},r},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,r){if(op(e,"slice"),Un(e.shape,t,r)){var n=Gn(t,e.strides),o=B(r);return yr(this.readSync(e.dataId).subarray(n,n+o),r,e.dtype)}for(var a=Jr(r,e.dtype),i=this.bufferSync(e),s=0;sd&&(d=f,_=h)}l[u]=_}return i},t.prototype.cumsum=function(e,t,r,n){if(op(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var o=Be(e.dtype,"int32"),a=xr(e.shape,o),i=this.readSync(a.dataId),s=this.readSync(e.dataId),l=e.shape[e.rank-1],c=n?function(e,t){return e+l-t-1}:function(e,t){return e+t},u=0;ut?1:0}))},t.prototype.greaterEqual=function(e,t){return op([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e>=t?1:0}))},t.prototype.logicalNot=function(e){op(e,"logicalNot");for(var t=this.readSync(e.dataId),r=new Uint8Array(t.length),n=0;n1||1===t.rank?1:B(t.shape.slice(1)),u=0;u=0&&t>=0?r:(r+t)%t}))},t.prototype.max=function(e,t){op(e,"max"),ir("max",t,e.rank);for(var r=or(e.shape,t),n=r[0],o=r[1],a=xr(n,e.dtype),i=B(o),s=this.readSync(a.dataId),l=this.readSync(e.dataId),c=0;cp&&(p=_)}s[c]=p}return a},t.prototype.maximum=function(e,t){return op([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.max(e,t)}))},t.prototype.all=function(e,t){op(e,"all"),ir("all",t,e.rank);for(var r=or(e.shape,t),n=r[0],o=r[1],a=xr(n,e.dtype),i=B(o),s=this.readSync(a.dataId),l=this.readSync(e.dataId),c=0;c0?r[n]=1:r[n]=0;return this.makeOutput(r,e.shape,"float32")},t.prototype.isNaN=function(e){op(e,"x");for(var t=this.readSync(e.dataId),r=new Uint8Array(t.length),n=0;n.5?r[n]=Math.ceil(t[n]):r[n]=o%2==0?o:o+1}return this.makeOutput(r,e.shape,"float32")},t.prototype.exp=function(e){op(e,"exp");for(var t=this.readSync(e.dataId),r=new Float32Array(t.length),n=0;n=0?o:Math.exp(o)-1}return this.makeOutput(t,e.shape,"float32")},t.prototype.eluDer=function(e,t){op([e,t],"eluDer");for(var r=new Float32Array(t.size),n=this.readSync(t.dataId),o=this.readSync(e.dataId),a=0;a=1?o[a]:o[a]*(i+1)}return this.makeOutput(r,t.shape,"float32")},t.prototype.selu=function(e){op(e,"selu");for(var t=new Float32Array(e.size),r=this.readSync(e.dataId),n=0;n=0?1.0507009873554805*o:1.7580993408473768*(Math.exp(o)-1)}return this.makeOutput(t,e.shape,"float32")},t.prototype.clip=function(e,t,r){op(e,"clip");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;ar?r:i-t,s=n[o]0?1:t}return this.makeOutput(r,e.shape,"float32")},t.prototype.fusedConv2d=function(e){var t=e.input,r=e.filter,n=e.convInfo,o=e.bias,a=e.activation,i=e.preluActivationWeights,s=this.conv2d(t,r,n);return o&&(s=this.add(s,o)),a&&(s=ap(this,s,a,i)),s},t.prototype.conv2d=function(e,t,r){op([e,t],"conv2d");for(var n=r.filterHeight,o=r.filterWidth,a=r.dilationHeight,i=r.dilationWidth,s=r.padInfo.left,l=r.padInfo.top,c="channelsLast"===r.dataFormat,u=Jr(r.outShape,e.dtype),p=e.strides[0],d=c?e.strides[1]:e.strides[2],_=c?e.strides[2]:1,h=c?1:e.strides[1],f=u.strides[0],y=c?u.strides[1]:u.strides[2],m=c?u.strides[2]:1,g=c?1:u.strides[1],b=this.readSync(e.dataId),v=this.readSync(t.dataId),E=u.values,k=0;k=r.inHeight))for(var O=D*t.strides[0],C=S+T*d,L=0;L=r.inWidth))for(var P=C+M*_,F=O+N*t.strides[1],W=0;W=r.inDepth))for(var R=k*t.strides[0],w=m+S*e.strides[1],A=0;A=r.inHeight))for(var C=R+T*t.strides[1],L=w+O*e.strides[2],B=0;B=r.inWidth))for(var F=C+M*t.strides[2],W=L+P*r.inChannels,H=F,z=0;z=r.inHeight))for(var k=v*t.strides[0],S=f+E*e.strides[1],R=0;R=r.inWidth))for(var T=k+x*t.strides[1],O=S+D*r.inChannels,C=w,L=T,B=0;BC?C=P:"avg"===r&&(L+=P,B++)}if(isNaN(C))break}h[A+x*m+E]="avg"===r?L/B:C}return _.toTensor()},t.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},t.prototype.maxPoolPositions=function(e,t){for(var r=Jr(t.outShape,"int32"),n=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=t.padInfo.top,u=t.padInfo.left,p=this.bufferSync(e),d=0;dk&&(k=D,S=w*l+x)}r.set(S,d,h,g,_)}}return r.toTensor()},t.prototype.maxPoolBackprop=function(e,t,r,n){op([t,r],"maxPoolBackprop");for(var o=this.maxPoolPositions(t,n),a=n.strideHeight,i=n.strideWidth,s=n.dilationHeight,l=n.dilationWidth,c=n.effectiveFilterHeight,u=n.effectiveFilterWidth,p=u-1-n.padInfo.left,d=c-1-n.padInfo.top,_=Jr(t.shape,"float32"),h=this.bufferSync(o),f=this.bufferSync(e),y=0;y=n.outHeight||Math.floor(R)!==R))for(var w=0;w=n.outWidth||Math.floor(A)!==A)){var x=c*u-1-h.get(y,R,A,m)===S*u+w?1:0;0!==x&&(k+=f.get(y,R,A,m)*x)}}}_.set(k,y,g,b,m)}return _.toTensor()},t.prototype.avgPoolBackprop=function(e,t,r){op([e,t],"avgPoolBackprop");for(var n=r.strideHeight,o=r.strideWidth,a=r.filterHeight,i=r.filterWidth,s=r.dilationHeight,l=r.dilationWidth,c=r.effectiveFilterHeight,u=r.effectiveFilterWidth,p=u-1-r.padInfo.left,d=c-1-r.padInfo.top,_=Jr(t.shape,"float32"),h=1/(a*i),f=this.bufferSync(e),y=0;y=r.outHeight||Math.floor(R)!==R))for(var w=0;w=r.outWidth||Math.floor(A)!==A||(k+=f.get(y,R,A,m))}}_.set(k*h,y,g,b,m)}return _.toTensor()},t.prototype.pool3d=function(e,t,r){op(e,"pool3d");for(var n=t.strideDepth,o=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,s=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,_=t.padInfo.top,h=t.padInfo.left,f="max"===r?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,y=this.readSync(e.dataId),m=Jr(t.outShape,e.dtype),g=m.values,b=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],v=t.outShape[2]*t.outShape[3]*t.outShape[4],E=t.outShape[3]*t.outShape[4],k=t.outShape[4],S=0;Sj?j=Y:"avg"===r&&(V+=Y,U++),isNaN(j))break}if(isNaN(j))break}if(isNaN(j))break}g[z+A]="avg"===r?V/U:j}}}return m.toTensor()},t.prototype.avgPool3d=function(e,t){return op(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,t,r){op([e,t],"avgPool3dBackprop");for(var n=r.strideDepth,o=r.strideHeight,a=r.strideWidth,i=r.filterDepth,s=r.filterHeight,l=r.filterWidth,c=r.dilationDepth,u=r.dilationHeight,p=r.dilationWidth,d=r.effectiveFilterDepth,_=r.effectiveFilterHeight,h=r.effectiveFilterWidth,f=d-1-r.padInfo.front,y=h-1-r.padInfo.left,m=_-1-r.padInfo.top,g=Jr(t.shape,"float32"),b=1/(i*s*l),v=this.bufferSync(e),E=0;E=r.outDepth||Math.floor(C)!==C))for(var L=0;L<_;L+=u){var B=(x+L)/o;if(!(B<0||B>=r.outHeight||Math.floor(B)!==B))for(var I=0;I=r.outWidth||Math.floor(N)!==N||(T+=v.get(E,C,B,N,k))}}}g.set(T*b,E,S,R,w,k)}return g.toTensor()},t.prototype.maxPool3d=function(e,t){return op(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,t){for(var r=Jr(t.outShape,"int32"),n=t.strideDepth,o=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,s=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,_=t.padInfo.top,h=t.padInfo.left,f=this.bufferSync(e),y=0;y=O&&(O=F,C=B*u*p+N*u+P)}r.set(C,y,g,k,A,m)}}}return r.toTensor()},t.prototype.maxPool3dBackprop=function(e,t,r,n){op([t,r],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(t,n),a=n.strideDepth,i=n.strideHeight,s=n.strideWidth,l=n.dilationDepth,c=n.dilationHeight,u=n.dilationWidth,p=n.effectiveFilterDepth,d=n.effectiveFilterHeight,_=n.effectiveFilterWidth,h=p-1-n.padInfo.front,f=_-1-n.padInfo.left,y=d-1-n.padInfo.top,m=Jr(t.shape,"float32"),g=this.bufferSync(o),b=this.bufferSync(e),v=0;v=n.outDepth||Math.floor(O)!==O))for(var C=0;C=n.outHeight||Math.floor(L)!==L))for(var B=0;B<_;B+=u){var I=(x+B)/s;if(!(I<0||I>=n.outWidth||Math.floor(I)!==I)){var N=p*d*_-1-g.get(v,O,L,I,E)===T*d*_+C*_+B?1:0;0!==N&&(D+=b.get(v,O,L,I,E)*N)}}}}m.set(D,v,k,S,R,E)}return m.toTensor()},t.prototype.cast=function(e,t){return mo(e,t,this)},t.prototype.reshape=function(e,t){return go(e,t)},t.prototype.avgPool=function(e,t){return op(e,"avgPool"),this.pool(e,t,"avg").toFloat()},t.prototype.resizeBilinear=function(e,t,r,n){op(e,"resizeBilinear");for(var o=e.shape,a=o[0],i=o[1],s=o[2],l=o[3],c=this.readSync(e.dataId),u=new Float32Array(B([a,t,r,l])),p=[n&&t>1?i-1:i,n&&r>1?s-1:s],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],_=0,h=p[0]/d[0],f=p[1]/d[1],y=0;y1?a-1:a,r&&u>1?i-1:i],_=[r&&c>1?c-1:c,r&&u>1?u-1:u],h=d[0]/_[0],f=d[1]/_[1],y=this.readSync(e.dataId),m=0,g=0;g1?i-1:i,n&&r>1?s-1:s],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],_=p[0]/d[0],h=p[1]/d[1],f=0,y=0;y1?a-1:a,r&&u>1?i-1:i],h=[r&&c>1?c-1:c,r&&u>1?u-1:u],f=_[0]/h[0],y=_[1]/h[1],m=1/f,g=1/y,b=2*Math.ceil(m)+2,v=2*Math.ceil(g)+2,E=0;E=c)){var N=k+I*e.strides[1],M=I*f;if(S===Math.min(a-1,r?Math.round(M):Math.floor(M)))for(var P=0;P=u)){var W=N+F*e.strides[2],H=F*y;x===Math.min(i-1,r?Math.round(H):Math.floor(H))&&(L+=d[W+C])}}}}p[D+C]=L}return kr(p,t.shape,t.dtype)},t.prototype.batchNormalization=function(e,t,r,n,o,a){op([e,t,r,o,a],"batchNorm");for(var i=this.readSync(e.dataId),s=this.readSync(t.dataId),l=this.readSync(r.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),u=a?this.readSync(a.dataId):new Float32Array([0]),p=new Float32Array(i.length),d=u.length,_=c.length,h=l.length,f=s.length,y=0,m=0,g=0,b=0,v=0;v=d&&(y=0),m>=f&&(m=0),g>=_&&(g=0),b>=h&&(b=0);return kr(p,e.shape)},t.prototype.localResponseNormalization4D=function(e,t,r,n,o){op(e,"localResponseNormalization4D");var a=e.shape[3],i=a-1,s=this.readSync(e.dataId),l=e.size,c=new Float32Array(l);function u(e){for(var r=e%a,n=e-r+Math.max(0,r-t),o=e-r+Math.min(r+t,i),l=0;n<=o;n++){var c=s[n];l+=c*c}return l}for(var p=0;p=0&&a[i]1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+t}));for(var n=e.shape[0],o=e.shape[1],a=e.shape[2],i=e.shape[3],s=o*t,l=a*t,c=i/(t*t),u=this.readSync(e.dataId),p=new Float32Array(n*s*l*c),d=0,_=0;_=s))for(var x=d>1?(R-k)*(l-1)/(d-1):0,D=_>1?(w-S)*(c-1)/(_-1):0,T=0;T1?k*(l-1)+T*x:.5*(k+R)*(l-1);if(O<0||O>l-1)for(var C=0;C<_;C++)for(var L=0;L1?S*(c-1)+C*D:.5*(S+w)*(c-1))<0||G>c-1)for(L=0;L1?S*(c-1)+C*D:.5*(S+w)*(c-1))<0||G>c-1)for(L=0;L=e.size/s)throw new Error("Invalid indices: "+_+" does not index into "+e.shape);for(var m=0;m=n/o)throw new Error("Invalid indices: "+f+" does not index into "+r);for(var b=0;b0,(function(){return"scheme must not be an empty string."}));var n=e.getInstance();T(null==n.managers[t],(function(){return"A model store manager is already registered for scheme '"+t+"'."})),n.managers[t]=r},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function Op(e){if(-1===e.indexOf(Dp))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Tp.getSchemes().join(","));return{scheme:e.split(Dp)[0],path:e.split(Dp)[1]}}function Cp(e,t,r){return void 0===r&&(r=!1),p(this,void 0,void 0,(function(){var n,o,a,i,s,l,c,u,p;return d(this,(function(d){switch(d.label){case 0:return T(e!==t,(function(){return"Old path and new path are the same: '"+e+"'"})),T((n=xp.getLoadHandlers(e)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+e+"."})),T(n.length<2,(function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+e+"."})),o=n[0],T((a=xp.getSaveHandlers(t)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+t+"."})),T(a.length<2,(function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."})),i=a[0],s=Op(e).scheme,l=Op(e).path,c=s===Op(e).scheme,[4,o.load()];case 1:return u=d.sent(),r&&c?[4,Tp.getManager(s).removeModel(l)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,i.save(u)];case 4:return p=d.sent(),!r||c?[3,6]:[4,Tp.getManager(s).removeModel(l)];case 5:d.sent(),d.label=6;case 6:return[2,p.modelArtifactsInfo]}}))}))}var Lp="models_store",Bp="model_info_store";function Ip(){if(!f().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window||self,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Np(e){var t=e.result;t.createObjectStore(Lp,{keyPath:"modelPath"}),t.createObjectStore(Bp,{keyPath:"modelPath"})}var Mp=function(){function e(e){if(this.indexedDB=Ip(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return p(this,void 0,void 0,(function(){return d(this,(function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]}))}))},e.prototype.load=function(){return p(this,void 0,void 0,(function(){return d(this,(function(e){return[2,this.databaseAction(this.modelPath)]}))}))},e.prototype.databaseAction=function(e,t){var r=this;return new Promise((function(e,n){var o=r.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Np(o)},o.onsuccess=function(){var a=o.result;if(null==t){var i=a.transaction(Lp,"readonly"),s=i.objectStore(Lp).get(r.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),n(new Error("Cannot find model with path '"+r.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return a.close(),n(s.error)},i.oncomplete=function(){return a.close()}}else{var l,c=Ap(t),u=a.transaction(Bp,"readwrite"),p=u.objectStore(Bp),d=p.put({modelPath:r.modelPath,modelArtifactsInfo:c});d.onsuccess=function(){var o=(l=a.transaction(Lp,"readwrite")).objectStore(Lp).put({modelPath:r.modelPath,modelArtifacts:t,modelArtifactsInfo:c});o.onsuccess=function(){return e({modelArtifactsInfo:c})},o.onerror=function(e){var t=(p=u.objectStore(Bp)).delete(r.modelPath);t.onsuccess=function(){return a.close(),n(o.error)},t.onerror=function(e){return a.close(),n(o.error)}}},d.onerror=function(e){return a.close(),n(d.error)},u.oncomplete=function(){null==l?a.close():l.oncomplete=function(){return a.close()}}}},o.onerror=function(e){return n(o.error)}}))},e.URL_SCHEME="indexeddb://",e}(),Pp=function(e){return f().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Mp.URL_SCHEME)?(t=e.slice(Mp.URL_SCHEME.length),new Mp(t)):null;var t};xp.registerSaveRouter(Pp),xp.registerLoadRouter(Pp);var Fp=function(){function e(){this.indexedDB=Ip()}return e.prototype.listModels=function(){return p(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,r){var n=e.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=function(){return Np(n)},n.onsuccess=function(){var e=n.result,o=e.transaction(Bp,"readonly"),a=o.objectStore(Bp).getAll();a.onsuccess=function(){for(var e={},r=0,n=a.result;r0,(function(){return"promises must be a none empty array"}))}(e),function(e,t){T(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+e})),T(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+t})),T(t>=e,(function(){return"startFraction must be no more than endFraction, but got startFraction "+e+" and endFraction "+t}))}(r=null==r?0:r,n=null==n?1:n);var o=0;return Promise.all(e.map((function(a){return a.then((function(a){var i=r+ ++o/e.length*(n-r);return t(i),a})),a})))}function td(e,t){return p(this,void 0,void 0,(function(){var r,n,o,a,i,s,l,c,u;return d(this,(function(p){switch(p.label){case 0:return null==t&&(t={}),r=null==t.fetchFunc?f().platform.fetch:t.fetchFunc,n=e.map((function(e){return r(e,t.requestInit,{isBinary:!0})})),o=0,a=.5,null!=t.onProgress?[3,2]:[4,Promise.all(n)];case 1:return i=p.sent(),[3,4];case 2:return[4,ed(n,t.onProgress,o,a)];case 3:i=p.sent(),p.label=4;case 4:return s=i.map((function(e){return e.arrayBuffer()})),l=.5,c=1,null!=t.onProgress?[3,6]:[4,Promise.all(s)];case 5:return u=p.sent(),[3,8];case 6:return[4,ed(s,t.onProgress,l,c)];case 7:u=p.sent(),p.label=8;case 8:return[2,u]}}))}))}function rd(e){var t=this;return function(r,n,o){return void 0===n&&(n=""),p(t,void 0,void 0,(function(){var t,a,i,s,l,c,u,p,_,h;return d(this,(function(d){switch(d.label){case 0:if(t=r.map((function(){return!1})),a={},i=null!=o?o.map((function(){return!1})):[],s=[],r.forEach((function(e,r){var n=0;e.weights.forEach((function(e){var l="quantization"in e?e.quantization.dtype:e.dtype,c=bp[l]*B(e.shape),u=function(){t[r]=!0,null==a[r]&&(a[r]=[]),a[r].push({manifestEntry:e,groupOffset:n,sizeBytes:c})};null!=o?o.forEach((function(t,r){t===e.name&&(u(),i[r]=!0)})):u(),s.push(e.name),n+=c}))})),!i.every((function(e){return e})))throw l=o.filter((function(e,t){return!i[t]})),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return c=t.reduce((function(e,t,r){return t&&e.push(r),e}),[]),u=[],c.forEach((function(e){r[e].paths.forEach((function(e){var t=n+(n.endsWith("/")?"":"/")+e;u.push(t)}))})),[4,e(u)];case 1:return p=d.sent(),_={},h=0,c.forEach((function(e){for(var t=r[e].paths.length,n=0,o=0;o0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(e)&&T(2===e.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+e.length+")."})),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}return e.prototype.save=function(e){return p(this,void 0,void 0,(function(){var t,r,n,o;return d(this,(function(a){switch(a.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=(0,l.default)({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:r},t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,t)];case 1:if((o=a.sent()).ok)return[2,{modelArtifactsInfo:Ap(e),responses:[o]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}}))}))},e.prototype.load=function(){return p(this,void 0,void 0,(function(){var e,t,r,n,o,a,i,s,l,c,u,p;return d(this,(function(d){switch(d.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(e=d.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+e.status+". Please verify this URL points to the model JSON of the model to load.");d.label=2;case 2:return d.trys.push([2,4,,5]),[4,e.json()];case 3:return t=d.sent(),[3,5];case 4:throw d.sent(),r="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?r+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":r+=" Please make sure the server is serving valid JSON for this request.",new Error(r);case 5:if(n=t.modelTopology,o=t.weightsManifest,a=t.generatedBy,i=t.convertedBy,s=t.format,l=t.userDefinedMetadata,null==n&&null==o)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==o?[3,7]:[4,this.loadWeights(o)];case 6:p=d.sent(),c=p[0],u=p[1],d.label=7;case 7:return[2,{modelTopology:n,weightSpecs:c,weightData:u,userDefinedMetadata:l,generatedBy:a,convertedBy:i,format:s}]}}))}))},e.prototype.loadWeights=function(e){return p(this,void 0,void 0,(function(){var t,r,n,o,a,i,s,l,c,u,p;return d(this,(function(d){switch(d.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,r=function(e){var t=e.lastIndexOf("/"),r=e.lastIndexOf("?");return[e.substring(0,t)+"/",r>t?e.substring(r):""]}(t),n=r[0],o=r[1],a=this.weightPathPrefix||n,i=[],s=0,l=e;s0&&Number.isInteger(r),(function(){return"If provided, numClasses must be a positive integer, but got "+r})),T(1===n.rank,(function(){return"Expected the rank of labels to be 1, but got "+n.rank})),T(1===o.rank,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),T(n.shape[0]===o.shape[0],(function(){return"Mismatch in the number of examples: "+n.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."})),T(r>0&&Number.isInteger(r),(function(){return"numClasses is required to be a positive integer, but got "+r}));var a=cn(n.asType("int32"),r),i=cn(o.asType("int32"),r);return a.transpose().matMul(i).asType("int32")}}),dd=Object.freeze({confusionMatrix:pd});t.math=dd;var _d=dr({fromPixels_:function(e,t){if(void 0===t&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var r=!1,n=!1,o=!1,a=!1,i=!1;if(e.data instanceof Uint8Array)r=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)n=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)o=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else{if(null==e.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);i=!0}if(o&&o&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the